Example #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Request"/> class.
        /// </summary>
        /// <param name="method">The HTTP data transfer method used by the client.</param>
        /// <param name="uri">The absolute path of the requested resource. This shold not not include the scheme, host name, or query portion of the URI</param>
        /// <param name="headers">The headers that was passed in by the client.</param>
        /// <param name="body">The <see cref="Stream"/> that represents the incoming HTTP body.</param>
        /// <param name="protocol">The HTTP protocol that was used by the client.</param>
        /// <param name="query">The querystring data that was sent by the client.</param>
        public Request(string method, string uri, IDictionary<string, IEnumerable<string>> headers, RequestStream body, string protocol, string query = "")
        {
            if (method == null)
                throw new ArgumentNullException("method", "The value of the method parameter cannot be null.");

            if (method.Length == 0)
                throw new ArgumentOutOfRangeException("method", method, "The value of the method parameter cannot be empty.");

            if (uri == null)
                throw new ArgumentNullException("uri", "The value of the uri parameter cannot be null.");

            if (uri.Length == 0)
                throw new ArgumentOutOfRangeException("uri", uri, "The value of the uri parameter cannot be empty.");

            if (headers == null)
                throw new ArgumentNullException("headers", "The value of the headers parameter cannot be null.");

            if (body == null)
                throw new ArgumentNullException("body", "The value of the body parameter cannot be null.");

            if (protocol == null)
                throw new ArgumentNullException("protocol", "The value of the protocol parameter cannot be null.");

            if (protocol.Length == 0)
                throw new ArgumentOutOfRangeException("protocol", protocol, "The value of the protocol parameter cannot be empty.");

            this.Body = body;
            this.Headers = new Dictionary<string, IEnumerable<string>>(headers, StringComparer.OrdinalIgnoreCase);
            this.Method = method;
            this.Uri = uri;
            this.Protocol = protocol;
            this.Query = query.AsQueryDictionary();
            this.Session = new NullSessionProvider();
            this.ParseFormData();
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Request"/> class.
        /// </summary>
        /// <param name="method">The HTTP data transfer method used by the client.</param>
        /// <param name="url">The <see cref="Url"/> of the requested resource</param>
        /// <param name="headers">The headers that was passed in by the client.</param>
        /// <param name="body">The <see cref="Stream"/> that represents the incoming HTTP body.</param>
        /// <param name="ip">The client's IP address</param>
        /// <param name="certificate">The client's certificate when present.</param>
        /// <param name="protocolVersion">The HTTP protocol version.</param>
        public Request(string method,
            Url url,
            RequestStream body = null,
            IDictionary<string, IEnumerable<string>> headers = null,
            string ip = null,
            byte[] certificate = null,
            string protocolVersion = null)
        {
            if (String.IsNullOrEmpty(method))
            {
                throw new ArgumentOutOfRangeException("method");
            }

            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            if (url.Path == null)
            {
                throw new ArgumentNullException("url.Path");
            }

            if (String.IsNullOrEmpty(url.Scheme))
            {
                throw new ArgumentOutOfRangeException("url.Scheme");
            }

            this.UserHostAddress = ip;

            this.Url = url;

            this.Method = method;

            this.Query = url.Query.AsQueryDictionary();

            this.Body = body ?? RequestStream.FromStream(new MemoryStream());

            this.Headers = new RequestHeaders(headers ?? new Dictionary<string, IEnumerable<string>>());

            this.Session = new NullSessionProvider();

            if (certificate != null && certificate.Length != 0)
            {
                this.ClientCertificate = new X509Certificate2(certificate);
            }

            this.ProtocolVersion = protocolVersion ?? string.Empty;

            if (String.IsNullOrEmpty(this.Url.Path))
            {
                this.Url.Path = "/";
            }

            this.ParseFormData();
            this.RewriteMethod();
        }
            public void First()
            {
                stream = new RequestStream(null, firstSeg, firstSeg.Count);

                mockObserver.Setup(o => o.OnNext(It.Is<ArraySegment<byte>>(v => v.Equals(firstSeg)))).Verifiable();
                mockObserver.Setup(o => o.OnError(It.IsAny<Exception>())).Throws(new Exception("Should not have got error."));
                mockObserver.Setup(o => o.OnCompleted()).Verifiable();

                stream.ReadAsync().Subscribe(mockObserver.Object);

                mockObserver.Verify();
            }
Example #4
0
 public ConnectionInfo(int startBufferOffset, int receiveBufferSize, int constantsOffset, SocketAsyncEventArgs receiveSocketAsyncEventArgs, SocketAsyncEventArgs sendSocketAsyncEventArgs, Socket listenSocket, Func<IDictionary<string, object>, Task> app)
 {
     StartBufferOffset = startBufferOffset;
     ReceiveBufferSize = receiveBufferSize;
     ConstantsOffset = constantsOffset;
     ReceiveSocketAsyncEventArgs = receiveSocketAsyncEventArgs;
     SendSocketAsyncEventArgs = sendSocketAsyncEventArgs;
     _buffer = receiveSocketAsyncEventArgs.Buffer;
     _listenSocket = listenSocket;
     _app = app;
     ResponseStream = new ResponseStream(this);
     RequestStream = new RequestStream(this);
     Environment = new Dictionary<string, object>();
     _reqHeaders = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
     _respHeaders = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
 }
Example #5
0
        public void Should_work_even_with_a_non_seekable_stream()
        {
            var str = A.Fake <Stream>();

            A.CallTo(() => str.CanRead).Returns(true);
            A.CallTo(() => str.CanSeek).Returns(false);
            A.CallTo(() => str.CanTimeout).Returns(true);
            A.CallTo(() => str.CanWrite).Returns(true);

            // Given
            var request = RequestStream.FromStream(str, 0, 1, false);

            // When
            var result = request.CanRead;

            // Then
            result.ShouldBeTrue();
        }
Example #6
0
 public void CloseRequestStream()
 {
     if (RequestStream != null)
     {
         try
         {
             RequestStream.Close();
         }
         // ReSharper disable once EmptyGeneralCatchClause
         catch
         {
         }
         finally
         {
             RequestStream = null;
         }
     }
 }
 public void CloseRequestStream()
 {
     if (RequestStream != null)
     {
         try
         {
             RequestStream.Close();
         }
         catch
         {
             // ignored
         }
         finally
         {
             RequestStream = null;
         }
     }
 }
Example #8
0
        public void Should_return_result_from_underlaying_beginwrite_when_beginwrite_is_called()
        {
            // Given
            var           stream      = CreateFakeStream();
            var           buffer      = new byte[10];
            var           asyncResult = A.Fake <IAsyncResult>();
            AsyncCallback callback    = x => { };
            var           state       = new object();
            var           request     = RequestStream.FromStream(stream, 0, 10, true);

            A.CallTo(() => stream.BeginWrite(buffer, 0, buffer.Length, callback, state)).Returns(asyncResult);

            // When
            var result = request.BeginWrite(buffer, 0, buffer.Length, callback, state);

            // Then
            result.ShouldBeSameAs(asyncResult);
        }
Example #9
0
        private Request ConvertRequestToNancyRequest(HttpListenerRequest request)
        {
            var baseUri = this.baseUriList.FirstOrDefault(uri => uri.IsCaseInsensitiveBaseOf(request.Url));

            if (baseUri == null)
            {
                throw new InvalidOperationException(String.Format("Unable to locate base URI for request: {0}", request.Url));
            }

            var expectedRequestLength =
                GetExpectedRequestLength(request.Headers.ToDictionary());

            var relativeUrl = baseUri.MakeAppLocalPath(request.Url);

            var nancyUrl = new Url
            {
                Scheme   = request.Url.Scheme,
                HostName = request.Url.Host,
                Port     = request.Url.IsDefaultPort ? null : (int?)request.Url.Port,
                BasePath = baseUri.AbsolutePath.TrimEnd('/'),
                Path     = HttpUtility.UrlDecode(relativeUrl),
                Query    = request.Url.Query,
            };

            byte[] certificate = null;

            if (this.configuration.EnableClientCertificates)
            {
                var x509Certificate = request.GetClientCertificate();

                if (x509Certificate != null)
                {
                    certificate = x509Certificate.RawData;
                }
            }

            return(new Request(
                       request.HttpMethod,
                       nancyUrl,
                       RequestStream.FromStream(request.InputStream, expectedRequestLength, false),
                       request.Headers.ToDictionary(),
                       (request.RemoteEndPoint != null) ? request.RemoteEndPoint.Address.ToString() : null,
                       certificate));
        }
Example #10
0
        public async Task UploadFiles(IEnumerable <UploadFile> files, NameValueCollection values)
        {
            string newLine  = Environment.NewLine;
            string boundary = $"--{this.Boundary}";

            long totalBytes = files.Select(f => new FileInfo(f.FileName).Length).Sum();
            long sendBytes  = 0;

            if (values != null)
            {
                foreach (string name in values.Keys)
                {
                    await WriteString($"{boundary}{newLine}", Encoding.ASCII);
                    await WriteString($"Content-Disposition: form-data; name=\"{name}\"{newLine}{newLine}", Encoding.ASCII);
                    await WriteString($"{values[name]}{newLine}", Encoding.UTF8);
                }
            }

            foreach (UploadFile file in files)
            {
                await WriteString($"{boundary}{newLine}", Encoding.ASCII);
                await WriteString($"Content-Disposition: form-data; name=\"{file.Name}\"; filename=\"{Path.GetFileName(file.FileName)}\"{newLine}", Encoding.UTF8);
                await WriteString($"Content-Type: {file.ContentType}{newLine}{newLine}", Encoding.ASCII);

                using (var fs = File.OpenRead(file.FileName))
                {
                    byte[] buffer = new byte[4096];
                    int    read   = 0;

                    while ((read = await fs.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        await RequestStream.WriteAsync(buffer, 0, read);

                        sendBytes += read;

                        this.OnReport(sendBytes / (double)totalBytes);
                    }

                    await WriteString(newLine, Encoding.ASCII);
                }
            }

            await WriteString($"{boundary}--", Encoding.ASCII);
        }
Example #11
0
        public Request(string method, Url url, RequestStream body = null, IDictionary <string, IEnumerable <string> > headers = null, string ip = null)
        {
            if (String.IsNullOrEmpty(method))
            {
                throw new ArgumentOutOfRangeException("method");
            }

            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            if (String.IsNullOrEmpty(url.Path))
            {
                throw new ArgumentOutOfRangeException("url.Path");
            }

            if (url.Scheme == null)
            {
                throw new ArgumentNullException("url.Scheme");
            }

            if (String.IsNullOrEmpty(url.Scheme))
            {
                throw new ArgumentOutOfRangeException("url.Scheme");
            }

            this.UserHostAddress = ip;

            this.Url = url;

            this.Method = method;

            this.Query = url.Query.AsQueryDictionary();

            this.Body = body ?? RequestStream.FromStream(new MemoryStream());

            this.Headers = new RequestHeaders(headers ?? new Dictionary <string, IEnumerable <string> >());

            this.Session = new NullSessionProvider();

            this.ParseFormData();
            this.RewriteMethod();
        }
        public async Task Invoke(HttpContext environment)
        {
            var aspnetCoreRequestMethod      = environment.Request.Method;
            var aspnetCoreRequestScheme      = environment.Request.Scheme;
            var aspnetCoreRequestHeaders     = environment.Request.Headers;
            var aspnetCoreRequestPathBase    = environment.Request.PathBase;
            var aspnetCoreRequestPath        = environment.Request.Path;
            var aspnetCoreRequestQueryString = environment.Request.QueryString.Value ?? string.Empty;
            var aspnetCoreRequestBody        = environment.Request.Body;
            var aspnetCoreRequestProtocol    = environment.Request.Protocol;
            var aspnetCoreCallCancelled      = environment.RequestAborted;
            var aspnetCoreRequestHost        = environment.Request.Host.Value ?? Dns.GetHostName();
            var aspnetCoreUser = environment.User;

            X509Certificate2 certificate = null;

            if (_options.EnableClientCertificates)
            {
                var clientCertificate = new X509Certificate2(environment.Connection.ClientCertificate.Export(X509ContentType.Cert));
                certificate = clientCertificate ?? null;
            }

            var serverClientIp = environment.Connection.RemoteIpAddress.ToString();

            var url = CreateUrl(aspnetCoreRequestHost, aspnetCoreRequestScheme, aspnetCoreRequestPathBase, aspnetCoreRequestPath, aspnetCoreRequestQueryString);

            var nancyRequestStream = new RequestStream(aspnetCoreRequestBody, ExpectedLength(aspnetCoreRequestHeaders), StaticConfiguration.DisableRequestStreamSwitching ?? false);

            var nancyRequest = new Request(
                aspnetCoreRequestMethod,
                url,
                nancyRequestStream,
                aspnetCoreRequestHeaders.ToDictionary(kv => kv.Key, kv => (IEnumerable <string>)kv.Value, StringComparer.OrdinalIgnoreCase),
                serverClientIp,
                certificate,
                aspnetCoreRequestProtocol);

            var nancyContext = await _engine.HandleRequest(
                nancyRequest,
                StoreEnvironment(environment, aspnetCoreUser),
                aspnetCoreCallCancelled).ConfigureAwait(false);

            await RequestComplete(nancyContext, environment, _options.PerformPassThrough, _next).ConfigureAwait(false);
        }
Example #13
0
        public Request(string method, Url url, RequestStream body = null, IDictionary<string, IEnumerable<string>> headers = null, string ip = null)
        {
            if (String.IsNullOrEmpty(method))
            {
                throw new ArgumentOutOfRangeException("method");
            }

            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            if (String.IsNullOrEmpty(url.Path))
            {
                throw new ArgumentOutOfRangeException("url.Path");
            }

            if (url.Scheme == null)
            {
                throw new ArgumentNullException("url.Scheme");
            }

            if (String.IsNullOrEmpty(url.Scheme))
            {
                throw new ArgumentOutOfRangeException("url.Scheme");
            }

            this.UserHostAddress = ip;

            this.Url = url;

            this.Method = method;

            this.Query = url.Query.AsQueryDictionary();

            this.Body = body ?? RequestStream.FromStream(new MemoryStream());

            this.Headers = new RequestHeaders(headers ?? new Dictionary<string, IEnumerable<string>>());

            this.Session = new NullSessionProvider();

            this.ParseFormData();
            this.RewriteMethod();
        }
        /// <summary>
        /// Read the http stream as a <see cref="Request"/>.
        /// </summary>
        /// <param name="stream">The http stream.</param>
        /// <param name="scheme">The url scheme.</param>
        /// <param name="ip">The ip address.</param>
        /// <returns>Returns the parse <see cref="Request"/>.</returns>
        public static Request ReadAsRequest(this Stream stream, IDictionary <string, IEnumerable <string> > headers)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            var requestLine = RequestLineParser.Parse(stream);

            var url = new Url();

            if (requestLine.Uri.StartsWith("http", StringComparison.InvariantCultureIgnoreCase))
            {
                Uri uri;
                if (Uri.TryCreate(requestLine.Uri, UriKind.Absolute, out uri))
                {
                    url.Path  = uri.AbsolutePath;
                    url.Query = uri.Query;
                    //url.Fragment = uri.Fragment;
                    url.Scheme = uri.Scheme;
                }
            }
            else
            {
                var splitUri = requestLine.Uri.Split('?');
                url.Path   = splitUri[0];
                url.Query  = splitUri.Length == 2 ? splitUri[1] : string.Empty;
                url.Scheme = "https";
            }


            IEnumerable <string> headerValues;

            if (headers.TryGetValue("Host", out headerValues))
            {
                url.HostName = headerValues.FirstOrDefault();
            }

            var nestedRequestStream = new RequestStream(new HttpMultipartSubStream(stream, stream.Position, stream.Length), stream.Length - stream.Position, true);

            var request = new Request(requestLine.Method, url, nestedRequestStream, headers, null);

            return(request);
        }
Example #15
0
        /// <summary>
        /// OWIN App Action
        /// </summary>
        /// <param name="environment">Application environment</param>
        /// <returns>Returns result</returns>
        public Task Invoke(IDictionary <string, object> environment)
        {
            var owinRequestMethod      = Get <string>(environment, "owin.RequestMethod");
            var owinRequestScheme      = Get <string>(environment, "owin.RequestScheme");
            var owinRequestHeaders     = Get <IDictionary <string, string[]> >(environment, "owin.RequestHeaders");
            var owinRequestPathBase    = Get <string>(environment, "owin.RequestPathBase");
            var owinRequestPath        = Get <string>(environment, "owin.RequestPath");
            var owinRequestQueryString = Get <string>(environment, "owin.RequestQueryString");
            var owinRequestBody        = Get <Stream>(environment, "owin.RequestBody");
            var owinCallCancelled      = Get <CancellationToken>(environment, "owin.CallCancelled");
            var owinRequestHost        = GetHeader(owinRequestHeaders, "Host") ?? Dns.GetHostName();

            byte[] certificate = null;
            if (this.options.EnableClientCertificates)
            {
                var clientCertificate = Get <X509Certificate>(environment, "ssl.ClientCertificate");
                certificate = (clientCertificate == null) ? null : clientCertificate.GetRawCertData();
            }

            var serverClientIp = Get <string>(environment, "server.RemoteIpAddress");

            var url = CreateUrl(owinRequestHost, owinRequestScheme, owinRequestPathBase, owinRequestPath, owinRequestQueryString);

            var nancyRequestStream = new RequestStream(owinRequestBody, ExpectedLength(owinRequestHeaders), false);

            var nancyRequest = new Request(
                owinRequestMethod,
                url,
                nancyRequestStream,
                owinRequestHeaders.ToDictionary(kv => kv.Key, kv => (IEnumerable <string>)kv.Value, StringComparer.OrdinalIgnoreCase),
                serverClientIp,
                certificate);

            var tcs = new TaskCompletionSource <int>();

            this.engine.HandleRequest(
                nancyRequest,
                StoreEnvironment(environment),
                RequestComplete(environment, this.options.PerformPassThrough, this.next, tcs),
                RequestErrored(tcs),
                owinCallCancelled);

            return(tcs.Task);
        }
        public AnalyticsModule()
        {
            Get("/_analytics", parameters =>
            {
                return(new FhirReader().ReadPatient(parameters.id));
                //return $"I am a Patient: {parameters.id}";
            });

            Post("/_analytics", parameters =>
            {
                var body = RequestStream.FromStream(Request.Body).AsString();

                var result = new FhirReader().RunAnalytics(body);

                return(Response.AsText(result, "application/json"));

                //return $"I am a Patient: {parameters.id}";
            });
        }
Example #17
0
        private static Request CreateNancyRequestFromIncomingWebRequest(IncomingWebRequestContext webRequest, Stream requestBody)
        {
            var address =
                ((RemoteEndpointMessageProperty)
                 OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name]);
            var relativeUri = GetUrlAndPathComponents(webRequest.UriTemplateMatch.BaseUri).MakeRelativeUri(GetUrlAndPathComponents(webRequest.UriTemplateMatch.RequestUri));

            var expectedRequestLength =
                GetExpectedRequestLength(webRequest.Headers.ToDictionary());

            return(new Request(
                       webRequest.Method,
                       string.Concat("/", relativeUri),
                       webRequest.Headers.ToDictionary(),
                       RequestStream.FromStream(requestBody, expectedRequestLength, false),
                       webRequest.UriTemplateMatch.RequestUri.Scheme,
                       webRequest.UriTemplateMatch.RequestUri.Query,
                       address.Address));
        }
Example #18
0
        private static Request CreateRequest(string method, Url url, IBrowserContextValues contextValues)
        {
            BuildRequestBody(contextValues);

            var requestStream =
                RequestStream.FromStream(contextValues.Body, 0, true);

            var certBytes = (contextValues.ClientCertificate == null)
                ? ArrayCache.Empty <byte>()
                : contextValues.ClientCertificate.GetRawCertData();

            var requestUrl = url;

            requestUrl.Scheme   = string.IsNullOrWhiteSpace(contextValues.Protocol) ? requestUrl.Scheme : contextValues.Protocol;
            requestUrl.HostName = string.IsNullOrWhiteSpace(contextValues.HostName) ? requestUrl.HostName : contextValues.HostName;
            requestUrl.Query    = string.IsNullOrWhiteSpace(url.Query) ? (contextValues.QueryString ?? string.Empty) : url.Query;

            return(new Request(method, requestUrl, requestStream, contextValues.Headers, contextValues.UserHostAddress, certBytes));
        }
Example #19
0
        private Request CreateRequest(string method, string path, Action <BrowserContext> browserContext)
        {
            var context =
                new BrowserContext();

            this.SetCookies(context);

            browserContext.Invoke(context);

            var contextValues =
                (IBrowserContextValues)context;

            BuildRequestBody(contextValues);

            var requestStream =
                RequestStream.FromStream(contextValues.Body, 0, true);

            return(new Request(method, path, contextValues.Headers, requestStream, contextValues.Protocol, contextValues.QueryString));
        }
 public RequestStream GetRequestStream(bool chunked, long contentlength)
 {
     if (i_stream == null)
     {
         byte[] buffer = ms.GetBuffer();
         int    length = (int)ms.Length;
         ms = null;
         if (chunked)
         {
             this.chunked = true;
             context.Response.SendChunked = true;
             i_stream = new ChunkedInputStream(context, stream, buffer, position, length - position);
         }
         else
         {
             i_stream = new RequestStream(stream, buffer, position, length - position, contentlength);
         }
     }
     return(i_stream);
 }
Example #21
0
        private static Request CreateNancyRequest(HttpContextBase context)
        {
            var incomingHeaders = context.Request.Headers.ToDictionary();

            var expectedRequestLength =
                GetExpectedRequestLength(incomingHeaders);

            var basePath = context.Request.ApplicationPath.TrimEnd('/');

            var path = context.Request.Url.AbsolutePath.Substring(basePath.Length);

            path = string.IsNullOrWhiteSpace(path) ? "/" : path;

            var nancyUrl = new Url
            {
                Scheme   = context.Request.Url.Scheme,
                HostName = context.Request.Url.Host,
                Port     = context.Request.Url.Port,
                BasePath = basePath,
                Path     = path,
                Query    = context.Request.Url.Query,
                Fragment = context.Request.Url.Fragment,
            };

            byte[] certificate = null;

            if (context.Request.ClientCertificate != null &&
                context.Request.ClientCertificate.IsPresent &&
                context.Request.ClientCertificate.Certificate.Length != 0)
            {
                certificate = context.Request.ClientCertificate.Certificate;
            }

            return(new Request(
                       context.Request.HttpMethod.ToUpperInvariant(),
                       nancyUrl,
                       RequestStream.FromStream(context.Request.InputStream, expectedRequestLength, true),
                       incomingHeaders,
                       context.Request.UserHostAddress,
                       certificate));
        }
Example #22
0
        /// <summary>
        /// OWIN App Action
        /// </summary>
        /// <param name="environment">Application environment</param>
        /// <returns>Returns result</returns>
        public Task Invoke(IDictionary <string, object> environment)
        {
            var owinRequestMethod      = Get <string>(environment, "owin.RequestMethod");
            var owinRequestScheme      = Get <string>(environment, "owin.RequestScheme");
            var owinRequestHeaders     = Get <IDictionary <string, string[]> >(environment, "owin.RequestHeaders");
            var owinRequestPathBase    = Get <string>(environment, "owin.RequestPathBase");
            var owinRequestPath        = Get <string>(environment, "owin.RequestPath");
            var owinRequestQueryString = Get <string>(environment, "owin.RequestQueryString");
            var owinRequestBody        = Get <Stream>(environment, "owin.RequestBody");
            var serverClientIp         = Get <string>(environment, "server.RemoteIpAddress");
            //var callCancelled = Get<CancellationToken>(environment, "owin.RequestBody");

            var url = new Url
            {
                Scheme   = owinRequestScheme,
                HostName = GetHeader(owinRequestHeaders, "Host"),
                Port     = null,
                BasePath = owinRequestPathBase,
                Path     = owinRequestPath,
                Query    = owinRequestQueryString,
            };

            var nancyRequestStream = new RequestStream(owinRequestBody, ExpectedLength(owinRequestHeaders), false);

            var nancyRequest = new Request(
                owinRequestMethod,
                url,
                nancyRequestStream,
                owinRequestHeaders.ToDictionary(kv => kv.Key, kv => (IEnumerable <string>)kv.Value, StringComparer.OrdinalIgnoreCase),
                serverClientIp);

            var tcs = new TaskCompletionSource <int>();

            this.engine.HandleRequest(
                nancyRequest,
                StoreEnvironment(environment),
                RequestComplete(environment, tcs),
                RequestErrored(tcs));

            return(tcs.Task);
        }
Example #23
0
        public static JObject BodyToJObject(RequestStream body)
        {
            body.Position = 0;
            JObject jsonObject = null;

            using (var memory = new MemoryStream())
            {
                try
                {
                    body.CopyTo(memory);
                    var str = Encoding.UTF8.GetString(memory.ToArray());
                    if (!string.IsNullOrEmpty(str))
                    {
                        jsonObject = JObject.Parse(str);
                    }
                }
                catch { }
            }

            return(jsonObject);
        }
            public void FirstAndOne()
            {
                var restSeg = new ArraySegment<byte>(buffer, first.Length, last.Length);

                stream = new RequestStream(mockSocket.Object, firstSeg, buffer.Length);

                mockObserver.Setup(o => o.OnNext(It.Is<ArraySegment<byte>>(v => v.Equals(firstSeg)))).Verifiable();
                mockObserver.Setup(o => o.OnError(It.IsAny<Exception>())).Throws(new Exception("Should not have got error."));
                mockObserver.Setup(o => o.OnCompleted()).Verifiable();

                stream.ReadAsync().Subscribe(mockObserver.Object);

                mockObserver.Verify();

                int bufferSize = 1024;

                mockSocket
                    .Setup(s => s.Read(
                        It.Is<byte[]>(b => b.Length == bufferSize),
                        It.Is<int>(o => o == 0),
                        It.Is<int>(c => c == bufferSize)))
                    .Returns<byte[], int, int>((byte[] b, int o, int c) =>
                        Observable.Create<int>(ob =>
                        {
                            ob.OnNext(restSeg.Count);
                            ob.OnCompleted();
                            return () => { };
                        }))
                    .Verifiable();

                mockObserver.Setup(o => o.OnNext(It.Is<ArraySegment<byte>>(v => v.Count == restSeg.Count))).Verifiable();
                mockObserver.Setup(o => o.OnError(It.IsAny<Exception>())).Throws(new Exception("Should not have got error."));
                mockObserver.Setup(o => o.OnCompleted()).Verifiable();

                stream.ReadAsync().Subscribe(mockObserver.Object);

                mockSocket.Verify();
                mockObserver.Verify();
            }
Example #25
0
        public object Proxy()
        {
            var baseUrl         = this.GetBaseUrl();
            var method          = this.Context.Request.Method;
            var queryAsString   = this.Context.Request.Url.Query;
            var query           = this.GetQueryString(queryAsString);
            var path            = this.Context.Request.Url.Path;
            var headers         = this.GetRequestHeaders();
            var headersAsString = this.GetRequestHeadersAsString(headers);
            var body            = "";

            if (method.ToLowerInvariant() != "get")
            {
                body = RequestStream.FromStream(this.Context.Request.Body).AsString();
            }

            this.PrintRequest(baseUrl, method, path, queryAsString, body, headersAsString);

            var restResponse = this.ExecuteRequestToTunnel(baseUrl, method, path, body, query, headers);

            return(this.GetProxyResponse(restResponse));
        }
        public ProductController()
        {
            Get("/", _ => "Hello Nancy");

            Get("/products/name/{name}", parameters => {
                return("Hello " + parameters.name);
            });

            Get("/products", _ => {
                return(Products);
            });

            Post("/products", product =>
            {
                var text       = RequestStream.FromStream(Request.Body).AsString();
                var newProduct = JsonConvert.DeserializeObject <Product>(text);

                Products.Add(newProduct);

                return("Exito");
            });
        }
Example #27
0
        private NancyContext PopulateForm(string cultureName)
        {
            string bodyContent = string.Concat("CurrentCulture=", cultureName);
            var    memory      = new MemoryStream();
            var    writer      = new StreamWriter(memory);

            writer.Write(bodyContent);
            writer.Flush();
            memory.Position = 0;

            var headers =
                new Dictionary <string, IEnumerable <string> >
            {
                { "content-type", new[] { "application/x-www-form-urlencoded" } }
            };


            var context = new NancyContext();

            context.Request = new Request("POST", "/", headers, RequestStream.FromStream(memory), "http");
            return(context);
        }
Example #28
0
 internal void Complete(int read, uint errorCode = UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
 {
     if (_requestStream.TryCheckSizeLimit(read + (int)DataAlreadyRead, out var exception))
     {
         _tcs.TrySetException(exception);
     }
     else if (_tcs.TrySetResult(read + (int)DataAlreadyRead))
     {
         RequestStream.UpdateAfterRead((uint)errorCode, (uint)(read + DataAlreadyRead));
         if (_callback != null)
         {
             try
             {
                 _callback(this);
             }
             catch (Exception)
             {
                 // TODO: Exception handling? This may be an IO callback thread and throwing here could crash the app.
             }
         }
     }
     Dispose();
 }
Example #29
0
        private static Request CreateNancyRequest(HttpContextBase context)
        {
            var expectedRequestLength =
                GetExpectedRequestLength(context.Request.Headers.ToDictionary());

            var nancyUrl = new Url
            {
                Scheme   = context.Request.Url.Scheme,
                HostName = context.Request.Url.Host,
                Port     = context.Request.Url.Port,
                BasePath = context.Request.ApplicationPath.TrimEnd('/'),
                Path     = context.Request.AppRelativeCurrentExecutionFilePath.Replace("~", string.Empty),
                Query    = context.Request.Url.Query,
                Fragment = context.Request.Url.Fragment,
            };

            return(new Request(
                       context.Request.HttpMethod.ToUpperInvariant(),
                       nancyUrl,
                       RequestStream.FromStream(context.Request.InputStream, expectedRequestLength, true),
                       context.Request.Headers.ToDictionary(),
                       context.Request.UserHostAddress));
        }
Example #30
0
        public void AsString_should_always_start_from_position_0_and_reset_it_afterwards()
        {
            // Given
            using (var innerStream = new MemoryStream())
                using (var streamWriter = new StreamWriter(innerStream, Encoding.UTF8)
                {
                    AutoFlush = true
                })
                {
                    streamWriter.Write("fake request body");

                    var requestStream = RequestStream.FromStream(innerStream);

                    var initialPosition = requestStream.Position = 3;

                    // When
                    var result = requestStream.AsString(Encoding.UTF8);

                    // Then
                    Assert.Equal("fake request body", result);
                    Assert.Equal(initialPosition, requestStream.Position);
                }
        }
        public void Handle_WithAPostRequestToPactAndNoInteractionsHaveBeenRegistered_NewPactFileIsSavedWithNoInteractions()
        {
            var pactDetails = new PactDetails
            {
                Consumer = new Party {
                    Name = "Consumer"
                },
                Provider = new Party {
                    Name = "Provider"
                }
            };

            var pactFile = new ProviderServicePactFile
            {
                Provider     = pactDetails.Provider,
                Consumer     = pactDetails.Consumer,
                Interactions = new ProviderServiceInteraction[0]
            };

            var pactFileJson    = JsonConvert.SerializeObject(pactFile, JsonConfig.PactFileSerializerSettings);
            var pactDetailsJson = JsonConvert.SerializeObject(pactDetails, JsonConfig.ApiSerializerSettings);

            var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(pactDetailsJson));

            var requestStream = new RequestStream(jsonStream, jsonStream.Length, true);
            var context       = new NancyContext
            {
                Request = new Request("POST", new Url("http://localhost/pact"), requestStream)
            };

            var handler = GetSubject();

            handler.Handle(context);

            _mockFileSystem.File.Received(1).WriteAllText(Path.Combine(Constants.DefaultPactFileDirectory, pactDetails.GeneratePactFileName()), pactFileJson);
        }
        private async Task<Request> MapNancyRequest(HttpRequestMessage request)
        {
            IEnumerable<KeyValuePair<string, IEnumerable<string>>> headersToCopy = request.Headers;
            RequestStream requestStream = null;
            if (request.Content != null)
            {
                headersToCopy = headersToCopy.Concat(request.Content.Headers);
                requestStream = new RequestStream(await request.Content.ReadAsStreamAsync(),
                                                  request.Content.Headers.ContentLength.GetValueOrDefault(), true);
            }

            if (Credentials != null)
            {
                string encodedCredentials =
                    Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Credentials.UserName}:{Credentials.Password}"));
                headersToCopy =
                    headersToCopy.Append(new KeyValuePair<string, IEnumerable<string>>("Authorization",
                                                                                       new[] { "Basic " + encodedCredentials }));
            }

            var nancyRequest = new Request(request.Method.ToString(), request.RequestUri,
                                           requestStream, headersToCopy.ToDictionary(x => x.Key, x => x.Value));
            return nancyRequest;
        }
Example #33
0
        private Request ConvertRequest(Uri baseUri, HttpListenerRequest httpRequest)
        {
            var expectedRequestLength = GetExpectedRequestLength(ConvertToDictionary(httpRequest.Headers));

            var url = new Url
            {
                Scheme   = httpRequest.Url.Scheme,
                HostName = httpRequest.Url.Host,
                Port     = httpRequest.Url.IsDefaultPort ? null : (int?)httpRequest.Url.Port,
                BasePath = baseUri.AbsolutePath.TrimEnd('/'),
                Path     = baseUri.MakeAppLocalPath(httpRequest.Url),
                Query    = httpRequest.Url.Query,
            };

            var fieldCount      = httpRequest.ProtocolVersion.Major == 2 ? 1 : 2;
            var protocolVersion = string.Format("HTTP/{0}", httpRequest.ProtocolVersion.ToString(fieldCount));

            byte[] certificate = null;
            if (httpRequest.IsSecureConnection)
            {
                var x509Certificate = httpRequest.GetClientCertificate();
                if (x509Certificate != null)
                {
                    certificate = x509Certificate.RawData;
                }
            }

            return(new Request(
                       httpRequest.HttpMethod,
                       url,
                       RequestStream.FromStream(httpRequest.InputStream, expectedRequestLength, false),
                       ConvertToDictionary(httpRequest.Headers),
                       httpRequest.RemoteEndPoint,
                       protocolVersion,
                       certificate));
        }
        void Init()
        {
            if (ssl_stream != null)
            {
                //ssl_stream.AuthenticateAsServer(client_cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
            }

            context_bound = false;
            i_stream = null;
            o_stream = null;
            prefix = null;
            chunked = false;
            ms = new MemoryStream();
            position = 0;
            input_state = InputState.RequestLine;
            line_state = LineState.None;
            context = new HttpListenerContext(this, _logger);
        }
Example #35
0
        void Init()
        {
            context_bound = false;

            i_stream      = null;

            o_stream      = null;

            prefix        = null;

            chunked       = false;

            ms            = new MemoryStream();

            position      = 0;

            input_state   = InputState.RequestLine;

            line_state    = LineState.None;

            context       = new HttpListenerContext(this);
        }
        public override Stream GetRequestStream()
        {
            if (_requestStream == null)
                _requestStream = new RequestStream(this);

            return _requestStream;
        }
Example #37
0
 private void Init()
 {
     #if SSL
     if (ssl_stream != null)
     {
         ssl_stream.AuthenticateAsServer(cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
     }
     #endif
     _contextBound = false;
     _iStream = null;
     _oStream = null;
     Prefix = null;
     _chunked = false;
     _ms = new MemoryStream();
     _position = 0;
     _inputState = InputState.RequestLine;
     _lineState = LineState.None;
     _context = new HttpListenerContext(this);
 }
Example #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Request"/> class.
 /// </summary>
 /// <param name="method">The HTTP data transfer method used by the client.</param>
 /// <param name="path">The path of the requested resource, relative to the "Nancy root". This shold not not include the scheme, host name, or query portion of the URI.</param>
 /// <param name="headers">The headers that was passed in by the client.</param>
 /// <param name="body">The <see cref="Stream"/> that represents the incoming HTTP body.</param>
 /// <param name="scheme">The HTTP scheme that was used by the client.</param>
 /// <param name="query">The querystring data that was sent by the client.</param>
 public Request(string method, string path, IDictionary<string, IEnumerable<string>> headers, RequestStream body, string scheme, string query = null, string ip = null)
     : this(method, new Url { Path=path, Scheme = scheme, Query = query ?? String.Empty}, body, headers, ip)
 {
 }
Example #39
0
        public RequestStream GetRequestStream(bool chunked, long contentlength)
        {
            if (_iStream != null) return _iStream;

            var buffer = _ms.ToArray();
            var length = (int) _ms.Length;
            _ms = null;
            if (chunked)
            {
                _chunked = true;
                _context.Response.SendChunked = true;
                _iStream = new ChunkedInputStream(_context, _stream, buffer, _position, length - _position);
            }
            else
            {
                _iStream = new RequestStream(_stream, buffer, _position, length - _position, contentlength);
            }
            return _iStream;
        }
    private void disposeStream ()
    {
      if (_stream == null)
        return;

      _inputStream = null;
      _outputStream = null;

      _stream.Dispose ();
      _stream = null;
    }
    public RequestStream GetRequestStream (long contentLength, bool chunked)
    {
      if (_inputStream != null || _socket == null)
        return _inputStream;

      lock (_sync) {
        if (_socket == null)
          return _inputStream;

        var buff = _requestBuffer.GetBuffer ();
        var len = (int) _requestBuffer.Length;
        disposeRequestBuffer ();
        if (chunked) {
          _context.Response.SendChunked = true;
          _inputStream = new ChunkedRequestStream (
            _stream, buff, _position, len - _position, _context);
        }
        else {
          _inputStream = new RequestStream (
            _stream, buff, _position, len - _position, contentLength);
        }

        return _inputStream;
      }
    }
 private void Init()
 {
     _chunked = false;
     _context = new HttpListenerContext (this);
     _contextWasBound = false;
     _inputState = InputState.RequestLine;
     _inputStream = null;
     _lineState = LineState.None;
     _outputStream = null;
     _position = 0;
     _prefix = null;
     _requestBuffer = new MemoryStream ();
     _timeout = 90000; // 90k ms for first request, 15k ms from then on.
 }
        public RequestStream GetRequestStream(bool chunked, long contentlength)
        {
            if (_inputStream == null) {
                var buffer = _requestBuffer.GetBuffer ();
                var length = buffer.Length;
                _requestBuffer = null;
                if (chunked) {
                    _chunked = true;
                    _context.Response.SendChunked = true;
                    _inputStream = new ChunkedInputStream (_context, _stream, buffer, _position, length - _position);
                } else {
                    _inputStream = new RequestStream (_stream, buffer, _position, length - _position, contentlength);
                }
            }

            return _inputStream;
        }
Example #44
0
 public FakeRequest(string method, string path, string query, string userHostAddress = null)
     : this(method, path, new Dictionary <string, IEnumerable <string> >(), RequestStream.FromStream(new MemoryStream()), "http", query, userHostAddress)
 {
 }
Example #45
0
        public static byte[] HandleRequest(string method, string uri, string query, Dictionary<string, string> headers, IPAddress ip)
        {
            var nuri = new Url
            {
                Scheme = "http",
                HostName = GetHeader(headers, "Host"),
                Port = null,
                BasePath = "",
                Path = uri,
                Query = query
            };

            var contentLength = ExpectedLength(headers);
            var bodyStream = Stream.Null;

            if (contentLength > 0)
            {
                var bodyBytes = GameInterface.ReadHTTPBody((int)contentLength);
                bodyStream = new MemoryStream(bodyBytes);
            }

            var body = new RequestStream(bodyStream, contentLength, false);

            var headerDictionary = headers.ToDictionary(kv => kv.Key, kv => (IEnumerable<string>)new[] { kv.Value }, StringComparer.OrdinalIgnoreCase);
            var request = new Request(method, nuri, body, headerDictionary, ip.ToString());

            var context = _engine.HandleRequest(request);
            var responseStatusCode = context.Response.StatusCode;
            var responseStream = new MemoryStream();
            context.Response.Contents(responseStream);
            responseStream.Position = 0;

            var response = new StringBuilder();
            response.Append("HTTP/1.0 ");
            response.Append(((int)responseStatusCode).ToString());
            response.Append(" ");
            response.Append(_statusCodes[(int)responseStatusCode]);
            response.Append("\r\n");

            foreach (var header in context.Response.Headers)
            {
                response.Append(header.Key);
                response.Append(": ");
                response.Append(string.Join(", ", header.Value));
                response.Append("\r\n");
            }

            if (context.Response.ContentType != null)
            {
                response.Append("Content-Type: ");
                response.Append(context.Response.ContentType);
                response.Append("\r\n");
            }

            if (context.Response.Cookies != null && context.Response.Cookies.Count != 0)
            {
                var cookies = context.Response.Cookies.Select(cookie => cookie.ToString()).ToArray();

                response.Append("Set-Cookie: ");
                response.Append(string.Join(", ", cookies));
                response.Append("\r\n");
            }


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

            var headerBytes = Encoding.UTF8.GetBytes(response.ToString());
            var dataBytes = new byte[responseStream.Length + headerBytes.Length];
            Array.Copy(headerBytes, dataBytes, headerBytes.Length);

            responseStream.Read(dataBytes, headerBytes.Length, (int)responseStream.Length);

            //Log.Debug(context.Trace.TraceLog.ToString());
            context.Dispose();

            return dataBytes;
        }
 private void init ()
 {
   _context = new HttpListenerContext (this);
   _inputState = InputState.RequestLine;
   _inputStream = null;
   _lineState = LineState.None;
   _outputStream = null;
   _position = 0;
   _prefix = null;
   _requestBuffer = new MemoryStream ();
 }
 public RequestStream GetRequestStream(bool chunked, long contentlength)
 {
     if (i_stream == null) {
         byte [] buffer = ms.GetBuffer ();
         int length = (int) ms.Length;
         ms = null;
         if (chunked) {
             this.chunked = true;
             context.Response.SendChunked = true;
             i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
         } else {
             i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
         }
     }
     return i_stream;
 }
Example #48
0
        public Task Invoke(IDictionary <string, object> env)
        {
            var owinRequestMethod      = Get <string>(env, OwinConstants.RequestMethod);
            var owinRequestScheme      = Get <string>(env, OwinConstants.RequestScheme);
            var owinRequestHeaders     = Get <IDictionary <string, string[]> >(env, OwinConstants.RequestHeaders);
            var owinRequestPathBase    = Get <string>(env, OwinConstants.RequestPathBase);
            var owinRequestPath        = Get <string>(env, OwinConstants.RequestPath);
            var owinRequestQueryString = Get <string>(env, OwinConstants.RequestQueryString);
            var owinRequestBody        = Get <Stream>(env, OwinConstants.RequestBody);
            var serverClientIp         = Get <string>(env, OwinConstants.RemoteIpAddress);

            var owinResponseHeaders = Get <IDictionary <string, string[]> >(env, OwinConstants.ResponseHeaders);
            var owinResponseBody    = Get <Stream>(env, OwinConstants.ResponseBody);

            var url = new Url
            {
                Scheme   = owinRequestScheme,
                HostName = GetHeader(owinRequestHeaders, "Host"),
                Port     = null,
                BasePath = owinRequestPathBase,
                Path     = owinRequestPath,
                Query    = owinRequestQueryString,
            };

            var body = new RequestStream(owinRequestBody, ExpectedLength(owinRequestHeaders), false);

            var nancyRequest = new Request(
                owinRequestMethod,
                url,
                body,
                owinRequestHeaders.ToDictionary(kv => kv.Key, kv => (IEnumerable <string>)kv.Value, StringComparer.OrdinalIgnoreCase),
                serverClientIp);

            var tcs = new TaskCompletionSource <object>();

            _engine.HandleRequest(
                nancyRequest,
                context =>
            {
                var nancyResponse = context.Response;

                if (_next != null && nancyResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    _next(env).CopyResultToCompletionSource(tcs, null);
                }
                else
                {
                    env[OwinConstants.ResponseStatusCode] = (int)nancyResponse.StatusCode;
                    foreach (var header in nancyResponse.Headers)
                    {
                        owinResponseHeaders.Add(header.Key, new string[] { header.Value });
                    }

                    if (!string.IsNullOrWhiteSpace(nancyResponse.ContentType))
                    {
                        owinResponseHeaders["Content-Type"] = new[] { nancyResponse.ContentType };
                    }
                    if (nancyResponse.Cookies != null && nancyResponse.Cookies.Count != 0)
                    {
                        owinResponseHeaders["Set-Cookie"] = nancyResponse.Cookies.Select(cookie => cookie.ToString()).ToArray();
                    }

                    nancyResponse.Contents(owinResponseBody);
                    context.Dispose();
                    tcs.TrySetResult(null);
                }
            },
                tcs.SetException);
            return(tcs.Task);
        }
 void Init()
 {
     context_bound = false;
     i_stream      = null;
     o_stream      = null;
     prefix        = null;
     chunked       = false;
     ms            = new MemoryStream ();
     position      = 0;
     input_state   = InputState.RequestLine;
     line_state    = LineState.None;
     context       = new HttpListenerContext (this);
     s_timeout     = 90000; // 90k ms for first request, 15k ms from then on
 }
Example #50
0
 public FakeRequest(string method, string path, IDictionary <string, IEnumerable <string> > headers)
     : this(method, path, headers, RequestStream.FromStream(new MemoryStream()), "http", string.Empty)
 {
 }
Example #51
0
 public FakeRequest(string method, string path, IDictionary<string, IEnumerable<string>> headers, RequestStream body, string protocol, string query)
     : base(method, path, headers, body, protocol, query)
 {
 }
Example #52
0
 public FakeRequest(string method, string path, IDictionary <string, IEnumerable <string> > headers, RequestStream body, string protocol, string query, string userHostAddress = null)
     : base(method, new Url {
     Path = path, Query = query, Scheme = protocol
 }, body, headers, ip: userHostAddress)
 {
 }
Example #53
0
 public FakeRequest(string method, string path, IDictionary<string, IEnumerable<string>> headers, RequestStream body, string protocol, string query)
     : base(method, new Url { Path = path, Query = query, Scheme = protocol }, body, headers)
 {
 }