private void ProcessRequest(OwinEnvironment ctx, JArray results, JToken request, Func <OutputStreamType, bool> authFunc) { RPCRequest req = null; try { req = RPCRequest.FromJson(request); } catch (RPCError err) { results.Add(new RPCResponse(null, err).ToJson()); return; } try { var methods = authFunc != null?this.methods.Where(method => authFunc(method.Grant)): this.methods; var m = methods.FirstOrDefault(method => method.Name == req.Method); if (m != null) { var res = m.Invoke(ctx, req.Parameters); if (req.Id != null) { results.Add(new RPCResponse(req.Id, res).ToJson()); } } else { throw new RPCError(RPCErrorCode.MethodNotFound); } } catch (RPCError err) { results.Add(new RPCResponse(req.Id, err).ToJson()); } }
public void Setup() { _env = new Dictionary <string, object>(); _env[RequestHeaderKey] = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase); //Per OWIN 1.0 spec. _env[ResponseHeaderKey] = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase); //Per OWIN 1.0 spec. _owinEnvironment = new OwinEnvironment(_env); }
private async Task FragmentHandler(OwinEnvironment ctx, ParsedRequest req, Channel channel) { var ct = ctx.Request.CallCancelled; using (var subscription = HLSChannelSink.GetSubscription(this, channel, ctx, req.Session)) { subscription.Stopped.ThrowIfCancellationRequested(); using (var cts = CancellationTokenSource.CreateLinkedTokenSource(ct, subscription.Stopped)) { cts.CancelAfter(10000); var segments = await subscription.Segmenter.GetSegmentsAsync(cts.Token).ConfigureAwait(false); var segment = segments.FirstOrDefault(s => s.Index == req.FragmentNumber); if (segment.Index == 0) { ctx.Response.StatusCode = HttpStatusCode.NotFound; } else { ctx.Response.StatusCode = HttpStatusCode.OK; ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*"); ctx.Response.ContentType = "video/MP2T"; ctx.Response.ContentLength = segment.Data.LongLength; await ctx.Response.WriteAsync(segment.Data, cts.Token).ConfigureAwait(false); } } } }
private async Task HLSHandler(OwinEnvironment ctx) { var ct = ctx.Request.CallCancelled; var req = ParsedRequest.Parse(ctx); if (!req.IsValid) { ctx.Response.StatusCode = req.Status; return; } Channel channel; try { channel = await GetChannelAsync(ctx, req, ct).ConfigureAwait(false); } catch (TaskCanceledException) { ctx.Response.StatusCode = HttpStatusCode.GatewayTimeout; return; } if (channel == null) { ctx.Response.StatusCode = HttpStatusCode.NotFound; return; } if (req.FragmentNumber.HasValue) { await FragmentHandler(ctx, req, channel).ConfigureAwait(false); } else { await PlayListHandler(ctx, req, channel).ConfigureAwait(false); } }
public async Task Invoke(OwinEnvironment ctx) { var cancel_token = ctx.Request.CallCancelled; var localpath = Path.GetFullPath(CombinePath(LocalPath, ctx.Request.Path)); if (Directory.Exists(localpath)) { localpath = Path.Combine(localpath, "index.html"); if (!File.Exists(localpath)) { ctx.Response.StatusCode = HttpStatusCode.Forbidden; return; } } if (File.Exists(localpath)) { var contents = File.ReadAllBytes(localpath); var content_desc = GetFileDesc(Path.GetExtension(localpath)); ctx.Response.ContentType = content_desc.MimeType; ctx.Response.ContentLength = contents.LongLength; var acinfo = ctx.GetAccessControlInfo(); if (acinfo?.AuthenticationKey != null) { ctx.Response.Headers.Add("Set-Cookie", $"auth={acinfo.AuthenticationKey.GetToken()}; Path=/"); } await ctx.Response.WriteAsync(contents, cancel_token).ConfigureAwait(false); } else { ctx.Response.StatusCode = HttpStatusCode.NotFound; } }
private HLSChannelSink(HTTPLiveStreamingDirectOwinApp owner, OwinEnvironment ctx, Tuple <Channel, string> session) { this.owner = owner; this.session = session; connectionInfo.AgentName = ctx.Request.Headers.Get("User-Agent"); connectionInfo.LocalDirects = null; connectionInfo.LocalRelays = null; connectionInfo.ProtocolName = "HLS Direct"; connectionInfo.RecvRate = null; connectionInfo.SendRate = null; connectionInfo.ContentPosition = 0; var remoteEndPoint = new IPEndPoint(IPAddress.Parse(ctx.Request.RemoteIpAddress), ctx.Request.RemotePort ?? 0); connectionInfo.RemoteEndPoint = remoteEndPoint; connectionInfo.RemoteName = remoteEndPoint.ToString(); connectionInfo.RemoteSessionID = null; connectionInfo.RemoteHostStatus = RemoteHostStatus.Receiving; if (remoteEndPoint.Address.GetAddressLocality() < 2) { connectionInfo.RemoteHostStatus |= RemoteHostStatus.Local; } connectionInfo.Status = ConnectionStatus.Connected; connectionInfo.Type = ConnectionType.Direct; getRecvRate = ctx.Get <Func <float> >(OwinEnvironment.PeerCastStation.GetRecvRate); getSendRate = ctx.Get <Func <float> >(OwinEnvironment.PeerCastStation.GetSendRate); contentSink = HLSContentSink.GetSubscription(owner, Channel); }
internal bool HandleUpgradeInsecureRequest(OwinEnvironment env) { const string https = "https"; //Already on https. if (https.Equals(env.RequestScheme)) { return(false); } //CSP upgrade-insecure-requests is disabled if (!_config.Enabled || !_config.UpgradeInsecureRequestsDirective.Enabled) { return(false); } if (!CspUpgradeHelper.UaSupportsUpgradeInsecureRequests(env)) { return(false); } var upgradeUri = new UriBuilder($"https://{env.RequestHeaders.Host}") { Port = _config.UpgradeInsecureRequestsDirective.HttpsPort, Path = env.RequestPathBase + env.RequestPath, }; //Redirect env.ResponseHeaders.SetHeader("Vary", "Upgrade-Insecure-Requests"); env.ResponseHeaders.Location = upgradeUri.Uri.AbsoluteUri; env.ResponseStatusCode = 307; return(true); }
private static async Task AdminHandler(OwinEnvironment ctx) { var cancel_token = ctx.Request.CallCancelled; switch (ctx.Request.Query.Get("cmd")) { case "viewxml": //リレー情報XML出力 await OnViewXML(ctx, cancel_token).ConfigureAwait(false); break; case "stop": //チャンネル停止 await OnStop(ctx, cancel_token).ConfigureAwait(false); break; case "bump": //チャンネル再接続 await OnBump(ctx, cancel_token).ConfigureAwait(false); break; default: ctx.Response.StatusCode = HttpStatusCode.BadRequest; break; } }
public static AddMiddleware UseOwin(this IApplicationBuilder builder) { AddMiddleware add = middleware => { Func <RequestDelegate, RequestDelegate> middleware1 = next1 => { AppFunc exitMiddlware = env => { return(next1((HttpContext)env[typeof(HttpContext).FullName])); }; var app = middleware(exitMiddlware); return(httpContext => { // Use the existing OWIN env if there is one. IDictionary <string, object> env; var owinEnvFeature = httpContext.Features.Get <IOwinEnvironmentFeature>(); if (owinEnvFeature != null) { env = owinEnvFeature.Environment; env[typeof(HttpContext).FullName] = httpContext; } else { env = new OwinEnvironment(httpContext); } return app.Invoke(env); }); }; builder.Use(middleware1); }; // Adapt WebSockets by default. add(WebSocketAcceptAdapter.AdaptWebSockets); return(add); }
public void OwinEnvironmentImplementsGetEnumerator() { var owinEnvironment = new OwinEnvironment(CreateContext()); Assert.NotNull(owinEnvironment.GetEnumerator()); Assert.NotNull(((IEnumerable)owinEnvironment).GetEnumerator()); }
public static AddMiddleware UseOwin(this IApplicationBuilder builder) { AddMiddleware add = middleware => { Func<RequestDelegate, RequestDelegate> middleware1 = next1 => { AppFunc exitMiddlware = env => { return next1((HttpContext)env[typeof(HttpContext).FullName]); }; var app = middleware(exitMiddlware); return httpContext => { // Use the existing OWIN env if there is one. IDictionary<string, object> env; var owinEnvFeature = httpContext.GetFeature<IOwinEnvironmentFeature>(); if (owinEnvFeature != null) { env = owinEnvFeature.Environment; env[typeof(HttpContext).FullName] = httpContext; } else { env = new OwinEnvironment(httpContext); } return app.Invoke(env); }; }; builder.Use(middleware1); }; // Adapt WebSockets by default. add(WebSocketAcceptAdapter.AdaptWebSockets); return add; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseOwin(pipeline => pipeline(next => context => { foreach (string key in context.Keys) { Console.WriteLine($"{key}: {context[key]}"); } return(next(context)); })); // alternative app.Use((context, next) => { OwinEnvironment environment = new OwinEnvironment(context); IDictionary <string, string[]> headers = (IDictionary <string, string[]>)environment.Single(item => item.Key == "owin.RequestHeaders").Value; return(next()); }); app.Use((context, next) => { OwinEnvironment environment = new OwinEnvironment(context); OwinFeatureCollection features = new OwinFeatureCollection(environment); IDictionary <string, string[]> headers = (IDictionary <string, string[]>)features.Environment["owin.RequestHeaders"]; return(next()); }); app.UseMvc(); }
internal override void PreInvokeNext(OwinEnvironment owinEnvironment) { owinEnvironment.NWebsecContext.ReferrerPolicy = _config; if (_headerResult.Action == HeaderResult.ResponseAction.Set) { owinEnvironment.ResponseHeaders.SetHeader(_headerResult.Name, _headerResult.Value); } }
public async Task Invoke(OwinEnvironment environment) { IocRegistration.RepositoryInitialization.BeginRequest(); await Next(environment); IocRegistration.RepositoryInitialization.EndRequest(); }
public static void Upgrade(this OwinEnvironment ctx, Func <IDictionary <string, object>, Task> handler) { var upgradeAction = (Action <IDictionary <string, object>, Func <IDictionary <string, object>, Task> >) ctx.Environment[OwinEnvironment.Opaque.Upgrade]; upgradeAction.Invoke(new Dictionary <string, object>(), handler); }
public async Task Invoke(OwinEnvironment environment) { Debug.WriteLine("Requesting: " + environment["owin.RequestPath"]); await Next(environment); Debug.WriteLine("Response: " + environment["owin.ResponseStatusCode"]); }
private static async Task OnViewXML(OwinEnvironment ctx, CancellationToken cancel_token) { var data = BuildViewXml(ctx.GetPeerCast()); ctx.Response.StatusCode = HttpStatusCode.OK; ctx.Response.ContentType = "text/xml;charset=utf-8"; ctx.Response.ContentLength = data.LongLength; await ctx.Response.WriteAsync(data, cancel_token).ConfigureAwait(false); }
public OwinEnvironmentTests() { _env = new Dictionary <string, object> { [RequestHeaderKey] = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase), //Per OWIN 1.0 spec. [ResponseHeaderKey] = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase) //Per OWIN 1.0 spec. }; _owinEnvironment = new OwinEnvironment(_env); }
public static AccessControlInfo GetAccessControlInfo(this OwinEnvironment ctx) { if (ctx.Environment.TryGetValue(OwinEnvironment.PeerCastStation.AccessControlInfo, out var obj)) { return(obj as AccessControlInfo); } else { return(null); } }
public static PeerCast GetPeerCast(this OwinEnvironment ctx) { if (ctx.Environment.TryGetValue(OwinEnvironment.PeerCastStation.PeerCast, out var obj)) { return(obj as PeerCast); } else { return(null); } }
public JToken ProcessRequest(OwinEnvironment ctx, string request_str, Func <OutputStreamType, bool> authFunc) { JToken req; try { req = ParseRequest(request_str); } catch (RPCError err) { return(new RPCResponse(null, err).ToJson()); } return(ProcessRequest(ctx, req, authFunc)); }
internal override void PreInvokeNext(OwinEnvironment owinEnvironment) { if (_config.HttpsOnly && !Https.Equals(owinEnvironment.RequestScheme, StringComparison.OrdinalIgnoreCase)) { return; } if (_headerResult.Action == HeaderResult.ResponseAction.Set) { owinEnvironment.ResponseHeaders.SetHeader(_headerResult.Name, _headerResult.Value); } }
public void OwinEnvironmentSuppliesDefaultsForMissingRequiredEntries() { HttpContext context = CreateContext(); IDictionary <string, object> env = new OwinEnvironment(context); object value; Assert.True(env.TryGetValue("owin.CallCancelled", out value), "owin.CallCancelled"); Assert.True(env.TryGetValue("owin.Version", out value), "owin.Version"); Assert.Equal(CancellationToken.None, env["owin.CallCancelled"]); Assert.Equal("1.0", env["owin.Version"]); }
public Task Invoke(HttpContext context) { var owinEnvironment = new OwinEnvironment(context); var owinFeatures = new OwinFeatureCollection(owinEnvironment); var requestId = owinFeatures.Environment.ContainsKey("owin.RequestId") ? owinFeatures.Environment["owin.RequestId"] : string.Empty; var requestMethod = owinFeatures.Environment.ContainsKey("owin.RequestMethod") ? owinFeatures.Environment["owin.RequestMethod"] : string.Empty; var requestPath = owinFeatures.Environment.ContainsKey("owin.RequestPath") ? owinFeatures.Environment["owin.RequestPath"] : string.Empty; this.logger.LogInformation("[RequestId: {0}][RequestMethod: {1}][RequestPath: {2}]", requestId, requestMethod, requestPath); return(this.next(context)); }
private static async Task<Channel> GetChannelAsync(OwinEnvironment ctx, ParsedRequest req, CancellationToken ct) { var tip = ctx.Request.Query.Get("tip"); var channel = ctx.GetPeerCast().RequestChannel(req.ChannelId, OutputStreamBase.CreateTrackerUri(req.ChannelId, tip), true); if (channel==null) { return null; } using (var cts=CancellationTokenSource.CreateLinkedTokenSource(ct)) { cts.CancelAfter(10000); await channel.WaitForReadyContentTypeAsync(cts.Token).ConfigureAwait(false); } return channel; }
public async Task Invoke(IDictionary <string, object> environment) { var env = new OwinEnvironment(environment); PreInvokeNext(env); if (_next != null) { await _next(environment); } PostInvokeNext(env); }
public void OwinEnvironmentDoesNotContainEntriesForMissingFeatures(string key) { HttpContext context = CreateContext(); IDictionary <string, object> env = new OwinEnvironment(context); object value; Assert.False(env.TryGetValue(key, out value)); Assert.Throws <KeyNotFoundException>(() => env[key]); Assert.False(env.Keys.Contains(key)); Assert.False(env.ContainsKey(key)); }
public async Task Invoke(OwinEnvironment ctx) { var cancel_token = ctx.Request.CallCancelled; ctx.Response.ContentType = "application/javascript"; ctx.Response.ContentLength = contents.LongLength; var acinfo = ctx.GetAccessControlInfo(); if (acinfo?.AuthenticationKey != null) { ctx.Response.Headers.Add("Set-Cookie", $"auth={acinfo.AuthenticationKey.GetToken()}; Path=/"); } await ctx.Response.WriteAsync(contents, cancel_token).ConfigureAwait(false); }
private static async Task InvokeIndexTXT(OwinEnvironment ctx) { var cancel_token = ctx.Request.CallCancelled; ctx.Response.ContentType = "text/plain;charset=utf-8"; var acinfo = ctx.GetAccessControlInfo(); if (acinfo?.AuthenticationKey != null) { ctx.Response.Headers.Add("Set-Cookie", $"auth={acinfo.AuthenticationKey.GetToken()}; Path=/"); } var peercast = ctx.GetPeerCast(); var indextxt = String.Join("\r\n", peercast.Channels.Select(c => BuildIndexTXTEntry(peercast, c))); await ctx.Response.WriteAsync(indextxt, cancel_token).ConfigureAwait(false); }
private static async Task InvokeRedirect(OwinEnvironment ctx) { var cancel_token = ctx.Request.CallCancelled; ctx.Response.ContentType = "text/plain;charset=utf-8"; ctx.Response.Headers.Set("Location", "/html/index.html"); var acinfo = ctx.GetAccessControlInfo(); if (acinfo?.AuthenticationKey != null) { ctx.Response.Headers.Add("Set-Cookie", $"auth={acinfo.AuthenticationKey.GetToken()}; Path=/"); } ctx.Response.StatusCode = HttpStatusCode.Moved; await ctx.Response.WriteAsync("Moving...", cancel_token).ConfigureAwait(false); }
internal override void PostInvokeNext(OwinEnvironment environment) { var statusCode = environment.ResponseStatusCode; if (!_redirectValidator.IsRedirectStatusCode(statusCode)) { return; } var scheme = environment.RequestScheme; var hostandport = environment.RequestHeaders.Host; var requestUri = new Uri(scheme + "://" + hostandport); _redirectValidator.ValidateRedirect(statusCode, environment.ResponseHeaders.Location, requestUri, _config); }
private Task<IClientResponse> ProcessRequest(string httpMethod, string url, Action<IClientRequest> prepareRequest, IDictionary<string, string> postData, bool disableWrites = false) { if (url == null) { throw new ArgumentNullException("url"); } if (prepareRequest == null) { throw new ArgumentNullException("prepareRequest"); } if (_appFunc == null) { throw new InvalidOperationException(); } if (_shutDownToken.IsCancellationRequested) { return TaskAsyncHelper.FromError<IClientResponse>(new InvalidOperationException("Service unavailable")); } var tcs = new TaskCompletionSource<IClientResponse>(); // REVIEW: Should we add a new method to the IClientResponse to trip this? var clientTokenSource = new SafeCancellationTokenSource(); var env = new OwinEnvironment(_appBuilder.Properties); // Request specific setup var uri = new Uri(url); env[OwinConstants.RequestProtocol] = "HTTP/1.1"; env[OwinConstants.CallCancelled] = clientTokenSource.Token; env[OwinConstants.RequestMethod] = httpMethod; env[OwinConstants.RequestPathBase] = String.Empty; env[OwinConstants.RequestPath] = uri.LocalPath; env[OwinConstants.RequestQueryString] = uri.Query.Length > 0 ? uri.Query.Substring(1) : String.Empty; env[OwinConstants.RequestScheme] = uri.Scheme; env[OwinConstants.RequestBody] = GetRequestBody(postData); var headers = new Dictionary<string, string[]>(); env[OwinConstants.RequestHeaders] = headers; headers.SetHeader("X-Server", "MemoryHost"); headers.SetHeader("X-Server-Name", InstanceName); if (httpMethod == "POST") { headers.SetHeader("Content-Type", "application/x-www-form-urlencoded"); } var networkObservable = new NetworkObservable(disableWrites); var clientStream = new ClientStream(networkObservable, clientTokenSource); var serverStream = new ServerStream(networkObservable); var response = new Response(clientStream); // Trigger the tcs on flush. This mimicks the client side networkObservable.OnFlush = () => tcs.TrySetResult(response); // Run the client function to initialize the request prepareRequest(new Request(env, networkObservable.Cancel)); env[OwinConstants.ResponseBody] = serverStream; env[OwinConstants.ResponseHeaders] = new Dictionary<string, string[]>(); _appFunc(env).ContinueWith(task => { var owinResponse = new OwinResponse(env); if (!IsSuccessStatusCode(owinResponse.StatusCode)) { tcs.TrySetException(new InvalidOperationException("Unsuccessful status code " + owinResponse.StatusCode)); } else if (task.IsFaulted) { tcs.TrySetException(task.Exception.InnerExceptions); } else if (task.IsCanceled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(response); } // Close the server stream when the request has ended serverStream.Close(); clientTokenSource.Dispose(); }); return tcs.Task; }