Exemplo n.º 1
0
        void context_PostRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpContext   context = HttpContext.Current;
            UploadSession session = SlickUploadContext.CurrentUploadSessionInternal;

            if (session != null && session.State != UploadState.Uploading)
            {
                SlickUploadContext.CommitSession(session);
            }

            ComponentHelper.EnsureScriptsRendered();

            // We're set to use session state, but we didn't create a cookie. Ensure we do.
            if (HttpContext.Current.Items["EnsureSessionCreated"] != null)
            {
                HttpCookie cookie = context.Response.Cookies[_sessionCookieName];

                if (cookie == null)
                {
                    cookie = new HttpCookie(_sessionCookieName, context.Session.SessionID)
                    {
                        Path = "/", HttpOnly = true
                    }
                }
                ;
                else
                {
                    cookie.Value = context.Session.SessionID;
                }

                context.Items["SlickUploadSessionStateFixCookie"] = cookie;
            }
        }
Exemplo n.º 2
0
        public void PartData(ref byte[] data, int start, int length)
        {
            if (length > 0)
            {
                // If it's a UploadedFile
                if (_currentStream != null)
                {
                    if (_currentStream != Stream.Null)
                    {
                        _currentStream.Write(data, start, length);
                    }

                    _fileLength += length;
                }
                else
                {
                    string value = _httpRequest.ContentEncoding.GetString(data, start, length);

                    _textParts.Append(_httpRequest.ContentEncoding.GetString(data, start, length));

                    string currentValue = _httpRequest.Form[_httpRequest.Form.Count - 1];

                    if (string.IsNullOrEmpty(currentValue))
                    {
                        currentValue = value;
                    }
                    else
                    {
                        currentValue += value;
                    }

                    _httpRequest.Form[_httpRequest.Form.AllKeys[_httpRequest.Form.Count - 1]] = currentValue;
                }

                // TODO: fix ?

                /*if (SlickUploadConfiguration.StatusManager.UpdateInterval == 0 || DateTime.Now.Subtract(_lastDisconnectCheck).TotalSeconds > SlickUploadConfiguration.StatusManager.UpdateInterval)
                 * {
                 *  UploadStatus currentStatus = HttpUploadModule.StatusManager.GetUploadStatus(this._uploadStatus.UploadId);
                 *
                 *  if (currentStatus != null && currentStatus.State == UploadState.Terminated)
                 *      throw new UploadException(currentStatus.Reason);
                 *
                 *  _lastDisconnectCheck = DateTime.Now;
                 * }*/

                _request.Position = _requestStream.Position;

                SlickUploadContext.UpdateRequest(_request, false);
            }
        }
Exemplo n.º 3
0
        /*long InitMaxRequestLength(HttpContext context)
         * {
         *  long _maxRequestLength;
         *
         *  long slickUploadMaxRequestLength = 0;
         *  string slickUploadMaxRequestLengthString = UploadParser["maxUploadRequestLength"];
         *
         *  if (!long.TryParse(slickUploadMaxRequestLengthString, out slickUploadMaxRequestLength))
         *      slickUploadMaxRequestLength = -1;
         *
         *  if (slickUploadMaxRequestLength > 0)
         *  {
         *      _maxRequestLength = slickUploadMaxRequestLength;
         *  }
         *  else
         *  {
         *      long maxAllowedContentLength = GetMaxAllowedContentLength(context);
         *      long maxRequestLength = GetMaxRequestLength(context);
         *
         *      if (maxAllowedContentLength > 0)
         *          _maxRequestLength = (maxAllowedContentLength < maxRequestLength ? maxAllowedContentLength : maxRequestLength);
         *      else
         *          _maxRequestLength = maxRequestLength;
         *
         *      if (_maxRequestLength <= 0)
         *          _maxRequestLength = -1;//4096 * 1024;
         *  }
         *
         *  return _maxRequestLength;
         * }
         *
         * long GetMaxRequestLength(HttpContext context)
         * {
         *  long maxRequestLength = -1;
         *
         *  object httpRuntimeConfig = null;
         *
         *  try
         *  {
         *      httpRuntimeConfig = context.GetSection("system.web/httpRuntime");
         *  }
         *  catch
         *  { }
         *  //_maxRequestLength = -1;
         *
         *  if (httpRuntimeConfig != null)
         *      maxRequestLength = ((HttpRuntimeSection)httpRuntimeConfig).MaxRequestLength * 1024;
         *
         *  return maxRequestLength;
         * }
         *
         * long GetMaxAllowedContentLength(HttpContext context)
         * {
         *  long maxAllowedContentLength = 0;
         *
         *  try
         *  {
         *      Assembly a = Assembly.Load("Microsoft.Web.Administration, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
         *
         *      if (a != null)
         *      {
         *          Type man = a.GetType("Microsoft.Web.Administration.WebConfigurationManager");
         *
         *          object requestFilteringSection = man.InvokeMember("GetSection",
         *                                                         BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null,
         *                                                         new object[] { "system.webServer/security/requestFiltering" });
         *
         *          object requestLimitsSection = requestFilteringSection.GetType().InvokeMember("GetChildElement",
         *                                                                                       BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, requestFilteringSection,
         *                                                                                       new object[] { "requestLimits" });
         *
         *          object maxAllowedContentLengthAttribute = requestLimitsSection.GetType().InvokeMember("GetAttributeValue",
         *                                                                                                BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, requestLimitsSection,
         *                                                                                                new object[] { "maxAllowedContentLength" });
         *
         *          maxAllowedContentLength = (long)maxAllowedContentLengthAttribute;
         *      }
         *  }
         *  catch
         *  { }
         *
         *  return maxAllowedContentLength;
         * }*/


        void CleanupThread()
        {
            try
            {
                // TODO: log

                foreach (UploadSession session in SlickUploadContext.SessionStorageProvider.GetStaleSessions(DateTime.Now.AddSeconds(-SlickUploadContext.Config.SessionStorageProvider.StaleTimeout)))
                {
                    SlickUploadContext.RollbackSession(session);
                }

                // TODO: log
            }
            catch
            {
                // TODO: log
            }
        }
Exemplo n.º 4
0
        /// <inheritdoc />
        public void ProcessRequest(HttpContext context)
        {
            string uploadRequestId = context.Request.QueryString["uploadRequestId"];
            string uploadSessionId = context.Request.QueryString["uploadSessionId"];

            if (string.IsNullOrEmpty(uploadRequestId))
            {
                throw new HttpException(500, "uploadRequestId parameter is required.");
            }

            if (string.IsNullOrEmpty(uploadSessionId))
            {
                throw new HttpException(500, "uploadSessionId parameter is required.");
            }

            UploadRequest request = SlickUploadContext.SessionStorageProvider.GetRequest(uploadSessionId, uploadRequestId);

            SlickUploadContext.CancelRequest(request);
        }
Exemplo n.º 5
0
        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;

            //System.Diagnostics.Debug.WriteLine(context.Request.Url.ToString() + " - " + (context.Request.Cookies.Count > 0 ? context.Request.Cookies[0].Value : "null"));

            if (IsUploadRequest(context.Request))
            {
                if (context.Trace != null && context.Trace.IsEnabled)
                {
                    throw new HttpException("Trace must be disabled for SlickUpload to intercept upload requests.");
                }

                if ((DateTime.Now - _lastCleanupDate).TotalSeconds > SlickUploadContext.Config.SessionStorageProvider.StaleTimeout)
                {
                    lock (_cleanupThreadLock)
                    {
                        if ((DateTime.Now - _lastCleanupDate).TotalSeconds > SlickUploadContext.Config.SessionStorageProvider.StaleTimeout)
                        {
                            _lastCleanupDate = DateTime.Now;

                            Thread cleanupThread = new Thread(CleanupThread);

                            cleanupThread.Start();
                        }
                    }
                }

                string uploadSessionId = context.Request.QueryString["uploadSessionId"];

                // Generate an uploadSessionId if none was specified
                if (string.IsNullOrEmpty(uploadSessionId))
                {
                    uploadSessionId = Guid.NewGuid().ToString();
                }

                UploadSession session = SlickUploadContext.SessionStorageProvider.GetSession(uploadSessionId);

                if (session == null)
                {
                    session = new UploadSession(uploadSessionId, context.Request.QueryString["uploadProfile"]);

                    session.State = UploadState.Uploading;

                    SlickUploadContext.SessionStorageProvider.SaveSession(session, true);
                }

                SlickUploadContext.CurrentUploadSessionInternal = session;

                string uploadRequestId = context.Request.QueryString["uploadRequestId"];

                // Generate an uploadRequestId if none was specified
                if (string.IsNullOrEmpty(uploadRequestId))
                {
                    uploadRequestId = Guid.NewGuid().ToString();
                }

                UploadHttpRequest httpRequest = new UploadHttpRequest(context);
                UploadRequest     request     = new UploadRequest(uploadSessionId, uploadRequestId, httpRequest.ContentLength, context.Request.QueryString["uploadProfile"]);

                bool isCalculateSize = (context.Request.QueryString["handlerType"] == "calculatesize");

                try
                {
                    SlickUploadContext.CurrentUploadRequest = request;

                    if (httpRequest.ContentLength > request.UploadProfile.MaxRequestLengthBytes || (httpRequest.ContentLength < 0 && request.UploadProfile.MaxRequestLength > 4097152))
                    {
                        //SimpleLogger.Log("Request too big... aborting");

                        request.ErrorType = UploadErrorType.MaxRequestLengthExceeded;

                        context.ApplicationInstance.CompleteRequest();
                    }

                    if (request.ErrorType == UploadErrorType.None && !(request.UploadFilter == null || request.UploadFilter.ShouldHandleRequest(httpRequest)))
                    {
                        request.ErrorType = UploadErrorType.UploadFilter;
                    }

                    if (request.ErrorType != UploadErrorType.None)
                    {
                        request.State = UploadState.Error;
                    }
                    else if (isCalculateSize)
                    {
                        request.State = UploadState.Initializing;
                    }
                    else
                    {
                        request.State = UploadState.Uploading;
                    }
                }
                catch (Exception ex)
                {
                    request.State     = UploadState.Error;
                    request.ErrorType = UploadErrorType.Other;
                    request.Error     = ex;

                    throw;
                }
                finally
                {
                    bool hasExistingRequest = false;

                    try
                    {
                        hasExistingRequest = (SlickUploadContext.SessionStorageProvider.GetRequest(uploadSessionId, request.UploadRequestId) != null);
                    }
                    catch
                    { }

                    if (!hasExistingRequest)
                    {
                        SlickUploadContext.InsertRequest(request);
                    }
                    else
                    {
                        SlickUploadContext.UpdateRequest(request, true);
                    }
                }

                if (request.ErrorType == UploadErrorType.None)
                {
                    if (isCalculateSize)
                    {
                        httpRequest.Worker.CloseConnection();
                        context.ApplicationInstance.CompleteRequest();

                        return;
                    }

                    context.Server.ScriptTimeout = request.UploadProfile.ExecutionTimeout;

                    MimeUploadHandler handler = null;

                    try
                    {
                        handler = new MimeUploadHandler(httpRequest, request);

                        handler.ProcessRequest();

                        // TODO: should we check the session's state here, and cancel?
                        // TODO: maybe no, because MimeUploadHandler checks on part end and throws cancelled if it should
                        request.State = UploadState.Complete;
                    }
                    catch (Exception ex)
                    {
                        if (handler != null)
                        {
                            try
                            {
                                handler.CancelParse();
                            }
                            catch
                            {
                                // TODO: what do we do with this exception?
                            }
                        }

                        request.State = UploadState.Error;

                        if (ex is UploadDisconnectedException)
                        {
                            request.ErrorType = UploadErrorType.Disconnected;
                        }
                        else if (ex is UploadCancelledException)
                        {
                            request.ErrorType = UploadErrorType.Cancelled;
                        }
                        else
                        {
                            request.ErrorType = UploadErrorType.Other;

                            request.Error = ex;
                        }

                        try
                        {
                            SlickUploadContext.CleanupRequest(request);
                        }
                        catch
                        {
                            // TODO: what do we do with this exception?
                        }

                        // If we were disconnected, let everything pass through. Otherwise, rethrow it.
                        if (ex is UploadDisconnectedException || ex is UploadCancelledException)
                        {
                            httpRequest.Worker.CloseConnection();
                            context.ApplicationInstance.CompleteRequest();
                        }
                        else
                        {
                            throw;
                        }
                    }
                    finally
                    {
                        SlickUploadContext.UpdateRequest(request, true);
                    }
                }
            }
        }
Exemplo n.º 6
0
        /*UploadSettings LoadUploadSettings(string textParts)
         * {
         *  // TODO: parse text parts for settings
         * }*/

        public void BeginPart(NameValueCollection headers)
        {
            // Create a part for the file, or null if this isn't a valid file
            if (headers != null)
            {
                _currentFile = CreateUploadedFile(headers);
            }
            else
            {
                _currentFile = CreateSingleUploadedFile();
            }

            if (_currentFile != null)
            {
                //if (UploadSettings == null)
                //    LoadUploadSettings(_textParts.ToString());

                //SimpleLogger.Log("Starting file part", _uploadStatus.UploadId);
                //SimpleLogger.Log(_currentFile, _uploadStatus.UploadId);

                // Create a stream for the file
                if (_request.UploadFilter == null || _request.UploadFilter.ShouldHandleFile(_httpRequest, _currentFile))
                {
                    _currentStream = _request.UploadStreamProvider.GetWriteStream(_currentFile);
                }
                else
                {
                    _currentStream = Stream.Null;
                }

                _fileLength = 0;

                _request._uploadedFilesInternal.Add(_currentFile);

                SlickUploadContext.UpdateRequest(_request, true);
            }
            else
            {
                //SimpleLogger.Log("Starting non-file part", _uploadStatus.UploadId);

                // Write out the boundary start
                _textParts.Append(_httpRequest.ContentEncoding.GetString(_boundary) + "\r\n");

                // Write out the headers as textparts
                for (int i = 0; i < headers.Count; i++)
                {
                    _textParts.Append(headers.Keys[i] + ": " + headers[i] + "\r\n");
                }

                _textParts.Append("\r\n");

                // Add to our form collection
                string contentDisposition = headers["content-disposition"];

                if (contentDisposition != null)
                {
                    string[] dispositionParts = MimeHelper.QuotedSemiSplit(contentDisposition);

                    if (dispositionParts.Length == 2 && dispositionParts[1].Trim().StartsWith("name="))
                    {
                        _httpRequest.Form.Add(MimeHelper.GetParts(dispositionParts[1], '=')[1].Replace("\"", string.Empty), null);
                    }
                }
            }
        }