Beispiel #1
0
        public override HttpResponse Get(HttpRequest request)
        {
            if (File.Exists(request.RequestedController + ".html"))
                return HttpStatus.Ok(File.ReadAllText(request.RequestedController + ".html"));

            return HttpStatus.Ok("");
        }
Beispiel #2
0
        public void GivenUrl(string url)
        {
            request = new HttpRequest();

            controller = request.ParseController(url);

            resource = request.ParseResource(url, controller);
        }
Beispiel #3
0
 public static IHttpResponse GetResponse(HttpRequest req)
 {
     if (req == null)
     {
         return MakeNullResponse();
     }
     return new HttpResponse { Status = new HttpStatusCode() { Code = 200, Message = "OK", Description = "" }, Body = Encoding.Default.GetBytes("<h1>Hello World Test</h1>"), Headers = new List<HttpHeader> { new HttpHeader { Key = "Content-type", Value = "text/html" }, new HttpHeader { Key = "Date", Value = DateTime.Now.ToString() } } };
 }
 public PollServiceHttpRequest(
     PollServiceEventArgs pPollServiceArgs, HttpServerLib.HttpClientContext pHttpContext, HttpServerLib.HttpRequest pRequest)
 {
     PollServiceArgs = pPollServiceArgs;
     HttpContext = pHttpContext;
     Request = pRequest;
     RequestTime = System.Environment.TickCount;
     RequestID = UUID.Random();
 }
 public PollServiceHttpRequest(
     PollServiceEventArgs pPollServiceArgs, HttpServerLib.HttpClientContext pHttpContext, HttpServerLib.HttpRequest pRequest)
 {
     PollServiceArgs = pPollServiceArgs;
     HttpContext     = pHttpContext;
     Request         = pRequest;
     RequestTime     = System.Environment.TickCount;
     RequestID       = UUID.Random();
 }
Beispiel #6
0
        public override HttpResponse Get(HttpRequest request)
        {
            Console.WriteLine("ScreenCaptureController.Get: " + request.RequestedResource);

            var img = new ScreenCapture().CaptureScreen();

            if (request.RequestedResource.Contains('.'))
            {
                var name = request.RequestedResource.Split('.')[0];
                var mimeType = "image/" + request.RequestedResource.Split('.')[1].Replace("jpg", "jpeg");

                if (name.Equals("screen"))
                    return HttpStatus.Ok(img, mimeType);
            }

            return HttpStatus.NotFound(request.RequestedResource);
        }
Beispiel #7
0
        private void FinishFormData(HttpRequest request)
        {
            if (form_data.Count <= 2)
                return;

            // Chop the \r\n off the end
            form_data.RemoveRange (form_data.Count - 2, 2);
            string data = encoding.GetString (form_data.ToArray ());
            request.PostData.Set (current_name, data);
            form_data.Clear ();
        }
        public void given_wrong_http_verb_should_return_unknown_method()
        {
            var request = new HttpRequest() { HttpMethod = "FOO", RequestedController = "reg" };

            registry.Route(request).Content.ShouldBe("Unknown HTTP method: FOO");
        }
 internal static bool ShouldReplyTo100Continue(HttpRequest request)
 {
     string expectHeader = request.Headers["expect"];
     return expectHeader != null && expectHeader.Contains("100-continue");
 }
        public OSHttpRequest(HttpServerLib.HttpClientContext context, HttpServerLib.HttpRequest req)
        {
            _request = req;
            _context = context;

            if (null != req.Headers["content-encoding"])
            {
                try
                {
                    _contentEncoding = Encoding.GetEncoding(_request.Headers["content-encoding"]);
                }
                catch (Exception)
                {
                    // ignore
                }
            }

            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)
                    {
                        _log.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)
                {
                    _log.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 (HttpServerLib.HttpInputItem item in req.QueryString)
                {
                    try
                    {
                        _queryString.Add(item.Name, item.Value);
                        _query[item.Name] = item.Value;
                    }
                    catch (InvalidCastException)
                    {
                        _log.DebugFormat("[OSHttpRequest]: error parsing {0} query item, skipping it", item.Name);
                        continue;
                    }
                }
            }
            catch (Exception)
            {
                _log.ErrorFormat("[OSHttpRequest]: Error parsing querystring");
            }

//            Form = new Hashtable();
//            foreach (HttpInputItem item in req.Form)
//            {
//                _log.DebugFormat("[OSHttpRequest]: Got form item {0}={1}", item.Name, item.Value);
//                Form.Add(item.Name, item.Value);
//            }
        }
Beispiel #11
0
 public HttpRequestTest()
 {
     _request = new HttpRequest();
 }
Beispiel #12
0
 public override HttpResponse Post(HttpRequest request)
 {
     return HttpStatus.Ok("post");
 }
Beispiel #13
0
        public void route_post_should_return_post()
        {
            var request = new HttpRequest() { HttpMethod = "post", RequestedController = "reg" };

            registry.Route(request).Content.ShouldBe("post");
        }
Beispiel #14
0
        private void FinishFileData(HttpRequest request)
        {
            if (uploaded_file == null)
                return;

            // Chop off the \r\n that gets appended before the boundary marker
            uploaded_file.Contents.SetLength (uploaded_file.Contents.Position - 2);
            uploaded_file.Contents.Position = 0;
            //uploaded_file.Finish ();

            if (uploaded_file.Length > 0)
                request.Files.Add (current_name, uploaded_file);

            uploaded_file = null;
        }
Beispiel #15
0
        public void HandleData(HttpRequest request, byte[] data, int pos, int len)
        {
            byte [] str_data = data;

            int begin = pos;
            int end = begin + len;

            pos = begin - 1;

            while (pos < end - 1 && state != State.Finished) {

                byte c = str_data [++pos];

                switch (state) {
                case State.InBoundary:
                    if (index == boundary.Length - 1) {

                        boundary_buffer.Clear ();

                        // Flush any data
                        FinishFormData (request);
                        FinishFileData (request);

                        state = State.PostBoundary1;
                        index = 0;
                        break;
                    }

                    boundary_buffer.Add (c);

                    if (c != boundary [index]) {
                        // Copy the boundary buffer to the beginning and restart parsing there
                        MemoryStream stream = new MemoryStream ();
                        stream.Write (boundary_buffer.ToArray (), 0, boundary_buffer.Count);
                        stream.Write (str_data, pos + 1, end - pos - 1);
                        str_data = stream.ToArray ();

                        pos = -1;
                        end = str_data.Length;

                        not_boundary = true;
                        boundary_buffer.Clear ();
                        state = previous_state;
                        index = 0;

                        // continue instead of break so not_boundary is not reset
                        continue;
                    }

                    ++index;
                    break;

                case State.PostBoundary1:
                    if (c == '-') {
                        state = State.PostBoundaryComplete;
                        break;
                    }

                    if (c == '\r')
                        break;

                    if (c == '\n') {
                        state = State.InHeaderKey;
                        break;
                    }

                    throw new Exception (String.Format ("Invalid post boundary char '{0}'", c));

                case State.PostBoundaryComplete:
                    if (c != '-')
                        throw new Exception (String.Format ("Invalid char '{0}' in boundary complete.", c));

                    state = State.Finished;
                    break;

                case State.InHeaderKey:
                    if (c == '\n') {
                        state = current_filename == null ? State.InFormData : State.InFileData;
                        break;
                    }

                    if (c == ':') {
                        state = State.InHeaderValue;
                        break;
                    }

                    header_key.Add (c);
                    break;

                case State.InHeaderValue:
                    if (c == '\r') {
                        state = State.PostHeader1;
                        break;
                    }

                    header_value.Add (c);
                    break;

                case State.PostHeader1:
                    if (c != '\n')
                        throw new Exception (String.Format ("Invalid char '{0}' in post header 1.", c));
                    state = State.PostHeader2;
                    break;

                case State.PostHeader2:
                    HandleHeader (request); header_key.Clear ();
                    header_value.Clear ();
                    state = State.InHeaderKey;
                    break;

                case State.InFormData:
                    if (CheckStartingBoundary (str_data, pos))
                        break;

                    form_data.Add (c);
                    break;

                case State.InFileData:
                    if (CheckStartingBoundary (str_data, pos))
                        break;;

                    if (uploaded_file != null)
                        uploaded_file.Contents.WriteByte (c);
                    break;
                default:
                    throw new Exception (String.Format ("Unhandled state: {0}", state));
                }

                not_boundary = false;
            }
        }
Beispiel #16
0
 public void Finish(HttpRequest request)
 {
     FinishFormData (request);
     FinishFileData (request);
 }
 public void Enqueue(HttpClientContext context, HttpRequest request)
 {
     QueueItem item = new QueueItem { Context = context, Request = request };
     lock (_queue)
         _queue.Enqueue(item);
 }
        public OSHttpRequest(HttpServerLib.HttpClientContext context, HttpServerLib.HttpRequest req)
        {
            _request = req;
            _context = context;

            if (null != req.Headers["content-encoding"])
            {
                try
                {
                    _contentEncoding = Encoding.GetEncoding(_request.Headers["content-encoding"]);
                }
                catch (Exception)
                {
                    // ignore
                }
            }
            
            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)
                    {
                        _log.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)
                {
                    _log.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 (HttpServerLib.HttpInputItem item in req.QueryString)
                {
                    try
                    {
                        _queryString.Add(item.Name, item.Value);
                        _query[item.Name] = item.Value;
                    }
                    catch (InvalidCastException)
                    {
                        _log.DebugFormat("[OSHttpRequest]: error parsing {0} query item, skipping it", item.Name);
                        continue;
                    }
                }
            }
            catch (Exception)
            {
                _log.ErrorFormat("[OSHttpRequest]: Error parsing querystring");
            }

//            Form = new Hashtable();
//            foreach (HttpInputItem item in req.Form)
//            {
//                _log.DebugFormat("[OSHttpRequest]: Got form item {0}={1}", item.Name, item.Value);
//                Form.Add(item.Name, item.Value);
//            }
        }
Beispiel #19
0
        private void HandleHeader(HttpRequest request)
        {
            string key = encoding.GetString (header_key.ToArray ());
            string value = encoding.GetString (header_value.ToArray ());

            if (String.Compare(key,"Content-Disposition",true) == 0)
                ParseContentDisposition (value);
            else if (String.Compare(key,"Content-Type",true) == 0)
                ParseContentType (value);
        }
Beispiel #20
0
    ///<summary>
    ///Creates a new object that is a copy of the current instance.
    ///</summary>
    ///
    ///<returns>
    ///A new object that is a copy of this instance.
    ///</returns>
    ///<filterpriority>2</filterpriority>
    public object Clone()
    {
      // this method was mainly created for testing.
      // dont use it that much...
      var request = new HttpRequest();
      request.Method = _method;
      if (AcceptTypes != null)
      {
        request.AcceptTypes = new string[AcceptTypes.Length];
        AcceptTypes.CopyTo(request.AcceptTypes, 0);
      }
      request._httpVersion = _httpVersion;
      request._queryString = _queryString;
      request.Uri = _uri;

      var buffer = new byte[_body.Length];
      _body.Read(buffer, 0, (int) _body.Length);
      request.Body = new MemoryStream();
      request.Body.Write(buffer, 0, buffer.Length);
      request.Body.Seek(0, SeekOrigin.Begin);
      request.Body.Flush();

      request._headers.Clear();
      foreach (string key in _headers)
      {
        string[] values = _headers.GetValues(key);
        if (values != null)
          foreach (string value in values)
            request.AddHeader(key, value);
      }
      Clear();
      return request;
    }
 public HttpServerContextObj(HttpServerLib.HttpClientContext contxt, HttpServerLib.HttpRequest reqs)
 {
     context = contxt;
     req = reqs;
 }