public async Task Invoke(IDictionary<string, object> environment)
        {
            int maxRedirects = _maxRedirects;

            while (maxRedirects >= 0)
            {
                await _next(environment);

                var response = new OwinResponse(environment);

                if (response.StatusCode == 302 || response.StatusCode == 301)
                {
                    string url = BuildRedirectUrl(response);

                    // Clear the env so we can make a new request
                    environment.Clear();

                    // Populate the env with new request data
                    RequestBuilder.BuildGet(environment, url);
                }
                else
                {
                    break;
                }

                maxRedirects--;
            }
        }
Exemplo n.º 2
0
        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new OwinRequest(env);

            var logger = _kernel.Get<ILogger>();

            var requestHeaders = new StringBuilder();
            foreach (var header in request.Headers)
            {
                requestHeaders.AppendLine(header.Key + " = " + request.GetHeader(header.Key));
            }

            Task task = _next(env);

            var response = new OwinResponse(env);

            var responseHeaders = new StringBuilder();
            foreach (var header in response.Headers)
            {
                responseHeaders.AppendLine(header.Key + " = " + response.GetHeader(header.Key));
            }

            logger.Log("URI: " + request.Uri + " " + Environment.NewLine +
                       "Request Headers: \r\n " + requestHeaders.ToString() + Environment.NewLine +
                       "Response Headers: \r\n " + responseHeaders.ToString());

            return task;
        }
 private void SetHttp2UpgradeHeadersAndStatusCode(OwinResponse owinResponse)
 {
     owinResponse.StatusCode = 101;
     owinResponse.ReasonPhrase = "Switching Protocols";
     owinResponse.SetHeader("Connection", "Upgrade");
     owinResponse.SetHeader("Upgrade", "HTTP/2.0");
 }
Exemplo n.º 4
0
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            OwinRequest owinRequest = OwinRequest.Create();
            owinRequest.Scheme = request.RequestUri.Scheme;
            owinRequest.Method = request.Method.ToString();
            owinRequest.Path = request.RequestUri.AbsolutePath;
            owinRequest.QueryString = request.RequestUri.Query.TrimStart('?');
            owinRequest.CallCancelled = cancellationToken;
            foreach (var header in request.Headers)
            {
                owinRequest.AddHeaderUnmodified(header.Key, header.Value);
            }
            HttpContent requestContent = request.Content;
            if (requestContent != null)
            {
                foreach (var header in request.Content.Headers)
                {
                    owinRequest.AddHeaderUnmodified(header.Key, header.Value);
                }
            }
            else
            {
                requestContent = new StreamContent(Stream.Null);
            }

            return requestContent.ReadAsStreamAsync()
                .Then(requestBody =>
                {
                    owinRequest.Body = requestBody;
                    var responseMemoryStream = new MemoryStream();

                    var owinResponse = new OwinResponse(owinRequest)
                    {
                        Body = responseMemoryStream
                    };

                    return _invoke.Invoke(owinRequest.Dictionary)
                        .Then(() =>
                        {
                            var response = new HttpResponseMessage();
                            response.StatusCode = (HttpStatusCode)owinResponse.StatusCode;
                            response.ReasonPhrase = owinResponse.ReasonPhrase;
                            response.RequestMessage = request;
                            // response.Version = owinResponse.Protocol;

                            responseMemoryStream.Seek(0, SeekOrigin.Begin);
                            response.Content = new StreamContent(responseMemoryStream);
                            foreach (var header in owinResponse.Headers)
                            {
                                if (!response.Headers.TryAddWithoutValidation(header.Key, header.Value))
                                {
                                    response.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);
                                }
                            }
                            return response;
                        });
                });
        }
Exemplo n.º 5
0
        public Task Invoke(IDictionary<string, object> environment)
        {
            var request = new OwinRequest(environment);
            if (string.IsNullOrEmpty(_options.Path) || string.Equals(request.Path, _options.Path, StringComparison.OrdinalIgnoreCase))
            {
                // TODO: Make it pretty
                OwinResponse response = new OwinResponse(environment);
                response.ContentType = "text/html";

                StringBuilder builder = new StringBuilder();
                builder.AppendLine("<html>")

                .AppendLine("<head>")
                .AppendLine("<title>")
                .AppendLine("Welcome")
                .AppendLine("</title>")
                .AppendLine("</head>")

                .AppendLine("<body>")
                .AppendLine("<H1>Welcome</H1>")
                .AppendLine("<p>You have reached the default application page.</p>")
                .AppendLine("<H4>Additional Resources:</H4>")
                .AppendLine("<ul>")
                .AppendLine("<li><a href=\"http://katanaproject.codeplex.com/\">Katana Project</a>")
                .AppendLine("<li><a href=\"http://www.owin.org/\">owin.org</a>")
                .AppendLine("</ul>")
                .AppendLine("</body>")
                .AppendLine("</html>");
                return response.WriteAsync(builder.ToString());
            }
            return _next(environment);
        }
        public async Task Invoke(IDictionary<string, object> environment)
        {
            await _next(environment);

            var response = new OwinResponse(environment);

            if (response.Body == Stream.Null)
            {
                return;
            }

            string connection = response.GetHeader("Connection");

            if (response.Protocol.Equals("HTTP/1.1", StringComparison.OrdinalIgnoreCase) && 
                String.Equals(connection, "Close", StringComparison.OrdinalIgnoreCase))
            {
                var ms = new MemoryStream();

                using (response.Body)
                {
                    await response.Body.CopyToAsync(ms).ConfigureAwait(continueOnCapturedContext: false);
                }
                ms.Seek(0, SeekOrigin.Begin);
                response.Body = ms;
            }
        }
Exemplo n.º 7
0
        public async Task Invoke(IDictionary<string, object> env)
        {
            var request = new OwinRequest(env);
            var response = new OwinResponse(env);

            int id;
            if (int.TryParse(request.Path.Substring(1), out id))
            {
                switch (request.Method)
                {
                    case "GET":
                        var job = await _jobList.GetJob(id);
                        JsonSerializer.SerializeToStream(job, response.Body);
                        break;
                    case "DELETE":
                        _jobList.DeleteJob(id);
                        break;
                    default:
                        throw new NotImplementedException();
                }
            }
            else
            {
                JsonSerializer.SerializeToStream(await _jobList.ListJobs(), response.Body);
            }
        }
Exemplo n.º 8
0
        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new OwinRequest(env);
            var response = new OwinResponse(env);

            if (!request.Uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                var builder = new UriBuilder(request.Uri);
                builder.Scheme = "https";

                if (request.Uri.IsDefaultPort)
                {
                    builder.Port = -1;
                }

                response.SetHeader("Location", builder.ToString());
                response.StatusCode = 302;

                return TaskAsyncHelper.Empty;
            }
            else
            {
                return _next(env);
            }
        }
        public void Init()
        {
            table = new Mock<IRouteTable>();
            renderer = new Mock<IRazorRenderer>();
            request = new OwinRequest(new Dictionary<string, object>());
            response = new OwinResponse(new Dictionary<string, object>()) { Headers = new Dictionary<string, string[]>(), Body = new MemoryStream() };

            middleware = new RazorMiddleware(table.Object, renderer.Object);
        }
        Task UpgradeToWebSockets(OwinRequest request, OwinResponse response, Func<Task> next)
        {
            if (!request.CanAccept)
                return next();

            request.Accept(WebSocketEcho);

            return Task.FromResult<object>(null);
        }
 public Task Invoke(IDictionary<string, object> env)
 {
     var request = new OwinRequest(env);
     var response = new OwinResponse(env);
     if (!request.IsLocal)
     {
         response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
         return Task.FromResult(0);
     }
     return _next(env);
 }
Exemplo n.º 12
0
        private static void RewindResponseBody(IDictionary<string, object> environment)
        {
            var response = new OwinResponse(environment);

            var ms = response.Body as MemoryStream;
            if (ms != null)
            {
                // Rewind
                ms.Seek(0, SeekOrigin.Begin);
            }
        }
Exemplo n.º 13
0
 private static Task InvokeHandler(OwinResponse res, Func<OwinRequest, object> routeHandler, OwinRequest req)
 {
     var result = routeHandler(req);
     var flaskyResponse = result as IResponse;
     if(flaskyResponse != null)
     {
         return flaskyResponse.Write(res);
     }
     res.ContentType = "text/plain";
     return res.WriteAsync(result.ToString());
 }
Exemplo n.º 14
0
 public Task Invoke(IDictionary<string, object> environment)
 {
     var request = new OwinRequest(environment);
     if (_routeMatcher.HasMatch(request))
     {
         var response = new OwinResponse(environment);
         var routeHandler = _routeMatcher.GetMatch(request);
         return InvokeHandler(response, routeHandler, request);
     }
     return _next(environment);
 }
Exemplo n.º 15
0
 public StaticCompressionContext(IDictionary<string, object> environment, StaticCompressionOptions options, IEncoding encoding, ICompressedStorage storage)
 {
     _environment = environment;
     _options = options;
     _encoding = encoding;
     _encodingSuffix = "^" + _encoding.Name;
     _encodingSuffixQuote = "^" + _encoding.Name + "\"";
     _storage = storage;
     _request = new OwinRequest(environment);
     _response = new OwinResponse(environment);
 }
 public Task Invoke(IDictionary<string, object> environment)
 {
     var request = new OwinRequest(environment);
     if (string.IsNullOrEmpty(_options.Path) || string.Equals(request.Path, _options.Path, StringComparison.OrdinalIgnoreCase))
     {
         // TODO: Make it pretty
         OwinResponse response = new OwinResponse(environment);
         response.ContentType = "text/plain";
         return response.WriteAsync("Welcome to Katana");
     }
     return _next(environment);
 }
Exemplo n.º 17
0
        public async Task Invoke(IDictionary<string, object> environment)
        {
            await _next(environment);

            var response = new OwinResponse(environment);
            var encoding = response.GetHeader("Content-Encoding");

            if (String.Equals(encoding, "gzip", StringComparison.OrdinalIgnoreCase))
            {
                response.Body = new GZipStream(response.Body, CompressionMode.Decompress);
            }
        }
        public Task Invoke(IDictionary<string, object> environment)
        {
            OwinRequest request = new OwinRequest(environment);
            OwinResponse response = new OwinResponse(environment);

            response.ContentType = "text/plain";

            string responseText = request.GetHeader("breadcrumbs") + "\r\n"
                + "PathBase: " + request.PathBase + "\r\n"
                + "Path: " + request.Path + "\r\n";

            return response.WriteAsync(responseText);
        }
Exemplo n.º 19
0
        // Invoked once per request.
        public Task Invoke(IDictionary<string, object> environment)
        {
            OwinResponse owinResponse = new OwinResponse(environment);

	        string responseText = "Hello World";
	        byte[] responseBytes = Encoding.UTF8.GetBytes(responseText);

	        owinResponse.SetHeader("Content-Length", responseBytes.Length.ToString(CultureInfo.InvariantCulture));
            owinResponse.SetHeader("Content-Type", "text/plain");

            return owinResponse.Body.WriteAsync(responseBytes, 0, responseBytes.Length);
            // return Task.FromResult<object>(null);
        }
Exemplo n.º 20
0
        public async Task Invoke(IDictionary<string, object> environment)
        {
            var request = new OwinRequest(environment);
            Uri uri = request.Uri;

            // Create a stream for the host and port so we can send the request
            Stream stream = await _streamFactory.CreateStream(uri).ConfigureAwait(continueOnCapturedContext: false);

            var requestWriter = new StreamWriter(stream);

            // Request line
            requestWriter.WriteLine("{0} {1} {2}", request.Method, uri.LocalPath, request.Protocol);

            // Write headers
            foreach (var header in request.Headers)
            {
                requestWriter.WriteLine("{0}: {1}", header.Key, request.GetHeader(header.Key));
            }

            // End headers
            requestWriter.WriteLine();

            if (request.Body == null)
            {
                // End request
                requestWriter.WriteLine();
            }

            // Flush buffered content to the stream async
            await requestWriter.FlushAsync().ConfigureAwait(continueOnCapturedContext: false);

            if (request.Body != null)
            {
                // Copy the body to the request
                await request.Body.CopyToAsync(stream).ConfigureAwait(continueOnCapturedContext: false);
            }

            var response = new OwinResponse(environment);

            // Parse the response
            HttpParser.ParseResponse(stream, (protocol, statusCode, reasonPhrase) =>
            {
                response.Protocol = protocol;
                response.StatusCode = statusCode;
                response.ReasonPhrase = reasonPhrase;
            },
            (key, value) => response.SetHeader(key, value));

            // Set the body to the rest of the stream
            response.Body = stream;
        }
Exemplo n.º 21
0
        private static OwinRequest CreateRequest(string url, string method)
        {
            var uri = new Uri(url);
            var request = OwinRequest.Create();
            request.Protocol = "HTTP/1.1";
            request.Method = method;

            // Setup a empty stream by default
            var response = new OwinResponse(request);
            response.Body = new MemoryStream();

            BuildRequestFromUri(request, uri);
            return request;
        }
        private static async Task SendFileToResponse(OwinResponse response, CrossAppDomainResponseFile file) {
            if(response.CanSendFile)
            {
                await response.SendFileAsync(file.Path, file.Length, file.Offset, CancellationToken.None);
                return;
            }

            var buffer = new byte[file.Length - file.Offset];
            using (var stream = File.OpenRead(file.Path)) {
                stream.Seek(file.Offset, SeekOrigin.Begin);
                await stream.ReadAsync(buffer, 0, (int)file.Length);
            }
            await response.WriteAsync(buffer);
        }
Exemplo n.º 23
0
            public async Task Invoke(IDictionary<string, object> env) {

                OwinRequest request = new OwinRequest(env);
                if (request.Path == "/raw") {

                    OwinResponse response = new OwinResponse(request);
                    response.ContentType = "text/plain";
                    await response.WriteAsync("Hello from OWIN!");
                }
                else {

                    await _nextFunc(env);
                }
            }
Exemplo n.º 24
0
        public async Task ScriptFileCanBeExecutedByName()
        {
            var factory = new RoslynAppLoaderFactory();
            Func<string, Action<IAppBuilder>> loader = factory.Create(_ => null);
            Action<IAppBuilder> startup = loader.Invoke("Simple.csx");
            var builder = new AppBuilder();
            startup.Invoke(builder);
            var app = (AppFunc)builder.Build(typeof(AppFunc));

            OwinRequest req = OwinRequest.Create();
            await app.Invoke(req.Dictionary);
            var res = new OwinResponse(req);
            res.StatusCode.ShouldBe(24601);
        }
Exemplo n.º 25
0
        public async Task Invoke(IDictionary<string, object> env)
        {
            object value;
            if (env.TryGetValue("server.User", out value))
            {
                var windowsPrincipal = value as WindowsPrincipal;
                if (windowsPrincipal != null && windowsPrincipal.Identity.IsAuthenticated)
                {
                    await _next(env);

                    var request = new OwinRequest(env);
                    var response = new OwinResponse(env);

                    if (response.StatusCode == 401)
                    {
                        // We're going no add the identifier claim
                        var nameClaim = windowsPrincipal.FindFirst(ClaimTypes.Name);

                        // This is the domain name
                        string name = nameClaim.Value;

                        // If the name is something like DOMAIN\username then
                        // grab the name part
                        var parts = name.Split(new[] { '\\' }, 2);

                        string shortName = parts.Length == 1 ? parts[0] : parts[parts.Length - 1];

                        // REVIEW: Do we want to preserve the other claims?

                        // Normalize the claims here
                        var claims = new List<Claim>();
                        claims.Add(new Claim(ClaimTypes.NameIdentifier, name));
                        claims.Add(new Claim(ClaimTypes.Name, shortName));
                        claims.Add(new Claim(ClaimTypes.AuthenticationMethod, "Windows"));
                        var identity = new ClaimsIdentity(claims, Constants.JabbRAuthType);
                        var claimsPrincipal = new ClaimsPrincipal(identity);

                        response.SignIn(claimsPrincipal);

                        response.StatusCode = 302;
                        response.SetHeader("Location", request.PathBase + request.Path);
                    }

                    return;
                }
            }

            await _next(env);
        }
Exemplo n.º 26
0
        public static AppFunc Middleware(AppFunc app)
        {
            return env =>
            {
                var request = new OwinRequest(env);
                var websocketVersion = request.Get<string>(OwinConstants.WebSocket.Version);
                WebSocketAccept webSocketAccept = request.Get<WebSocketAccept>(OwinConstants.WebSocket.Accept);

                if (request.CanUpgrade && websocketVersion == null) // If we have opaque support and no WebSocket support yet
                {
                    if (IsWebSocketRequest(env))
                    {
                        // TODO: check for correct requested version of WebSocket protocol
                        IDictionary<string, object> acceptOptions = null;
                        WebSocketFunc webSocketFunc = null;

                        // Announce websocket support
                        env[OwinConstants.WebSocket.Accept] = new WebSocketAccept(
                            (options, callback) =>
                            {
                                acceptOptions = options;
                                webSocketFunc = callback;
                                env[OwinConstants.ResponseStatusCode] = 101;
                            });

                        return app(env).ContinueWith(t =>
                        {
                            OwinResponse response = new OwinResponse(env);
                            if (response.StatusCode == 101
                                && webSocketFunc != null)
                            {
                                SetWebSocketResponseHeaders(env, acceptOptions);

                                request.UpgradeDelegate(acceptOptions, opaqueEnv =>
                                {
                                    WebSocketLayer webSocket = new WebSocketLayer(opaqueEnv);
                                    return webSocketFunc(webSocket.Environment)
                                        .ContinueWith(tt => webSocket.CleanupAsync());
                                });
                            }
                        });
                    }
                }

                // else
                return app(env);
            };
        }
Exemplo n.º 27
0
        private string BuildRedirectUrl(OwinResponse response)
        {
            string location = response.GetHeader("Location");

            Uri uri;
            if (Uri.TryCreate(location, UriKind.Relative, out uri))
            {
                // If location is relative, we need to build a full url
                var previousRequest = new OwinRequest(response.Dictionary);
                var uriBuilder = new UriBuilder(previousRequest.Uri);
                uriBuilder.Path = location;

                return uriBuilder.ToString();
            }

            return location;
        }
Exemplo n.º 28
0
        private static Task RequestDump(OwinRequest request, OwinResponse response)
        {
            var builder = new StringBuilder();
            builder.AppendLine("<h1>Katana demo op TechDays</h1>");
            builder.AppendLine("<h2>request.Dictionary</h2>");

            builder.Append("<table>");
            foreach (var item in request.Dictionary)
            {
                builder.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>",
                    item.Key, item.Value);
            }
            builder.Append("</table>");

            response.ContentType = "text/html";
            return response.WriteAsync(builder.ToString());
        }
Exemplo n.º 29
0
        /// <summary></summary>
        /// <param name="environment"></param>
        /// <returns></returns>
        public async Task Invoke(IDictionary<string, object> environment)
        {
            OwinRequest request = new OwinRequest(environment);
            OwinResponse response = new OwinResponse(environment);
            CancellationToken cancellationToken = request.CallCancelled;

            AuthenticationHeaderValue authorization;
            string authorizationHeaderError;

            if (!TryParseAuthorizationHeader(request, out authorization, out authorizationHeaderError))
            {
                response.StatusCode = 400;
                cancellationToken.ThrowIfCancellationRequested();
                await WriteMessage(authorizationHeaderError, response, cancellationToken);
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();
            IBasicAuthenticationResult result = await AuthenticateAsync(authorization, cancellationToken);

            int errorStatusCode;
            string errorMessage;

            if (!TryProcessResult(result, environment, out errorStatusCode, out errorMessage))
            {
                response.StatusCode = errorStatusCode;
                cancellationToken.ThrowIfCancellationRequested();
                await AddChallengeOnUnauthorizedAsync(response, cancellationToken);
                cancellationToken.ThrowIfCancellationRequested();
                await WriteMessage(errorMessage, response, cancellationToken);
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();
            AuthenticationHeaderValue challenge = await _protocol.CreateChallengeAsync(cancellationToken);
            if (!TryRegisterOnSendingHeaders(challenge, request, response, out errorMessage))
            {
                response.StatusCode = 500;
                cancellationToken.ThrowIfCancellationRequested();
                await WriteMessage(errorMessage, response, cancellationToken);
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();
            await _next(environment);
        }
Exemplo n.º 30
0
        public async Task Invoke(IDictionary<string, object> env)
        {
            var httpRequest = new Gate.Request(env);
            var httpResponse = new OwinResponse(env);

            string url;
            Uri uri;
            if (!httpRequest.Query.TryGetValue("url", out url) ||
                String.IsNullOrEmpty(url) ||
                !Uri.TryCreate(url, UriKind.Absolute, out uri) ||
                !ImageContentProvider.IsValidImagePath(uri) ||
                !IsAuthenticated(env))
            {
                httpResponse.StatusCode = 404;
                return;
            }

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
                var response = (HttpWebResponse)await request.GetResponseAsync();

                if (!ImageContentProvider.IsValidContentType(response.ContentType) &&
                    response.ContentLength > _settings.ProxyImageMaxSizeBytes)
                {
                    httpResponse.StatusCode = 404;
                    return;
                }

                httpResponse.SetHeader("Content-Type", response.ContentType);
                httpResponse.StatusCode = (int)response.StatusCode;

                using (response)
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        await stream.CopyToAsync(httpResponse.Body);
                    }
                }
            }
            catch
            {
                httpResponse.StatusCode = 404;
            }
        }
Exemplo n.º 31
0
 public bool Equals(OwinResponse other)
 {
     return(Equals(_dictionary, other._dictionary));
 }