Пример #1
0
            private void SendResponseFileContent()
            {
                var localpath = GetPhysicalPath(this.request.Uri);

                if (localpath == null)
                {
                    throw new HTTPError(HttpStatusCode.Forbidden);
                }
                if (Directory.Exists(localpath))
                {
                    localpath = Path.Combine(localpath, "index.html");
                    if (!File.Exists(localpath))
                    {
                        throw new HTTPError(HttpStatusCode.Forbidden);
                    }
                }
                if (File.Exists(localpath))
                {
                    var contents     = File.ReadAllBytes(localpath);
                    var content_desc = GetFileDesc(Path.GetExtension(localpath));
                    var parameters   = new Dictionary <string, string> {
                        { "Content-Type", content_desc.MimeType },
                        { "Content-Length", contents.Length.ToString() },
                    };
                    Send(HTTPUtils.CreateResponseHeader(HttpStatusCode.OK, parameters));
                    if (this.request.Method == "GET")
                    {
                        Send(contents);
                    }
                }
                else
                {
                    throw new HTTPError(HttpStatusCode.NotFound);
                }
            }
Пример #2
0
 protected override void OnStarted()
 {
     base.OnStarted();
     Logger.Debug("Started");
     try {
         if (!HTTPUtils.CheckAuthorization(this.request, AccessControl.AuthenticationKey))
         {
             throw new HTTPError(HttpStatusCode.Unauthorized);
         }
         if (this.request.Method != "HEAD" && this.request.Method != "GET")
         {
             throw new HTTPError(HttpStatusCode.MethodNotAllowed);
         }
         if (this.request.Uri.AbsolutePath == "/")
         {
             SendResponseMoveToIndex();
         }
         else
         {
             SendResponseFileContent();
         }
     }
     catch (HTTPError err) {
         Send(HTTPUtils.CreateResponseHeader(err.StatusCode, new Dictionary <string, string> {
         }));
     }
     catch (UnauthorizedAccessException) {
         Send(HTTPUtils.CreateResponseHeader(HttpStatusCode.Forbidden, new Dictionary <string, string> {
         }));
     }
     Stop();
 }
Пример #3
0
            protected override void OnStarted()
            {
                base.OnStarted();
                Logger.Debug("Started");
                try {
                    if (this.request.Method != "HEAD" && this.request.Method != "GET")
                    {
                        throw new HTTPError(HttpStatusCode.MethodNotAllowed);
                    }
                    var    query = HTTPUtils.ParseQuery(this.request.Uri.Query);
                    string value;
                    if (query.TryGetValue("cmd", out value))
                    {
                        switch (value)
                        {
                        case "viewxml": //リレー情報XML出力
                            OnViewXML(query);
                            break;

                        default:
                            throw new HTTPError(HttpStatusCode.BadRequest);
                        }
                    }
                    else
                    {
                        throw new HTTPError(HttpStatusCode.BadRequest);
                    }
                }
                catch (HTTPError err) {
                    Send(HTTPUtils.CreateResponseHeader(err.StatusCode, new Dictionary <string, string> {
                    }));
                }
                Stop();
            }
Пример #4
0
            private void SendJson(JToken token)
            {
                var body       = System.Text.Encoding.UTF8.GetBytes(token.ToString());
                var parameters = new Dictionary <string, string> {
                    { "Content-Type", "application/json" },
                    { "Content-Length", body.Length.ToString() },
                };

                Send(HTTPUtils.CreateResponseHeader(HttpStatusCode.OK, parameters));
                Send(body);
            }
Пример #5
0
 protected override void OnStarted()
 {
     base.OnStarted();
     Logger.Debug("Started");
     try {
         if (this.request.Method == "HEAD" || this.request.Method == "GET")
         {
             var token      = GetVersionInfo();
             var body       = System.Text.Encoding.UTF8.GetBytes(token.ToString());
             var parameters = new Dictionary <string, string> {
                 { "Content-Type", "application/json" },
                 { "Content-Length", body.Length.ToString() },
             };
             Send(HTTPUtils.CreateResponseHeader(HttpStatusCode.OK, parameters));
             if (this.request.Method != "HEAD")
             {
                 Send(body);
             }
             Stop();
         }
         else if (this.request.Method == "POST")
         {
             string length;
             if (request.Headers.TryGetValue("CONTENT-LENGTH", out length))
             {
                 int len;
                 if (int.TryParse(length, out len) && len >= 0 && len <= RequestLimit)
                 {
                     bodyLength = len;
                     timeoutWatch.Start();
                 }
                 else
                 {
                     throw new HTTPError(HttpStatusCode.BadRequest);
                 }
             }
             else
             {
                 throw new HTTPError(HttpStatusCode.LengthRequired);
             }
         }
         else
         {
             throw new HTTPError(HttpStatusCode.MethodNotAllowed);
         }
     }
     catch (HTTPError err) {
         Send(HTTPUtils.CreateResponseHeader(err.StatusCode, new Dictionary <string, string> {
         }));
         Stop();
     }
 }
Пример #6
0
 protected override void OnStarted()
 {
     base.OnStarted();
     Logger.Debug("Started");
     try {
         if (this.request.Method != "HEAD" && this.request.Method != "GET")
         {
             throw new HTTPError(HttpStatusCode.MethodNotAllowed);
         }
         var localpath = GetPhysicalPath(this.request.Uri);
         if (localpath == null)
         {
             throw new HTTPError(HttpStatusCode.Forbidden);
         }
         if (Directory.Exists(localpath))
         {
             localpath = Path.Combine(localpath, "index.html");
             if (!File.Exists(localpath))
             {
                 throw new HTTPError(HttpStatusCode.Forbidden);
             }
         }
         if (File.Exists(localpath))
         {
             var contents     = File.ReadAllBytes(localpath);
             var content_desc = GetFileDesc(Path.GetExtension(localpath));
             var parameters   = new Dictionary <string, string> {
                 { "Content-Type", content_desc.MimeType },
                 { "Content-Length", contents.Length.ToString() },
             };
             Send(HTTPUtils.CreateResponseHeader(HttpStatusCode.OK, parameters));
             if (this.request.Method == "GET")
             {
                 Send(contents);
             }
         }
         else
         {
             throw new HTTPError(HttpStatusCode.NotFound);
         }
     }
     catch (HTTPError err) {
         Send(HTTPUtils.CreateResponseHeader(err.StatusCode, new Dictionary <string, string> {
         }));
     }
     catch (UnauthorizedAccessException) {
         Send(HTTPUtils.CreateResponseHeader(HttpStatusCode.Forbidden, new Dictionary <string, string> {
         }));
     }
     Stop();
 }
Пример #7
0
            private void OnViewXML(Dictionary <string, string> query)
            {
                var data       = BuildViewXml();
                var parameters = new Dictionary <string, string> {
                    { "Content-Type", "text/xml" },
                    { "Content-Length", data.Length.ToString() },
                };

                Send(HTTPUtils.CreateResponseHeader(HttpStatusCode.OK, parameters));
                if (this.request.Method != "HEAD")
                {
                    Send(data);
                }
            }
Пример #8
0
            private void SendResponseMoveToIndex()
            {
                var content    = "Moving...";
                var parameters = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" },
                    { "Content-Length", content.Length.ToString() },
                    { "Location", "/html/index.html" },
                };

                Send(HTTPUtils.CreateResponseHeader(HttpStatusCode.Moved, parameters));
                if (this.request.Method == "GET")
                {
                    Send(content);
                }
            }
Пример #9
0
        private async Task SendResponseMoveToIndex(OWINEnv env, CancellationToken cancel_token)
        {
            var content = System.Text.Encoding.UTF8.GetBytes("Moving...");

            env.SetResponseHeader("Content-Type", "text/plain");
            env.SetResponseHeader("Content-Length", content.Length.ToString());
            env.SetResponseHeader("Location", "/html/index.html");
            if (env.AccessControlInfo.AuthenticationKey != null)
            {
                env.SetResponseHeader("Set-Cookie", "auth=" + HTTPUtils.CreateAuthorizationToken(env.AccessControlInfo.AuthenticationKey));
            }
            env.ResponseStatusCode = (int)HttpStatusCode.Moved;
            if (env.RequestMethod == "GET")
            {
                await env.ResponseBody.WriteAsync(content, 0, content.Length, cancel_token).ConfigureAwait(false);
            }
        }
Пример #10
0
        private async Task SendResponseChannelList(OWINEnv env, CancellationToken cancel_token)
        {
            var channel_list = await GetYPChannels().ConfigureAwait(false);

            var contents = System.Text.Encoding.UTF8.GetBytes(ChannelsToIndex(channel_list));

            env.SetResponseHeader("Content-Type", "text/plain;charset=utf-8");
            env.SetResponseHeader("Content-Length", contents.Length.ToString());
            if (env.AccessControlInfo.AuthenticationKey != null)
            {
                env.SetResponseHeader("Set-Cookie", "auth=" + HTTPUtils.CreateAuthorizationToken(env.AccessControlInfo.AuthenticationKey));
            }
            if (env.RequestMethod == "GET")
            {
                await env.ResponseBody.WriteAsync(contents, 0, contents.Length, cancel_token).ConfigureAwait(false);
            }
        }
Пример #11
0
            private void OnStop(Dictionary <string, string> query)
            {
                HttpStatusCode status;
                var            parameters = new Dictionary <string, string> {
                };
                string res;
                var    channel = FindChannelFromQuery(query);

                if (channel != null)
                {
                    PeerCast.CloseChannel(channel);
                    status = HttpStatusCode.OK;
                    res    = "OK";
                }
                else
                {
                    status = HttpStatusCode.NotFound;
                    res    = "Channel NotFound";
                }
                Send(HTTPUtils.CreateResponse(status, parameters, res));
            }
Пример #12
0
 private async Task OnProcess(IDictionary<string, object> owinenv)
 {
   var env = new OWINEnv(owinenv);
   var cancel_token = env.CallCanlelled;
   try {
     if (!HTTPUtils.CheckAuthorization(env.GetAuthorizationToken(), env.AccessControlInfo)) {
       throw new HTTPError(HttpStatusCode.Unauthorized);
     }
     if (env.RequestMethod!="HEAD" && env.RequestMethod!="GET") {
       throw new HTTPError(HttpStatusCode.MethodNotAllowed);
     }
     var query = env.RequestParameters;
     string value;
     if (query.TryGetValue("cmd", out value)) {
       switch (value) {
       case "viewxml": //リレー情報XML出力
         await OnViewXML(env, query, cancel_token).ConfigureAwait(false);
         break;
       case "stop": //チャンネル停止
         await OnStop(env, query, cancel_token).ConfigureAwait(false);
         break;
       case "bump": //チャンネル再接続
         await OnBump(env, query, cancel_token).ConfigureAwait(false);
         break;
       default:
         throw new HTTPError(HttpStatusCode.BadRequest);
       }
     }
     else {
       throw new HTTPError(HttpStatusCode.BadRequest);
     }
   }
   catch (HTTPError err) {
     env.ResponseStatusCode = (int)err.StatusCode;
   }
   catch (UnauthorizedAccessException) {
     env.ResponseStatusCode = (int)HttpStatusCode.Forbidden;
   }
 }
Пример #13
0
        private async Task ProcessResponse(IDictionary <string, object> env, CancellationToken cancel_token)
        {
            var headers       = (Dictionary <string, string[]>)env["owin.ResponseHeaders"];
            var body          = (MemoryStream)env["owin.ResponseBody"];
            var protocol      = GetEnvValue(env, "owin.ResponseProtocol", this.request.Protocol);
            var status_code   = GetEnvValue(env, "owin.ResponseStatusCode", 200);
            var reason_phrase = GetEnvValue(env, "owin.ResponseReasonPhrase", HTTPUtils.GetReasonPhrase(status_code));
            var method        = GetEnvValue(env, "owin.RequestMethod", "GET");

            body.Close();
            var body_ary = body.ToArray();

            if (ResponseHasMessageBody(method, status_code))
            {
                SetHeader(headers, "Content-Length", body_ary.Length.ToString());
            }
            if (status_code == (int)HttpStatusCode.Unauthorized)
            {
                SetHeader(headers, "WWW-Authenticate", "Basic realm=\"PeerCastStation\"");
            }

            var header = new System.Text.StringBuilder($"{protocol} {status_code} {reason_phrase}\r\n");

            foreach (var kv in headers)
            {
                foreach (var v in kv.Value)
                {
                    header.Append($"{kv.Key}: {v}\r\n");
                }
            }
            header.Append("\r\n");
            await Connection.WriteUTF8Async(header.ToString(), cancel_token).ConfigureAwait(false);

            if (body_ary.Length > 0)
            {
                await Connection.WriteAsync(body_ary, cancel_token).ConfigureAwait(false);
            }
        }
Пример #14
0
        protected override async Task <StopReason> DoProcess(CancellationToken cancel_token)
        {
            try {
                var env = await CreateOWINEnvironment(cancel_token).ConfigureAwait(false);

                await application.AppFunc.Invoke(env).ConfigureAwait(false);
                await ProcessResponse(env, cancel_token).ConfigureAwait(false);

                if (request.KeepAlive)
                {
                    this.HandlerResult = HandlerResult.Continue;
                }
            }
            catch (IOException) {
                return(StopReason.ConnectionError);
            }
            catch (Exception) {
                await Connection.WriteUTF8Async(
                    HTTPUtils.CreateResponseHeader(HttpStatusCode.InternalServerError),
                    cancel_token).ConfigureAwait(false);
            }
            return(StopReason.OffAir);
        }
Пример #15
0
        private async Task OnRedirect(IDictionary <string, object> owinenv)
        {
            var env          = new OWINEnv(owinenv);
            var cancel_token = env.CallCanlelled;

            try {
                if (!HTTPUtils.CheckAuthorization(env.GetAuthorizationToken(), env.AccessControlInfo))
                {
                    throw new HTTPError(HttpStatusCode.Unauthorized);
                }
                if (env.RequestMethod != "HEAD" && env.RequestMethod != "GET")
                {
                    throw new HTTPError(HttpStatusCode.MethodNotAllowed);
                }
                await SendResponseMoveToIndex(env, cancel_token).ConfigureAwait(false);
            }
            catch (HTTPError err) {
                env.ResponseStatusCode = (int)err.StatusCode;
            }
            catch (UnauthorizedAccessException) {
                env.ResponseStatusCode = (int)HttpStatusCode.Forbidden;
            }
        }
Пример #16
0
        private async Task SendResponseFileContent(OWINEnv env, CancellationToken cancel_token)
        {
            var localpath = GetPhysicalPath(env);

            if (localpath == null)
            {
                throw new HTTPError(HttpStatusCode.Forbidden);
            }
            if (Directory.Exists(localpath))
            {
                localpath = Path.Combine(localpath, "index.html");
                if (!File.Exists(localpath))
                {
                    throw new HTTPError(HttpStatusCode.Forbidden);
                }
            }
            if (File.Exists(localpath))
            {
                var contents     = File.ReadAllBytes(localpath);
                var content_desc = GetFileDesc(Path.GetExtension(localpath));
                env.SetResponseHeader("Content-Type", content_desc.MimeType);
                env.SetResponseHeader("Content-Length", contents.Length.ToString());
                if (env.AccessControlInfo.AuthenticationKey != null)
                {
                    env.SetResponseHeader("Set-Cookie", "auth=" + HTTPUtils.CreateAuthorizationToken(env.AccessControlInfo.AuthenticationKey));
                }
                if (env.RequestMethod == "GET")
                {
                    await env.ResponseBody.WriteAsync(contents, 0, contents.Length, cancel_token).ConfigureAwait(false);
                }
            }
            else
            {
                throw new HTTPError(HttpStatusCode.NotFound);
            }
        }
Пример #17
0
            protected override void OnIdle()
            {
                base.OnIdle();
                if (this.request.Method != "POST" || bodyLength < 0)
                {
                    return;
                }
                string request_str = null;

                if (Recv(stream => {
                    if (stream.Length - stream.Position < bodyLength)
                    {
                        throw new EndOfStreamException();
                    }
                    var buf = new byte[stream.Length - stream.Position];
                    stream.Read(buf, 0, (int)(stream.Length - stream.Position));
                    request_str = System.Text.Encoding.UTF8.GetString(buf);
                }))
                {
                    JToken res = rpcHost.ProcessRequest(request_str);
                    if (res != null)
                    {
                        SendJson(res);
                    }
                    else
                    {
                        Send(HTTPUtils.CreateResponseHeader(HttpStatusCode.NoContent, new Dictionary <string, string>()));
                    }
                    Stop();
                }
                else if (timeoutWatch.ElapsedMilliseconds > TimeoutLimit)
                {
                    Send(HTTPUtils.CreateResponseHeader(HttpStatusCode.RequestTimeout, new Dictionary <string, string>()));
                    Stop();
                }
            }