Ejemplo n.º 1
0
        async Task LoadMultiPart()
        {
            string boundary = GetParameter(ContentType, "; boundary=");
            if (boundary == null)
                return;

            using (var requestStream = GetSubStream(InputStream))
            {
                //DB: 30/01/11 - Hack to get around non-seekable stream and received HTTP request
                //Not ending with \r\n?
                var ms = new MemoryStream(32 * 1024);
                await requestStream.CopyToAsync(ms).ConfigureAwait(false);

                var input = ms;
                ms.WriteByte((byte)'\r');
                ms.WriteByte((byte)'\n');

                input.Position = 0;

                //Uncomment to debug
                //var content = new StreamReader(ms).ReadToEnd();
                //Console.WriteLine(boundary + "::" + content);
                //input.Position = 0;

                var multi_part = new HttpMultipart(input, boundary, ContentEncoding);

                HttpMultipart.Element e;
                while ((e = multi_part.ReadNextElement()) != null)
                {
                    if (e.Filename == null)
                    {
                        byte[] copy = new byte[e.Length];

                        input.Position = e.Start;
                        input.Read(copy, 0, (int)e.Length);

                        form.Add(e.Name, (e.Encoding ?? ContentEncoding).GetString(copy));
                    }
                    else
                    {
                        //
                        // We use a substream, as in 2.x we will support large uploads streamed to disk,
                        //
                        HttpPostedFile sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
                        files.AddFile(e.Name, sub);
                    }
                }
            }
        }
Ejemplo n.º 2
0
		//
		// Loads the data on the form for multipart/form-data
		//
		void LoadMultiPart ()
		{
			string boundary = GetParameter (ContentType, "; boundary=");
			if (boundary == null)
				return;

			Stream input = GetSubStream (InputStream);
			HttpMultipart multi_part = new HttpMultipart (input, boundary, ContentEncoding);

			HttpMultipart.Element e;
			while ((e = multi_part.ReadNextElement ()) != null) {
				if (e.Filename == null){
					byte [] copy = new byte [e.Length];
				
					input.Position = e.Start;
					input.Read (copy, 0, (int) e.Length);

					form.Add (e.Name, ContentEncoding.GetString (copy));
				} else {
					//
					// We use a substream, as in 2.x we will support large uploads streamed to disk,
					//
					HttpPostedFile sub = new HttpPostedFile (e.Filename, e.ContentType, input, e.Start, e.Length);
					files.AddFile (e.Name, sub);
				}
			}
			EndSubStream (input);
		}
Ejemplo n.º 3
0
        public OSHttpRequest(IHttpClientContext context, IHttpRequest req)
        {
            _request = req;
            _context = context;

            if (null != req.Headers["content-encoding"])
                _contentEncoding = Encoding.GetEncoding(_request.Headers["content-encoding"]);
            if (null != req.Headers["content-type"])
                _contentType = _request.Headers["content-type"];
            if (null != req.Headers["user-agent"])
                _userAgent = req.Headers["user-agent"];
            if (null != req.Headers["remote_addr"])
            {
                try
                {
                    IPAddress addr = IPAddress.Parse(req.Headers["remote_addr"]);
                    // sometimes req.Headers["remote_port"] returns a comma separated list, so use
                    // the first one in the list and log it 
                    string[] strPorts = req.Headers["remote_port"].Split(new char[] { ',' });
                    if (strPorts.Length > 1)
                    {
                        MainConsole.Instance.ErrorFormat("[OSHttpRequest]: format exception on addr/port {0}:{1}, ignoring",
                                     req.Headers["remote_addr"], req.Headers["remote_port"]);
                    }
                    int port = Int32.Parse(strPorts[0]);
                    _remoteIPEndPoint = new IPEndPoint(addr, port);
                }
                catch (FormatException)
                {
                    MainConsole.Instance.ErrorFormat("[OSHttpRequest]: format exception on addr/port {0}:{1}, ignoring",
                                     req.Headers["remote_addr"], req.Headers["remote_port"]);
                }
            }

            _queryString = new NameValueCollection();
            _query = new Hashtable();
            try
            {
                foreach (HttpInputItem item in req.QueryString)
                {
                    try
                    {
                        _queryString.Add(item.Name, item.Value);
                        _query[item.Name] = item.Value;
                    }
                    catch (InvalidCastException)
                    {
                        MainConsole.Instance.DebugFormat("[OSHttpRequest]: error parsing {0} query item, skipping it", item.Name);
                        continue;
                    }
                }
            }
            catch (Exception)
            {
                MainConsole.Instance.ErrorFormat("[OSHttpRequest]: Error parsing querystring");
            }

            if (ContentType != null && ContentType.StartsWith("multipart/form-data"))
            {
                HttpMultipart.Element element;
                var boundry = "";
                var multipart = new HttpMultipart(InputStream, boundry, ContentEncoding ?? Encoding.UTF8);

                while ((element = multipart.ReadNextElement()) != null)
                {
                    if (string.IsNullOrEmpty(element.Name))
                        throw new FormatException("Error parsing request. Missing value name.\nElement: " + element);

                    if (!string.IsNullOrEmpty(element.Filename))
                    {
                        if (string.IsNullOrEmpty(element.ContentType))
                            throw new FormatException("Error parsing request. Value '" + element.Name +
                                                      "' lacks a content type.");

                        // Read the file data
                        var buffer = new byte[element.Length];
                        InputStream.Seek(element.Start, SeekOrigin.Begin);
                        InputStream.Read(buffer, 0, (int)element.Length);

                        // Generate a filename
                        var originalFileName = element.Filename;
                        var internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);

                        // if the internet path doesn't exist, assume mono and /var/tmp
                        var path = string.IsNullOrEmpty(internetCache)
                                       ? Path.Combine("var", "tmp")
                                       : Path.Combine(internetCache.Replace("\\\\", "\\"), "tmp");

                        element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode()) + ".tmp");

                        // If the file exists generate a new filename
                        while (File.Exists(element.Filename))
                            element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode() + 1) + ".tmp");

                        if (!Directory.Exists(path))
                            Directory.CreateDirectory(path);

                        File.WriteAllBytes(element.Filename, buffer);

                        var file = new HttpFile
                        {
                            Name = element.Name,
                            OriginalFileName = originalFileName,
                            ContentType = element.ContentType,
                            TempFileName = element.Filename
                        };
                        Files.Add(element.Name, file);
                    }
                    /*else
                    {
                        var buffer = new byte[element.Length];
                        message.Body.Seek(element.Start, SeekOrigin.Begin);
                        message.Body.Read(buffer, 0, (int)element.Length);

                        form.Add(Uri.UnescapeDataString(element.Name), message.ContentEncoding.GetString(buffer));
                    }*/
                }
            }
        }