/// <summary>
 /// Initializes a new instance of the <see cref="HttpRequest" /> class.
 /// </summary>
 public HttpRequest()
 {
     _cookies = new HttpCookieCollection<IHttpCookie>();
     _files = new HttpFileCollection();
     _queryString = new ParameterCollection();
     _form = new ParameterCollection();
 }
Beispiel #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpRequest" /> class.
 /// </summary>
 public HttpRequest()
 {
     this.cookies     = new HttpCookieCollection <IHttpCookie>();
     this.files       = new HttpFileCollection();
     this.queryString = new ParameterCollection();
     this.form        = new ParameterCollection();
 }
 public HttpRequest()
 {
     _cookies     = new HttpCookieCollection <IHttpCookie>();
     _files       = new HttpFileCollection();
     _queryString = new ParameterCollection();
     _form        = new ParameterCollection();
 }
        private static Dictionary <string, IHttpPostedFile[]> GetHttpPostedFileDictionary(IHttpFileCollection files)
        {
            if (files.Count == 0)
            {
                return(_emptyDictionary);
            }

            // build up the 1:many file mapping
            List <KeyValuePair <string, IHttpPostedFile> > mapping = new List <KeyValuePair <string, IHttpPostedFile> >();

            string[] allKeys = files.AllKeys;
            for (int i = 0; i < files.Count; i++)
            {
                string key = allKeys[i];
                if (key != null)
                {
                    mapping.Add(new KeyValuePair <string, IHttpPostedFile>(key, files[i]));
                }
            }

            // turn the mapping into a 1:many dictionary
            var grouped = mapping.GroupBy(el => el.Key, el => el.Value, StringComparer.OrdinalIgnoreCase);

            return(grouped.ToDictionary(g => g.Key, g => g.ToArray(), StringComparer.OrdinalIgnoreCase));
        }
Beispiel #5
0
        /// <summary>
        /// 执行与释放或重置非托管资源相关的应用程序定义的任务。
        /// </summary>
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }
            if (_headers != null)
            {
                _headers.Clear();
                _headers = null;
            }
            if (_cookies != null)
            {
                _cookies.Clear();
                _cookies = null;
            }
            if (_queryString != null)
            {
                _queryString.Clear();
                _queryString = null;
            }
            if (_form != null)
            {
                _form.Clear();
                _form = null;
            }
            if (_serverVariables != null)
            {
                _serverVariables.Clear();
                _serverVariables = null;
            }
            if (_params != null)
            {
                _params.Clear();
                _params = null;
            }
            if (_files != null)
            {
                _files.Dispose();
                _files = null;
            }
            if (_inputStream != null)
            {
                try { _inputStream.Dispose(); } catch { }
                _inputStream = null;
            }
            _acceptTypes       = null;
            _userAgent         = null;
            _userLanguages     = null;
            _contentEncoding   = null;
            _contentType       = null;
            _rawUrl            = null;
            _url               = null;
            _urlReferrer       = null;
            _httpMethod        = null;
            _protocolVersion   = null;
            _localEndPoint     = null;
            _remoteEndPoint    = null;
            _userHostAddress   = null;
            _userHostName      = null;
            _binaryReadHandler = null;

            _disposed = true;
        }
Beispiel #6
0
        void ParseMultiPart(string contentType, byte[] buffer, System.Text.Encoding encoding)
        {
            int boundaryIndex = contentType.IndexOf("boundary=", System.StringComparison.OrdinalIgnoreCase);

            if (boundaryIndex == -1)
            {
                return;
            }
            _form = new System.Collections.Specialized.NameValueCollection();
            var files = new HttpFileCollection();

            _files = files;

            string boundary = contentType.Substring(boundaryIndex + "boundary=".Length);

            byte[] spliter = System.Text.Encoding.ASCII.GetBytes(boundary + "\r\nContent-Disposition: form-data; name=\"");
            //byte[] endFlags = System.Text.Encoding.ASCII.GetBytes(boundary + "--");
            bool ended    = false;
            int  index    = 0;
            int  endIndex = -1;

            while (!ended && index < buffer.Length - 1)
            {
                index   += spliter.Length + 2;
                endIndex = BinarySearch(buffer, index, 34);
                if (endIndex == -1)
                {
                    break;
                }
                string name = encoding.GetString(buffer, index, endIndex - index);
                index = endIndex + 1;
                bool   isFile            = false;
                string filename          = null;
                string contentTypeHeader = null;
                while (true)
                {
                    if (buffer[index] == 59)  //; 还有其它值
                    {
                        index   += 2;
                        endIndex = BinarySearch(buffer, index, 61);//=
                        if (endIndex == -1)
                        {
                            ended = true;
                            break;
                        }
                        string name2 = encoding.GetString(buffer, index, endIndex - index);
                        index    = endIndex + 2;//="
                        endIndex = BinarySearch(buffer, index, 34);
                        if (endIndex == -1)
                        {
                            ended = true;
                            break;
                        }
                        string value2 = encoding.GetString(buffer, index, endIndex - index);
                        index = endIndex + 1; //\r
                                              //Console.WriteLine("{0}=[{1}]", name2, value2);
                        if (string.Equals(name2, "filename", System.StringComparison.OrdinalIgnoreCase))
                        {
                            isFile   = true;
                            filename = value2;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                if (ended)
                {
                    break;
                }
                index++;                     //\n

                if (buffer[index + 1] != 13) //headers
                {
                    index++;
                    endIndex = BinarySearch(buffer, index, 58);//:
                    if (endIndex == -1)
                    {
                        break;
                    }
                    string headerName = System.Text.Encoding.ASCII.GetString(buffer, index, endIndex - index);
                    index    = endIndex + 2;
                    endIndex = BinarySearch(buffer, index, 13);//\r
                    if (endIndex == -1)
                    {
                        break;
                    }
                    string headerValue = System.Text.Encoding.ASCII.GetString(buffer, index, endIndex - index);
                    index = endIndex + 1;//\r
                    if (string.Equals(headerName, "Content-Type", System.StringComparison.OrdinalIgnoreCase))
                    {
                        contentTypeHeader = headerValue;
                    }
                }
                index += 3;
                if (isFile)
                {
                    endIndex = BinarySearch(buffer, index, 13, new byte[] { 13, 10, 45, 45, 45, 45 });
                }
                else
                {
                    endIndex = BinarySearch(buffer, index, 13, new byte[] { 13, 10 });
                }
                if (endIndex == -1)
                {
                    break;
                }
                int valueLength = endIndex - index;
                if (isFile)
                {
                    _form.Add(name, filename);
                    System.IO.MemoryStream inputStream = null;
                    if (valueLength > 0)
                    {
                        inputStream          = new System.IO.MemoryStream(valueLength);
                        inputStream.Position = 0;
                        inputStream.Write(buffer, index, valueLength);
                        inputStream.Position = 0;
                    }
                    if (string.IsNullOrEmpty(contentType))
                    {
                        contentType = "application/octet-stream";
                    }
                    HttpPostedFile file = new HttpPostedFile(inputStream, filename, valueLength, contentTypeHeader);
                    files.Add(name, file);
                }
                else
                {
                    byte[] valueBuffer = new byte[valueLength];
                    System.Array.Copy(buffer, index, valueBuffer, 0, valueLength);
                    _form.Add(name, encoding.GetString(valueBuffer));
                }
                index = endIndex + 2;
            }
        }
        /// <summary>
        /// Encrypt values into a cookie.
        /// </summary>
        /// <param name="cleartext">The decrypted string (cleartext).</param>
        /// <returns>The encrypted string (ciphertext).</returns>

        /*public void EncryptStateInCookie(IDictionary cleartext)
         * {
         *      StringBuilder sb = new StringBuilder();
         *      IEnumerator i = new ArrayList(cleartext).GetEnumerator();
         * bool first = true;
         *      while (i.MoveNext())
         *      {
         *              try
         *              {
         *                  if (!first)
         *                  {
         *      sb.Append("&");
         *                  } else
         *                  {
         *                      first = false;
         *                  }
         *                  DictionaryEntry entry = (DictionaryEntry) i.Current;
         *                      string name = Esapi.Encoder().EncodeForUrl(entry.Key.ToString());
         *                      string cookieValue = Esapi.Encoder().EncodeForUrl(entry.Value.ToString());
         *                      sb.Append(name + "=" + cookieValue);
         *
         *              }
         *              catch (EncodingException e)
         *              {
         *                      // continue
         *              }
         *      }
         *      // FIXME: AAA - add a check to see if cookie length will exceed 2K limit
         *      string encrypted = Esapi.Encryptor().Encrypt(sb.ToString());
         *      this.SafeAddCookie("state", encrypted, - 1, null, null);
         * }*/


        // FIXME: No progress indicator.
        /// <summary> Uses the .NET HttpFileCollection object. to parse the multipart HTTP request
        /// and extract any files therein.
        /// </summary>
        /// <param name="tempDir">
        /// The temporary directory where the file is written.
        /// </param>
        /// <param name="finalDir">
        /// The final directory where the file will be written.
        /// </param>
        /// <seealso cref="Owasp.Esapi.Interfaces.IHttpUtilities.GetSafeFileUploads(FileInfo, FileInfo)">
        /// </seealso>
        public IList GetSafeFileUploads(FileInfo tempDir, FileInfo finalDir)
        {
            ArrayList newFiles = new ArrayList();

            try
            {
                if (!tempDir.Exists)
                {
                    tempDir.Create();
                }
                if (!finalDir.Exists)
                {
                    finalDir.Create();
                }
                IHttpFileCollection fileCollection = ((Authenticator)Esapi.Authenticator()).CurrentRequest.Files;
                if (fileCollection.AllKeys.Length == 0)
                {
                    throw new ValidationUploadException("Upload failed", "Not a multipart request");
                }

                // No progress meter yet
                foreach (string key in fileCollection.AllKeys)
                {
                    IHttpPostedFile file = fileCollection[key];
                    if (file.FileName != null && !file.FileName.Equals(""))
                    {
                        String[] fparts   = Regex.Split(file.FileName, "[\\/\\\\]");
                        String   filename = fparts[fparts.Length - 1];
                        if (!Esapi.Validator().IsValidFileName("upload", filename, false))
                        {
                            throw new ValidationUploadException("Upload only simple filenames with the following extensions " + Esapi.SecurityConfiguration().AllowedFileExtensions, "Invalid filename for upload");
                        }
                        logger.LogCritical(ILogger_Fields.SECURITY, "File upload requested: " + filename);
                        FileInfo f = new FileInfo(finalDir.ToString() + "\\" + filename);
                        if (f.Exists)
                        {
                            String[] parts     = Regex.Split(filename, "\\./");
                            String   extension = "";
                            if (parts.Length > 1)
                            {
                                extension = parts[parts.Length - 1];
                            }
                            String filenm = filename.Substring(0, filename.Length - extension.Length);

                            // Not sure if this is good enough solution for file overwrites
                            f = new FileInfo(finalDir + "\\" + filenm + Guid.NewGuid() + "." + extension);
                        }
                        file.SaveAs(f.FullName);
                        newFiles.Add(f);
                        logger.LogCritical(ILogger_Fields.SECURITY, "File successfully uploaded: " + f);
                    }
                }
                logger.LogCritical(ILogger_Fields.SECURITY, "File successfully uploaded: ");
                //session.Add("progress", System.Convert.ToString(0));
            }

            catch (Exception ex)
            {
                if (ex is ValidationUploadException)
                {
                    throw (ValidationException)ex;
                }
                throw new ValidationUploadException("Upload failure", "Problem during upload");
            }
            return(newFiles);
        }
        private static Dictionary<string, IHttpPostedFile[]> GetHttpPostedFileDictionary(IHttpFileCollection files)
        {
            if (files.Count == 0)
                return _emptyDictionary;

            // build up the 1:many file mapping
            List<KeyValuePair<string, IHttpPostedFile>> mapping = new List<KeyValuePair<string, IHttpPostedFile>>();
            string[] allKeys = files.AllKeys;
            for (int i = 0; i < files.Count; i++)
            {
                string key = allKeys[i];
                if (key != null)
                {
                    mapping.Add(new KeyValuePair<string, IHttpPostedFile>(key, files[i]));
                }
            }

            // turn the mapping into a 1:many dictionary
            var grouped = mapping.GroupBy(el => el.Key, el => el.Value, StringComparer.OrdinalIgnoreCase);
            return grouped.ToDictionary(g => g.Key, g => g.ToArray(), StringComparer.OrdinalIgnoreCase);
        }