Beispiel #1
0
 //public HttpContext(HttpServer serv, IClient client)
 //{
 //    if (serv == null || client == null)
 //        throw new Exception("HttpServer and HttpClient cannot be null.");
 //    Server = serv;
 //    Client = client;
 //    //Requests = Queue.Synchronized(new Queue());
 //    Request = null;
 //    _Response = new HttpResponse(this);
 //    _Response.NotifyClient += new ClientNotifEventHandler(Server.NotifyClient);
 //}
 public HttpContext(HttpServer serv, IClient client,HttpRequest request)
 {
     if (serv == null || client == null || request == null)
         throw new Exception("HttpServer HttpClient and HttpRequest cannot be null.");
     Server = serv;
     Client = client;
     //Requests = Queue.Synchronized(new Queue());
     Request = request;
     _Response = new HttpResponse(this);
     _Response.NotifyClient += new ClientNotifEventHandler(Server.NotifyClient);
 }
Beispiel #2
0
        public bool AppendRequest(HttpRequest request)
        {
            if (Server == null || request == null)
                return false;

            Request = request;

            //lock (Requests.SyncRoot)
            //{
            //    //  如果超过容量,弹出最旧的
            //    if (Requests.Count >= Server.MaxQueuedRequests)
            //        Requests.Dequeue();

            //    Requests.Enqueue(request);
            //}

            return true;
        }
Beispiel #3
0
 /// <summary>
 /// 注册用户请求
 /// </summary>
 /// <param name="clmngr"></param>
 /// <param name="request"></param>
 private void RegistUser(ClientManager clmngr, HttpRequest request)
 {
     if (clmngr == null || request == null)
         return;
     int userID = UserAuthLogic.AnalysisUserIDFromRequestCookies(request.Cookies);
     if (userID > 0)
     {
         RegistUser(clmngr, userID);
     }
 }
Beispiel #4
0
        /// <summary>
        /// 将本次KeepAlive的请求登记到处理队列中
        /// </summary>
        /// <param name="clmngr"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        private HttpContext RegistKeepAliveRequestContext(ClientManager clmngr, HttpRequest request)
        {
            HttpContext context = null;

            if (clmngr == null || !clmngr.IsAuthedUser || !this._Clients.ContainsKey(clmngr.nSessionID) || request == null || request.IsRequestError)
                return context;

            clmngr.IsKeepAlive = true;

            //Context Table使用User ID作为Key
            int uid = clmngr.nUID;

            lock (_ContextTable.SyncRoot)
            {
                if (_ContextTable.ContainsKey(uid))
                {
                    context = _ContextTable[uid] as HttpContext;
                    //将请求添加到队列
                    context.AppendRequest(request);
                }
                else
                {
                    context = new HttpContext(this, clmngr, request);
                    //将请求添加到队列
                    _ContextTable[uid] = context;
                }
            }

            return context;
        }
Beispiel #5
0
        private void HandleErrorRequest(ClientManager clmngr, HttpRequest request)
        {
            if (clmngr == null || request == null)
                return;

            HttpContext context = new HttpContext(this, clmngr, request);
            HttpResponse response = context.Response;
            response.Write(request.Error.Message);
        }
Beispiel #6
0
        /// <summary>
        /// 找到与Request匹配的处理管道
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private CometCommandHandlerPipeline GetRegistedCommandHandlers(HttpRequest request)
        {
            CometCommand command = CometCommand.ParseFromRequest(request);

            return GetRegistedCommandHandlers(command.CommandID);
        }
Beispiel #7
0
 /// <summary>
 /// 从Request中解析command
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 private CometCommand GetCommandFromRequest(HttpRequest request)
 {
     CometCommandHandlerPipeline handlers = GetRegistedCommandHandlers(request);
     if (handlers != null)
         return handlers.Command;
     return null;
 }
Beispiel #8
0
        private bool CheckRequestHost(HttpRequest request)
        {
            if (request == null)
                return false;

            if (_Config == null || _Config.HostList == null || _Config.HostList.Count < 1)
                return true;

            foreach (string host in _Config.HostList)
            {
                if (string.Compare(request.Host, host, true) == 0)
                    return true;
            }
            return false;
        }
Beispiel #9
0
        public static HttpRequest ParseFromRawMessage(HttpServer server, string raw)
        {
            if (server == null || string.IsNullOrEmpty(raw))
                throw new Exception("HttpServer or raw message cannot be null.");

            HttpRequest request = new HttpRequest(server);
            string path = "/";
            string line = string.Empty;
            try
            {
                //  first of all,read request line
                using(StringReader sr = new StringReader(raw))
                {
                    string requestLine = sr.ReadLine();
                    string[] protocol = requestLine.Split(' ');
                    if (protocol == null || protocol.Length != 3)
                    {
                        request.LogRequestError(400);
                        return request;
                    }

                    request.ProcState = ProcessingState.RequestLine;
                    switch (protocol[0])
                    {
                        case "GET":
                            request.Method = HttpMethod.GET;
                            break;
                        case "POST":
                            request.Method = HttpMethod.POST;
                            break;
                        case "PUT":
                            request.Method = HttpMethod.PUT;
                            break;
                        case "DELETE":
                            request.Method = HttpMethod.DELETE;
                            break;
                        case "HEAD":
                            request.Method = HttpMethod.HEAD;
                            break;
                        default:
                            request.Method = HttpMethod.NA;
                            break;
                    }
                    if (protocol[1].Length > 2500)
                    {
                        request.LogRequestError(414);
                        return request;
                    }

                    //request.PathBuilder = new UriBuilder(protocol[1]);
                    path = protocol[1];

                    if (!protocol[2].StartsWith("HTTP/") || !(protocol[2].Length > "HTTP/".Length))
                    {
                        request.LogRequestError(400);
                        return request;
                    }
                    request.HttpVersion = protocol[2].Substring("HTTP/".Length);

                    //  parse request line completed,prepared to read headers
                    request.ProcState = ProcessingState.RequestHeaders;

                    if (request == null || request.ProcState != ProcessingState.RequestHeaders)
                        return request;

                    //  read headers
                    if (request.Headers == null)
                        request.Headers = new NameValueCollection();

                    line = sr.ReadLine();
                    while (!string.IsNullOrEmpty(line) && request.Headers.Count < server.MaxHeaderLines)
                    {
                        int colonIndex = line.IndexOf(":");
                        if (colonIndex <= 1)
                        {
                            line = sr.ReadLine();
                            continue;
                        }
                        string val = line.Substring(colonIndex + 1).Trim();
                        string name = line.Substring(0, colonIndex).Trim();

                        request.Headers[name] = val;

                        switch (name.ToLower(CultureInfo.InvariantCulture))
                        {
                            case "host":
                                request.Host = val;
                                request.PathUri = new Uri(string.Format("http://{0}{1}", val, path));
                                request.Parameters = HttpUtility.ParseParametersFromQueryString(request.PathUri.Query);
                                break;
                            case "authorization":
                                if (val.Length < 6)
                                    break;

                                string encoded = val.Substring(6, val.Length - 6);
                                byte[] byteAuth;
                                try
                                {
                                    byteAuth = Convert.FromBase64String(encoded);
                                }
                                catch (FormatException)
                                {
                                    break;
                                }

                                string[] strings = Encoding.UTF8.GetString(byteAuth).Split(':');
                                if (strings.Length != 2)
                                    break;

                                request.Username = strings[0];
                                request.Password = strings[1];

                                break;

                            case "content-type":
                                request.ContentType = val;
                                break;
                            case "content-length":
                                try
                                {
                                    Int64 length = long.Parse(val, NumberStyles.Integer, CultureInfo.InvariantCulture);
                                    if (length < 0)
                                    {
                                        request.LogRequestError(400);
                                        break;
                                    }
                                    if (length > server.MaxPostLength)
                                    {
                                        request.LogRequestError(413);
                                        break;
                                    }
                                }
                                catch (FormatException)
                                {
                                    request.LogRequestError(413);
                                }
                                break;
                            case "accept":
                                request.Accept = val;
                                break;
                            case "accept-language":
                                request.AcceptLanguage = val;
                                break;
                            case "user-agent":
                                request.UserAgent = val;
                                break;
                            case "connection":
                                if (string.Compare(val, "close", true, CultureInfo.InvariantCulture) == 0)
                                    request.ConnMode = ConnectionMode.Close;
                                else
                                    request.ConnMode = ConnectionMode.KeepAlive;
                                break;
                            case "if-modified-since":
                                try
                                {
                                    request.IfModifiedSince = HttpUtility.ParseHttpTime(val);
                                }
                                catch (FormatException)
                                {
                                }
                                break;
                            case "if-unmodified-since":
                                try
                                {
                                    request.IfUnModifiedSince = HttpUtility.ParseHttpTime(val);
                                }
                                catch (FormatException)
                                {
                                }
                                break;
                            case "range":
                                try
                                {
                                    string[] rangeStrings = val.Split(',');
                                    request.Range = new ByteRange[rangeStrings.Length];
                                    for (int i = 0; i < rangeStrings.Length; i++)
                                        request.Range[i] = new ByteRange(rangeStrings[i]);
                                }
                                catch (FormatException)
                                {
                                    request.Range = null;
                                }
                                break;
                            case "cookie":
                                request.Cookies = HttpUtility.ParseCookiesFromCookieString(val);
                                break;
                            default:
                                break;
                        }
                        line = sr.ReadLine();
                    }
                    request.RequestProcOK();
                }
            }
            catch
            {
                request.LogRequestError(415);
            }
            finally
            {

            }

            return request;
        }