private void SetHttp2UpgradeHeadersAndStatusCode(OwinResponse owinResponse)
 {
     owinResponse.StatusCode = 101;
     owinResponse.ReasonPhrase = "Switching Protocols";
     owinResponse.SetHeader("Connection", "Upgrade");
     owinResponse.SetHeader("Upgrade", "HTTP/2.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);
        }
        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 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;
        }
        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);
        }
        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;
            }
        }
Exemple #7
0
        public async Task Invoke(IDictionary<string, object> env)
        {
            var httpRequest = new OwinRequest(env);

            if (!httpRequest.Path.StartsWith(_path))
            {
                await _next(env);
                return;
            }

            var httpResponse = new OwinResponse(env);

            var qs = new QueryStringCollection(httpRequest.QueryString);

            string url = qs["url"];

            Uri uri;
            if (String.IsNullOrEmpty(url) ||
                !ImageContentProvider.IsValidImagePath(url) ||
                !Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                httpResponse.StatusCode = 404;
                await TaskAsyncHelper.Empty;
                return;
            }

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

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

            using (response)
            {
                using (Stream stream = response.GetResponseStream())
                {
                    await stream.CopyToAsync(httpResponse.Body);
                }
            }
        }
        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new OwinRequest(env);
            var response = new OwinResponse(env);

            var requestPath = Uri.UnescapeDataString(request.Path);

            var backgrounds = DataManager.ActualBackgroundStorage;

            if (requestPath.StartsWith("/backgrounds/"))
            {
                if (request.Method != "GET")
                    return response.RespondMethodNotAllowed();

                var query = requestPath.Substring("/backgrounds".Length);

                if (query.EndsWith("/list"))
                {
                    string path = query.Substring(0, query.Length - "list".Length);
                    var dir = backgrounds.GetDirectory(path);

                    try
                    {
                        StringBuilder sb = new StringBuilder();
                        ListBackgroundEntries(dir, sb);

                        return response.RespondString(sb.ToString());
                    }
                    catch (FileNotFoundException)
                    {
                        return response.RespondNotFound();
                    }
                }
                else if (query == "/listall")
                {
                    StringBuilder sb = new StringBuilder();
                    ListBackgroundEntries(backgrounds.Root, sb, true);
                    return response.RespondString(sb.ToString());
                }
                else
                {
                    bool preview = false;
                    if (query.EndsWith("/preview"))
                    {
                        preview = true;
                        query = query.Substring(0, query.Length - "/preview".Length);
                    }

                    try
                    {
                        var file = backgrounds.GetFile(query);
                        var contentType = file.MimeType;

                        if (!String.IsNullOrEmpty(contentType))
                        {
                            response.SetHeader("Content-Type", contentType);
                        }
                        return response.RespondDownloaded(preview ? file.PreviewUri : file.Uri);
                    }
                    catch (FileNotFoundException)
                    {
                        return response.RespondNotFound();
                    }
                }
            }
            else
            {
                return next(env);
            }
        }
Exemple #9
0
		private async Task RespondGetSong(OwinResponse response, SongStorage storage, string name)
		{
			bool success = true;
			try
			{
				using (var entry = await storage.GetAsync(name, CancellationToken.None))
				{
					response.SetHeader("Content-Type", "text/xml");
					if (entry.LastModified.HasValue)
					{
						response.SetHeader("Last-Modified", entry.LastModified.Value.ToString("r"));
					}
					await entry.Stream.CopyToAsync(response.Body);
				}
			}
			catch (FileNotFoundException)
			{
				success = false;
			}
			catch (ArgumentException)
			{
				success = false;
			}

			if (!success)
			{
				await response.RespondNotFound();
			}
		}