Ejemplo n.º 1
0
        private void AcceptConnections(CancellationToken token)
        {
            try
            {
                if (ListenerSsl)
                {
                    ListenerPrefix = "https://" + ListenerIp + ":" + ListenerPort + "/";
                }
                else
                {
                    ListenerPrefix = "http://" + ListenerIp + ":" + ListenerPort + "/";
                }
                Http.Prefixes.Add(ListenerPrefix);
                Http.Start();

                while (Http.IsListening)
                {
                    ThreadPool.QueueUserWorkItem((c) =>
                    {
                        if (token.IsCancellationRequested)
                        {
                            throw new OperationCanceledException();
                        }

                        var context = c as HttpListenerContext;

                        try
                        {
                            #region Populate-Http-Request-Object

                            HttpRequest currRequest = new HttpRequest(context);
                            if (currRequest == null)
                            {
                                Logging.Log("Unable to populate HTTP request object on thread ID " + Thread.CurrentThread.ManagedThreadId + ", returning 400");
                                SendResponse(
                                    context,
                                    currRequest,
                                    BuildErrorResponse(500, "Unable to parse your request.", null),
                                    WatsonCommon.AddToDict("content-type", "application/json", null),
                                    400);
                                return;
                            }

                            Logging.Log("Thread " + currRequest.ThreadId + " " + currRequest.SourceIp + ":" + currRequest.SourcePort + " " + currRequest.Method + " " + currRequest.RawUrlWithoutQuery);

                            #endregion

                            #region Process-OPTIONS-Request

                            if (currRequest.Method.ToLower().Trim().Contains("option") &&
                                OptionsRoute != null)
                            {
                                Logging.Log("Thread " + Thread.CurrentThread.ManagedThreadId + " OPTIONS request received");
                                OptionsProcessor(context, currRequest);
                                return;
                            }

                            #endregion

                            #region Send-to-Handler

                            if (DebugRestRequests)
                            {
                                Logging.Log(currRequest.ToString());
                            }

                            Task.Run(() =>
                            {
                                HttpResponse currResponse = null;
                                Func <HttpRequest, HttpResponse> handler = null;

                                #region Find-Route

                                if (currRequest.Method.ToLower().Equals("get") || currRequest.Method.ToLower().Equals("head"))
                                {
                                    if (ContentRoutes.Exists(currRequest.RawUrlWithoutQuery))
                                    {
                                        // content route found
                                        currResponse = ContentProcessor.Process(currRequest);
                                    }
                                }

                                if (currResponse == null)
                                {
                                    handler = StaticRoutes.Match(currRequest.Method, currRequest.RawUrlWithoutQuery);
                                    if (handler != null)
                                    {
                                        // static route found
                                        currResponse = handler(currRequest);
                                    }
                                    else
                                    {
                                        // no static route, check for dynamic route
                                        handler = DynamicRoutes.Match(currRequest.Method, currRequest.RawUrlWithoutQuery);
                                        if (handler != null)
                                        {
                                            // dynamic route found
                                            currResponse = handler(currRequest);
                                        }
                                        else
                                        {
                                            // process using default route
                                            currResponse = DefaultRouteProcessor(context, currRequest);
                                        }
                                    }
                                }

                                #endregion

                                #region Return

                                if (currResponse == null)
                                {
                                    Logging.Log("Null response from handler for " + currRequest.SourceIp + ":" + currRequest.SourcePort + " " + currRequest.Method + " " + currRequest.RawUrlWithoutQuery);
                                    SendResponse(
                                        context,
                                        currRequest,
                                        BuildErrorResponse(500, "Unable to generate response", null),
                                        WatsonCommon.AddToDict("content-type", "application/json", null),
                                        500);
                                    return;
                                }
                                else
                                {
                                    if (DebugRestResponses)
                                    {
                                        Logging.Log(currResponse.ToString());
                                    }

                                    Dictionary <string, string> headers = new Dictionary <string, string>();
                                    if (!String.IsNullOrEmpty(currResponse.ContentType))
                                    {
                                        headers.Add("content-type", currResponse.ContentType);
                                    }

                                    if (currResponse.Headers != null && currResponse.Headers.Count > 0)
                                    {
                                        foreach (KeyValuePair <string, string> curr in currResponse.Headers)
                                        {
                                            headers = WatsonCommon.AddToDict(curr.Key, curr.Value, headers);
                                        }
                                    }

                                    if (currResponse.RawResponse)
                                    {
                                        SendResponse(
                                            context,
                                            currRequest,
                                            currResponse.Data,
                                            headers,
                                            currResponse.StatusCode);
                                        return;
                                    }
                                    else
                                    {
                                        SendResponse(
                                            context,
                                            currRequest,
                                            currResponse.ToJsonBytes(),
                                            headers,
                                            currResponse.StatusCode);
                                        return;
                                    }
                                }

                                #endregion
                            });

                            #endregion
                        }
                        catch (Exception)
                        {
                        }
                        finally
                        {
                        }
                    }, Http.GetContext());
                }
            }
            catch (Exception eOuter)
            {
                Logging.LogException("AcceptConnections", eOuter);
                throw;
            }
            finally
            {
                Logging.Log("Exiting");
            }
        }
Ejemplo n.º 2
0
        private void AcceptConnections(CancellationToken token)
        {
            try
            {
                foreach (string curr in _ListenerHostnames)
                {
                    string prefix = null;
                    if (_ListenerSsl)
                    {
                        prefix = "https://" + curr + ":" + _ListenerPort + "/";
                    }
                    else
                    {
                        prefix = "http://" + curr + ":" + _ListenerPort + "/";
                    }
                    _HttpListener.Prefixes.Add(prefix);
                }

                _HttpListener.Start();

                while (_HttpListener.IsListening)
                {
                    ThreadPool.QueueUserWorkItem((c) =>
                    {
                        if (token.IsCancellationRequested)
                        {
                            throw new OperationCanceledException();
                        }

                        var context = c as HttpListenerContext;

                        try
                        {
                            #region Populate-Http-Request-Object

                            HttpRequest req = new HttpRequest(context, ReadInputStream);
                            if (req == null)
                            {
                                HttpResponse resp = new HttpResponse(
                                    req,
                                    500,
                                    null,
                                    "text/plain",
                                    Encoding.UTF8.GetBytes("Unable to parse your HTTP request"));

                                SendResponse(
                                    context,
                                    req,
                                    resp);

                                return;
                            }

                            #endregion

                            #region Access-Control

                            if (!AccessControl.Permit(req.SourceIp))
                            {
                                context.Response.Close();
                                return;
                            }

                            #endregion

                            #region Process-OPTIONS-Request

                            if (req.Method == HttpMethod.OPTIONS &&
                                OptionsRoute != null)
                            {
                                OptionsProcessor(context, req);
                                return;
                            }

                            #endregion

                            #region Send-to-Handler

                            Task.Run(() =>
                            {
                                HttpResponse resp = null;
                                Func <HttpRequest, HttpResponse> handler = null;

                                #region Find-Route

                                if (req.Method == HttpMethod.GET ||
                                    req.Method == HttpMethod.HEAD)
                                {
                                    if (ContentRoutes.Exists(req.RawUrlWithoutQuery))
                                    {
                                        // content route found
                                        resp = _ContentRouteProcessor.Process(req);
                                    }
                                }

                                if (resp == null)
                                {
                                    handler = StaticRoutes.Match(req.Method, req.RawUrlWithoutQuery);
                                    if (handler != null)
                                    {
                                        // static route found
                                        resp = handler(req);
                                    }
                                    else
                                    {
                                        // no static route, check for dynamic route
                                        handler = DynamicRoutes.Match(req.Method, req.RawUrlWithoutQuery);
                                        if (handler != null)
                                        {
                                            // dynamic route found
                                            resp = handler(req);
                                        }
                                        else
                                        {
                                            // process using default route
                                            resp = DefaultRouteProcessor(context, req);
                                        }
                                    }
                                }

                                #endregion

                                #region Return

                                if (resp == null)
                                {
                                    resp = new HttpResponse(
                                        req,
                                        500,
                                        null,
                                        "text/plain",
                                        Encoding.UTF8.GetBytes("Unable to generate response"));

                                    SendResponse(
                                        context,
                                        req,
                                        resp);

                                    return;
                                }
                                else
                                {
                                    Dictionary <string, string> headers = new Dictionary <string, string>();
                                    if (!String.IsNullOrEmpty(resp.ContentType))
                                    {
                                        headers.Add("content-type", resp.ContentType);
                                    }

                                    if (resp.Headers != null && resp.Headers.Count > 0)
                                    {
                                        foreach (KeyValuePair <string, string> curr in resp.Headers)
                                        {
                                            headers = WatsonCommon.AddToDict(curr.Key, curr.Value, headers);
                                        }
                                    }

                                    SendResponse(
                                        context,
                                        req,
                                        resp);

                                    return;
                                }

                                #endregion
                            });

                            #endregion
                        }
                        catch (Exception)
                        {
                        }
                        finally
                        {
                        }
                    }, _HttpListener.GetContext());
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
            }
        }