コード例 #1
0
ファイル: Header.cs プロジェクト: zhangjiedy/FastHttpApi
        public void Write(PipeStream stream)
        {
            byte[] buffer = HttpParse.GetByteBuffer();
            int    count  = Type.Bytes.Length;

            System.Buffer.BlockCopy(Type.Bytes, 0, buffer, 0, count);
            if (Value == null)
            {
                Value = string.Empty;
            }
            count             = count + Encoding.UTF8.GetBytes(Value, 0, Value.Length, buffer, count);
            buffer[count]     = HeaderTypeFactory._LINE_R;
            buffer[count + 1] = HeaderTypeFactory._LINE_N;
            stream.Write(buffer, 0, count + 2);
        }
コード例 #2
0
ファイル: UrlRoute.cs プロジェクト: zhangjiedy/FastHttpApi
 public string GetRewriteUrl(Dictionary <string, string> parameters)
 {
     if (parameters.Count == 0 || !HasRewriteParamters)
     {
         return(Rewrite);
     }
     else
     {
         var buffer              = HttpParse.GetCharBuffer();
         int count               = 0;
         int nameIndex           = 0;
         ReadOnlySpan <char> str = Rewrite;
         for (int i = 0; i < str.Length; i++)
         {
             if (str[i] == '{')
             {
                 nameIndex = i + 1;
             }
             else if (str[i] == '}')
             {
                 if (nameIndex > 0)
                 {
                     string name = new string(str.Slice(nameIndex, i - nameIndex));
                     if (parameters.TryGetValue(name, out string value))
                     {
                         for (int l = 0; l < value.Length; l++)
                         {
                             buffer[count] = value[l];
                             count++;
                         }
                     }
                 }
                 nameIndex = 0;
             }
             else
             {
                 if (nameIndex == 0)
                 {
                     buffer[count] = str[i];
                     count++;
                 }
             }
         }
         return(new string(buffer, 0, count));
     }
 }
コード例 #3
0
        public static ReadOnlySpan <char> ReadCharLine(IndexOfResult result)
        {
            int offset = 0;

            char[]       data   = HttpParse.GetCharBuffer();
            IMemoryBlock memory = result.Start;

            for (int i = result.StartPostion; i < memory.Length; i++)
            {
                data[offset] = (char)result.Start.Bytes[i];
                offset++;
                if (offset == result.Length)
                {
                    break;
                }
            }
            if (offset < result.Length)
            {
Next:
                memory = result.Start.NextMemory;

                int count;
                if (memory.ID == result.End.ID)
                {
                    count = result.EndPostion + 1;
                }
                else
                {
                    count = memory.Length;
                }
                for (int i = 0; i < count; i++)
                {
                    data[offset] = (char)memory.Bytes[i];
                    offset++;
                    if (offset == result.Length)
                    {
                        break;
                    }
                }
                if (offset < result.Length)
                {
                    goto Next;
                }
            }
            return(new ReadOnlySpan <char>(data, 0, result.Length - 2));
        }
コード例 #4
0
ファイル: UrlRoute.cs プロジェクト: zhangjiedy/FastHttpApi
        public void Init()
        {
            string parent = @"(\{[A-Za-z0-9]+\})";
            int    index  = 0;

            if (UrlIgnoreCase)
            {
                Url = Url.ToLower();
                if (!string.IsNullOrEmpty(Rewrite))
                {
                    Rewrite = Rewrite.ToLower();
                }
            }
            for (int i = 0; i < Url.Length; i++)
            {
                if (Url[i] == '/')
                {
                    index = i;
                    PathLevel++;
                }
                else if (Url[i] == '?')
                {
                    HasQueryString = true;
                    break;
                }
            }

            if (!string.IsNullOrEmpty(Host))
            {
                this.Prefix = new UrlPrefix(Host);
            }
            // if (this.Prefix == null)
            Path = $"{Url.Substring(0, index + 1)}";
            ID   = $"{Host}{Path}";
            //else
            //    Path = $"{this.Prefix.Value}{Url.Substring(0, index + 1)}";
            Valid = Regex.IsMatch(Url, parent);
            //TemplateMatch = new RouteTemplateMatch(Url, Path.Length);
            TemplateMatch = new RouteTemplateMatch(Url, 0);
            if (!string.IsNullOrEmpty(Rewrite))
            {
                ReExt = HttpParse.GetBaseUrlExt(Rewrite);
                HasRewriteParamters = Rewrite.IndexOf("{") >= 0;
            }
        }
コード例 #5
0
 private void LoadMethod(PipeStream stream)
 {
     if (mState == LoadedState.None)
     {
         Span <char> data;
         if (!stream.ReadLine(out data))
         {
             return;
         }
         HttpParse.AnalyzeRequestLine(data, this);
         HttpParse.ReadHttpVersionNumber(HttpVersion, mQueryString, this);
         int len = HttpParse.ReadUrlQueryString(Url, mQueryString, this);
         if (len > 0)
         {
             HttpParse.ReadUrlPathAndExt(Url.AsSpan().Slice(0, len), mQueryString, this, this.Server.Options);
         }
         else
         {
             HttpParse.ReadUrlPathAndExt(Url.AsSpan(), mQueryString, this, this.Server.Options);
         }
         //UrlCode = BaseUrl.GetHashCode() << 16 | BaseUrl.Length;
         RouteMatchResult routeMatchResult = new RouteMatchResult();
         if (Server.UrlRewrite.Count > 0 && Server.UrlRewrite.Match(this, ref routeMatchResult, mQueryString))
         {
             this.IsRewrite = true;
             this.SourceUrl = this.Url;
             if (Server.EnableLog(EventArgs.LogType.Info))
             {
                 Server.BaseServer.Log(EventArgs.LogType.Info, Session, $"HTTP {ID} request rewrite {Url} to {routeMatchResult.RewriteUrl}");
             }
             Url = routeMatchResult.RewriteUrl;
             if (Server.Options.UrlIgnoreCase)
             {
                 BaseUrl = routeMatchResult.RewriteUrlLower;
             }
             else
             {
                 BaseUrl = routeMatchResult.RewriteUrl;
             }
             Ext = routeMatchResult.Ext;
         }
         mState = LoadedState.Method;
     }
 }
コード例 #6
0
ファイル: HttpRequest.cs プロジェクト: szg/FastHttpApi
        private void LoadMethod(PipeStream stream)
        {
            if (mState == LoadedState.None)
            {
                string data;
                if (!stream.TryReadWith(HeaderTypeFactory.LINE_BYTES, out data))
                {
                    return;
                }
                HttpParse.AnalyzeRequestLine(data, this);
                HttpParse.ReadHttpVersionNumber(HttpVersion, mQueryString, this);
                int len = HttpParse.ReadUrlQueryString(Url, mQueryString, this);
                if (len > 0)
                {
                    HttpParse.ReadUrlPathAndExt(Url.AsSpan().Slice(0, len), mQueryString, this, this.Server.ServerConfig);
                }
                else
                {
                    HttpParse.ReadUrlPathAndExt(Url.AsSpan(), mQueryString, this, this.Server.ServerConfig);
                }

                RouteMatchResult routeMatchResult = new RouteMatchResult();
                if (Server.UrlRewrite.Match(this, ref routeMatchResult, mQueryString))
                {
                    this.IsRewrite = true;
                    this.SourceUrl = this.Url;
                    if (Server.EnableLog(EventArgs.LogType.Info))
                    {
                        Server.BaseServer.Log(EventArgs.LogType.Info, Session, "request rewrite {0}  to {1}", Url, routeMatchResult.RewriteUrl);
                    }
                    Url = routeMatchResult.RewriteUrl;
                    if (Server.ServerConfig.UrlIgnoreCase)
                    {
                        BaseUrl = routeMatchResult.RewriteUrlLower;
                    }
                    else
                    {
                        BaseUrl = routeMatchResult.RewriteUrl;
                    }
                    Ext = routeMatchResult.Ext;
                }
                mState = LoadedState.Method;
            }
        }
コード例 #7
0
        private void LoadMethod(PipeStream stream)
        {
            string line;

            if (mState == LoadedState.None)
            {
                if (stream.TryReadLine(out line))
                {
                    Tuple <string, string, string> result = HttpParse.AnalyzeRequestLine(line);
                    Method      = result.Item1;
                    Url         = result.Item2;
                    BaseUrl     = HttpParse.GetBaseUrl(Url);
                    Ext         = HttpParse.GetBaseUrlExt(BaseUrl);
                    HttpVersion = result.Item3;
                    HttpParse.AnalyzeQueryString(Url, mQueryString);
                    mState = LoadedState.Method;
                }
            }
        }
コード例 #8
0
 private void LoadMethod(PipeStream stream)
 {
     if (mState == LoadedState.None)
     {
         IndexOfResult index = stream.IndexOf(HeaderType.LINE_BYTES);
         if (index.End != null)
         {
             ReadOnlySpan <Char> line = HttpParse.ReadCharLine(index);
             stream.ReadFree(index.Length);
             Tuple <string, string, string> result = HttpParse.AnalyzeRequestLine(line);
             Method      = result.Item1;
             Url         = result.Item2;
             BaseUrl     = HttpParse.GetBaseUrlToLower(Url);
             Ext         = HttpParse.GetBaseUrlExt(BaseUrl);
             HttpVersion = result.Item3;
             HttpParse.AnalyzeQueryString(Url, mQueryString);
             mState = LoadedState.Method;
         }
     }
 }
コード例 #9
0
        public bool Read(PipeStream stream, Cookies cookies)
        {
            Span <char> lineData;

            while (stream.ReadLine(out lineData))
            {
                if (lineData.Length == 0)
                {
                    return(true);
                }
                else
                {
                    ReadOnlySpan <Char>    line   = lineData;
                    Tuple <string, string> result = HttpParse.AnalyzeHeader(line);
                    this[result.Item1] = result.Item2;
                    if (line.StartsWith(new ReadOnlySpan <char>(new [] { 'c', 'o', 'o', 'k', 'i', 'e' }), StringComparison.OrdinalIgnoreCase))
                    {
                        HttpParse.AnalyzeCookie(line.Slice(8, line.Length - 8), cookies);
                    }
                }
            }
            return(false);
        }
コード例 #10
0
ファイル: Header.cs プロジェクト: yuyu2you/FastHttpApi
        public bool Read(PipeStream stream, Cookies cookies)
        {
            string lineData;

            while (stream.TryReadWith(HeaderTypeFactory.LINE_BYTES, out lineData))
            {
                if (string.IsNullOrEmpty(lineData))
                {
                    return(true);
                }
                else
                {
                    ReadOnlySpan <Char>    line   = lineData;
                    Tuple <string, string> result = HttpParse.AnalyzeHeader(line);
                    this[result.Item1] = result.Item2;
                    if (line[0] == 'C' && line[5] == 'e' && line[1] == 'o' && line[2] == 'o' && line[3] == 'k' && line[4] == 'i')
                    {
                        HttpParse.AnalyzeCookie(line.Slice(8, line.Length - 8), cookies);
                    }
                }
            }
            return(false);
        }
コード例 #11
0
ファイル: Header.cs プロジェクト: xiecunjing/FastHttpApi
        public bool Read(PipeStream stream, Cookies cookies)
        {
            Span <char> lineData;

            while (stream.ReadLine(out lineData))
            {
                if (lineData.Length == 0)
                {
                    return(true);
                }
                else
                {
                    ReadOnlySpan <Char>    line   = lineData;
                    Tuple <string, string> result = HttpParse.AnalyzeHeader(line);
                    this[result.Item1] = result.Item2;
                    if (line[0] == 'C' && line[5] == 'e' && line[1] == 'o' && line[2] == 'o' && line[3] == 'k' && line[4] == 'i')
                    {
                        HttpParse.AnalyzeCookie(line.Slice(8, line.Length - 8), cookies);
                    }
                }
            }
            return(false);
        }
コード例 #12
0
        public void Init()
        {
            string parent = @"(\{[A-Za-z0-9]+\})";
            int    index  = 0;

            if (UrlIgnoreCase)
            {
                Url = Url.ToLower();
                if (!string.IsNullOrEmpty(Rewrite))
                {
                    Rewrite = Rewrite.ToLower();
                }
            }
            for (int i = 0; i < Url.Length; i++)
            {
                if (Url[i] == '/')
                {
                    index = i;
                    PathLevel++;
                }
                else if (Url[i] == '?')
                {
                    HasQueryString = true;
                    break;
                }
            }
            Path  = Url.Substring(0, index + 1);
            Valid = Regex.IsMatch(Url, parent);
            ID    = GetPathID(Path, PathLevel);
            //TemplateMatch = new RouteTemplateMatch(Url, Path.Length);
            TemplateMatch = new RouteTemplateMatch(Url, 0);
            if (!string.IsNullOrEmpty(Rewrite))
            {
                ReExt = HttpParse.GetBaseUrlExt(Rewrite);
                HasRewriteParamters = Rewrite.IndexOf("{") >= 0;
            }
        }
コード例 #13
0
ファイル: Header.cs プロジェクト: ypzw0101/FastHttpApi
        public bool Read(PipeStream stream, Cookies cookies)
        {
            IndexOfResult index = stream.IndexOf(HeaderTypeFactory.LINE_BYTES);

            while (index.End != null)
            {
                if (index.Length == 2)
                {
                    stream.ReadFree(2);
                    return(true);
                }
                else
                {
                    ReadOnlySpan <Char> line = HttpParse.ReadCharLine(index);
                    stream.ReadFree(index.Length);
                    if (line[0] == 'C' && line[5] == 'e' && line[1] == 'o' && line[2] == 'o' && line[3] == 'k' && line[4] == 'i')
                    {
                        HttpParse.AnalyzeCookie(line.Slice(8, line.Length - 8), cookies);
                    }
                    else
                    {
                        Tuple <string, string> result = HttpParse.AnalyzeHeader(line);
                        HeaderType             type   = HeaderTypeFactory.Find(result.Item1);
                        if (type == null)
                        {
                            Add(result.Item1, result.Item2);
                        }
                        else
                        {
                            Add(type.Name, result.Item2);
                        }
                    }
                }
                index = stream.IndexOf(HeaderTypeFactory.LINE_BYTES);
            }
            return(false);
        }
コード例 #14
0
ファイル: HttpRequest.cs プロジェクト: zhangjiedy/FastHttpApi
 private void LoadMethod(PipeStream stream)
 {
     if (mState == LoadedState.None)
     {
         Span <char> data;
         if (!stream.ReadLine(out data))
         {
             return;
         }
         PathLevel = 0;
         HttpParse.AnalyzeRequestLine(data, this);
         HttpParse.ReadHttpVersionNumber(HttpVersion, mQueryString, this);
         mQueryStringIndex = HttpParse.ReadUrlQueryString(Url, mQueryString, this);
         if (mQueryStringIndex > 0)
         {
             HttpParse.ReadUrlPathAndExt(Url.AsSpan().Slice(0, mQueryStringIndex), mQueryString, this, this.Server.Options);
         }
         else
         {
             HttpParse.ReadUrlPathAndExt(Url.AsSpan(), mQueryString, this, this.Server.Options);
         }
         mState = LoadedState.Method;
     }
 }
コード例 #15
0
ファイル: HttpRequest.cs プロジェクト: zhangjiedy/FastHttpApi
 public void UrlRewriteTo(string url)
 {
     if (!this.IsRewrite)
     {
         this.IsRewrite     = true;
         this.SourceUrl     = Url;
         this.SourceBaseUrl = BaseUrl;
         this.SourcePath    = Path;
     }
     Url = url;
     mQueryStringIndex = HttpParse.ReadUrlQueryString(Url, null, this);
     if (mQueryStringIndex > 0)
     {
         HttpParse.ReadUrlPathAndExt(Url.AsSpan().Slice(0, mQueryStringIndex), mQueryString, this, this.Server.Options);
     }
     else
     {
         HttpParse.ReadUrlPathAndExt(Url.AsSpan(), mQueryString, this, this.Server.Options);
     }
     if (Server.EnableLog(EventArgs.LogType.Info))
     {
         Server.BaseServer.Log(EventArgs.LogType.Info, Session, $"HTTP {ID} {((IPEndPoint)Session.RemoteEndPoint).Address} request {SourceUrl} rewrite to {Url}");
     }
 }
コード例 #16
0
        public void ExecuteWithWS(HttpRequest request, HttpApiServer server, JToken token)
        {
            ActionResult result = new ActionResult();
            JToken       url    = token["url"];

            WebSockets.DataFrame dataFrame = server.CreateDataFrame(result);
            if (url == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, null, $"Websocket {request.ID} {request.RemoteIPAddress} process error action url info notfound!");
                }
                result.Code  = 403;
                result.Error = "not support, url info notfound!";
                request.Session.Send(dataFrame);
                return;
            }
            result.Url = url.Value <string>();
            string baseurl = result.Url;

            if (server.Options.UrlIgnoreCase)
            {
                baseurl = HttpParse.CharToLower(result.Url);
            }
            if (baseurl[0] != '/')
            {
                baseurl = "/" + baseurl;
            }
            result.Url = baseurl;
            JToken data = token["params"];

            if (data == null)
            {
                data = (JToken)Newtonsoft.Json.JsonConvert.DeserializeObject("{}");
            }
            JToken requestid = data["_requestid"];

            if (requestid != null)
            {
                result.ID = requestid.Value <string>();
            }

            ActionHandler handler = GetAction(baseurl);

            if (handler == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, null, $"Websocket {request.ID} {request.RemoteIPAddress} ws execute {result.Url} notfound!");
                }
                result.Code  = 404;
                result.Error = "url " + baseurl + " notfound!";
                request.Session.Send(dataFrame);
            }
            else
            {
                try
                {
                    Data.DataContxt dataContxt = new Data.DataContxt();
                    DataContextBind.BindJson(dataContxt, data);
                    WebsocketJsonContext dc = new WebsocketJsonContext(server, request, dataContxt);
                    dc.ActionUrl = baseurl;
                    dc.RequestID = result.ID;
                    if (!Server.OnActionExecuting(dc))
                    {
                        return;
                    }
                    ActionContext         context               = new ActionContext(handler, dc, this);
                    long                  startTime             = server.BaseServer.GetRunTime();
                    WSActionResultHandler wSActionResultHandler = new WSActionResultHandler(dc, server, request, result, dataFrame, startTime);
                    if (!handler.HasValidation || handler.ValidateParamters(context.Parameters, out (Validations.ValidationBase, ParameterInfo)error))
                    {
                        context.Execute(wSActionResultHandler);
                    }
                    else
                    {
                        server.ValidationOutputHandler.Execute(dc, wSActionResultHandler, error.Item1, error.Item2);
                    }
                }
コード例 #17
0
        internal void Write(PipeStream stream)
        {
            IResult result = mBody as IResult;

            if (result != null)
            {
                this.Header[HeaderTypeFactory.CONTENT_TYPE] = result.ContentType;
                result.Setting(this);
            }

            byte[] buffer = HttpParse.GetByteBuffer();
            //string line = string.Concat(HttpVersion, " ", mCode, " ", CodeMsg, "\r\n");
            //var hlen = Encoding.ASCII.GetBytes(line, 0, line.Length, buffer, 0);
            int hlen = 0;

            hlen         = hlen + Encoding.ASCII.GetBytes(HttpVersion, 0, HttpVersion.Length, buffer, hlen);
            buffer[hlen] = HeaderTypeFactory._SPACE_BYTE;
            hlen++;
            hlen         = hlen + Encoding.ASCII.GetBytes(mCode, 0, mCode.Length, buffer, hlen);
            buffer[hlen] = HeaderTypeFactory._SPACE_BYTE;
            hlen++;
            hlen = hlen + Encoding.ASCII.GetBytes(CodeMsg, 0, CodeMsg.Length, buffer, hlen);

            buffer[hlen] = HeaderTypeFactory._LINE_R;
            hlen++;
            buffer[hlen] = HeaderTypeFactory._LINE_N;
            hlen++;

            stream.Write(buffer, 0, hlen);
            stream.Write(HeaderTypeFactory.SERVAR_HEADER_BYTES, 0, HeaderTypeFactory.SERVAR_HEADER_BYTES.Length);
            Header.Write(stream);
            for (int i = 0; i < mSetCookies.Count; i++)
            {
                HeaderTypeFactory.Write(HeaderTypeFactory.SET_COOKIE, stream);
                stream.Write(mSetCookies[i]);
                stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
            }
            if (mBody != null)
            {
                StaticResurce.FileBlock fb = mBody as StaticResurce.FileBlock;
                if (fb != null)
                {
                    stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
                    fb.Write(stream);
                }
                else
                {
                    if (result.HasBody)
                    {
                        if (result.Length > 0)
                        {
                            stream.Write(HeaderTypeFactory.CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.CONTENT_LENGTH_BYTES.Length);
                            stream.Write(result.Length.ToString());
                            stream.Write(HeaderTypeFactory.TOW_LINE_BYTES, 0, 4);
                            result.Write(stream, this);
                        }
                        else
                        {
                            stream.Write(HeaderTypeFactory.CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.CONTENT_LENGTH_BYTES.Length);
                            MemoryBlockCollection contentLength = stream.Allocate(10);
                            stream.Write(HeaderTypeFactory.TOW_LINE_BYTES, 0, 4);
                            int len = stream.CacheLength;
                            result.Write(stream, this);
                            int count = stream.CacheLength - len;
                            //contentLength.Full("Content-Length: " + count.ToString().PadRight(10) + "\r\n\r\n", stream.Encoding);
                            contentLength.Full(count.ToString().PadRight(10), stream.Encoding);
                        }
                    }
                    else
                    {
                        stream.Write(HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES.Length);
                        stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
                    }
                }
            }
            else
            {
                stream.Write(HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES.Length);
                stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
            }

            if (Session.Server.EnableLog(EventArgs.LogType.Debug))
            {
                Session.Server.Log(EventArgs.LogType.Debug, Session, "{0} {1}", Request.ClientIPAddress, this.ToString());
            }

            if (Session.Server.EnableLog(EventArgs.LogType.Info))
            {
                Session.Server.Log(EventArgs.LogType.Info, Session, "{4} {0} {1} response {2} {3}", Request.Method, Request.Url, Code, CodeMsg, Request.ClientIPAddress);
            }
        }
コード例 #18
0
 public object GetNotSupport(HttpResponse response)
 {
     return(new ActionResult {
         Url = HttpParse.GetBaseUrl(response.Request.Url), Code = 403, Error = response.Request.Method + " method type not support"
     });
 }
コード例 #19
0
 public object GetInnerError(Exception e, HttpResponse response, bool outputStackTrace)
 {
     return(new ActionResult {
         Url = HttpParse.GetBaseUrl(response.Request.Url), Code = 500, Error = e.Message, StackTrace = outputStackTrace ? e.StackTrace : null
     });
 }
コード例 #20
0
 private void LoadMethod(PipeStream stream)
 {
     if (mState == LoadedState.None)
     {
         Span <char> data;
         if (!stream.ReadLine(out data))
         {
             return;
         }
         HttpParse.AnalyzeRequestLine(data, this);
         HttpParse.ReadHttpVersionNumber(HttpVersion, mQueryString, this);
         int len = HttpParse.ReadUrlQueryString(Url, mQueryString, this);
         if (len > 0)
         {
             HttpParse.ReadUrlPathAndExt(Url.AsSpan().Slice(0, len), mQueryString, this, this.Server.Options);
         }
         else
         {
             HttpParse.ReadUrlPathAndExt(Url.AsSpan(), mQueryString, this, this.Server.Options);
         }
         RouteMatchResult routeMatchResult = new RouteMatchResult();
         this.IsRewrite = false;
         if (Server.UrlRewrite.Count > 0 && Server.UrlRewrite.Match(this, ref routeMatchResult, mQueryString))
         {
             this.IsRewrite     = true;
             this.SourceUrl     = Url;
             this.SourceBaseUrl = BaseUrl;
             this.SourcePath    = Path;
             if (Server.Options.UrlIgnoreCase)
             {
                 Url = routeMatchResult.RewriteUrlLower;
             }
             else
             {
                 Url = routeMatchResult.RewriteUrl;
             }
             if (Server.Options.AgentRewrite)
             {
                 if (len > 0 && this.SourceUrl.Length > len + 1)
                 {
                     if (Url.IndexOf('?') > 0)
                     {
                         Url += "&";
                     }
                     else
                     {
                         Url += "?";
                     }
                     Url += new string(SourceUrl.AsSpan().Slice(len + 1));
                 }
             }
             len = HttpParse.ReadUrlQueryString(Url, null, this);
             if (len > 0)
             {
                 HttpParse.ReadUrlPathAndExt(Url.AsSpan().Slice(0, len), mQueryString, this, this.Server.Options);
             }
             else
             {
                 HttpParse.ReadUrlPathAndExt(Url.AsSpan(), mQueryString, this, this.Server.Options);
             }
             if (Server.EnableLog(EventArgs.LogType.Info))
             {
                 Server.BaseServer.Log(EventArgs.LogType.Info, Session, $"HTTP {ID} {((IPEndPoint)Session.RemoteEndPoint).Address} request {SourceUrl} rewrite to {Url}");
             }
         }
         mState = LoadedState.Method;
     }
 }
コード例 #21
0
        public ActionResult ExecuteWithWS(HttpRequest request, HttpApiServer server, JToken token)
        {
            ActionResult result = new ActionResult();
            JToken       url    = token["url"];

            WebSockets.DataFrame dataFrame = server.CreateDataFrame(result);
            if (url == null)
            {
                result.Code  = 403;
                result.Error = "not support url info notfound!";
                request.Session.Send(dataFrame);
                return(result);
            }
            result.Url = url.Value <string>();
            string baseurl = HttpParse.CharToLower(result.Url);

            if (baseurl[0] != '/')
            {
                baseurl = "/" + baseurl;
            }
            ActionHandler handler = GetAction(baseurl);

            if (handler == null)
            {
                server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, baseurl + " not found");
                result.Code  = 404;
                result.Error = "url " + baseurl + " notfound!";
                request.Session.Send(dataFrame);
            }
            else
            {
                try
                {
                    JToken data = token["params"];
                    if (data == null)
                    {
                        data = (JToken)Newtonsoft.Json.JsonConvert.DeserializeObject("{}");
                    }
                    WebsocketContext dc      = new WebsocketContext(server, request, data);
                    ActionContext    context = new ActionContext(handler, dc);
                    context.Execute();
                    if (!dc.AsyncResult)
                    {
                        result.Data = context.Result;
                        request.Session.Send(dataFrame);
                    }
                }
                catch (Exception e_)
                {
                    server.BaseServer.Log(EventArgs.LogType.Error, request.Session, "{0} inner error {1}@{2}", request.Url, e_.Message, e_.StackTrace);
                    result.Code  = 500;
                    result.Error = e_.Message;
                    if (server.ServerConfig.OutputStackTrace)
                    {
                        result.StackTrace = e_.StackTrace;
                    }
                    request.Session.Send(dataFrame);
                }
            }
            return(result);
        }
コード例 #22
0
        public ActionResult ExecuteWithWS(HttpRequest request, HttpApiServer server, JToken token)
        {
            ActionResult result = new ActionResult();
            JToken       url    = token["url"];

            WebSockets.DataFrame dataFrame = server.CreateDataFrame(result);
            if (url == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "{0} ws not support, url info notfound!", request.RemoteIPAddress);
                }
                result.Code  = 403;
                result.Error = "not support, url info notfound!";
                request.Session.Send(dataFrame);
                return(result);
            }
            result.Url = url.Value <string>();
            string baseurl = result.Url;

            if (server.Options.UrlIgnoreCase)
            {
                baseurl = HttpParse.CharToLower(result.Url);
            }
            if (baseurl[0] != '/')
            {
                baseurl = "/" + baseurl;
            }
            result.Url = baseurl;
            JToken data = token["params"];

            if (data == null)
            {
                data = (JToken)Newtonsoft.Json.JsonConvert.DeserializeObject("{}");
            }
            JToken requestid = data["_requestid"];

            if (requestid != null)
            {
                result.ID = requestid.Value <string>();
            }

            ActionHandler handler = GetAction(baseurl);

            if (handler == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "{0} ws execute {1} notfound", request.RemoteIPAddress, result.Url);
                }
                result.Code  = 404;
                result.Error = "url " + baseurl + " notfound!";
                request.Session.Send(dataFrame);
            }
            else
            {
                try
                {
                    Data.DataContxt dataContxt = new Data.DataContxt();
                    DataContextBind.BindJson(dataContxt, data);
                    WebsocketJsonContext dc = new WebsocketJsonContext(server, request, dataContxt);
                    dc.ActionUrl = baseurl;
                    dc.RequestID = result.ID;
                    ActionContext         context               = new ActionContext(handler, dc, this);
                    long                  startTime             = server.BaseServer.GetRunTime();
                    WSActionResultHandler wSActionResultHandler = new WSActionResultHandler(dc, server, request, result, dataFrame, startTime);
                    context.Execute(wSActionResultHandler);
                }
                catch (Exception e_)
                {
                    handler.IncrementError();
                    if (server.EnableLog(EventArgs.LogType.Error))
                    {
                        server.BaseServer.Log(EventArgs.LogType.Error, request.Session, "{0} ws execute {1} inner error {2}@{3}", request.RemoteIPAddress, result.Url, e_.Message, e_.StackTrace);
                    }
                    result.Code  = 500;
                    result.Error = e_.Message;
                    if (server.Options.OutputStackTrace)
                    {
                        result.StackTrace = e_.StackTrace;
                    }
                    dataFrame.Send(request.Session);
                }
            }
            return(result);
        }
コード例 #23
0
        public ActionResult ExecuteWithWS(HttpRequest request, HttpApiServer server, JToken token)
        {
            ActionResult result = new ActionResult();
            JToken       url    = token["url"];

            WebSockets.DataFrame dataFrame = server.CreateDataFrame(result);
            if (url == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "websocket {0} not support, url info notfound!", request.ClientIPAddress);
                }
                result.Code  = 403;
                result.Error = "not support, url info notfound!";
                request.Session.Send(dataFrame);
                return(result);
            }
            result.Url = url.Value <string>();
            string baseurl = HttpParse.CharToLower(result.Url);

            if (baseurl[0] != '/')
            {
                baseurl = "/" + baseurl;
            }
            result.Url = baseurl;
            JToken data = token["params"];

            if (data == null)
            {
                data = (JToken)Newtonsoft.Json.JsonConvert.DeserializeObject("{}");
            }
            JToken requestid = data["_requestid"];

            if (requestid != null)
            {
                result.ID = requestid.Value <string>();
            }
            ActionHandler handler = GetAction(baseurl);

            if (handler == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "websocket {0} execute {1} notfound", request.ClientIPAddress, result.Url);
                }
                result.Code  = 404;
                result.Error = "url " + baseurl + " notfound!";
                request.Session.Send(dataFrame);
            }
            else
            {
                try
                {
                    WebsocketContext dc = new WebsocketContext(server, request, data);
                    dc.ActionUrl = baseurl;
                    dc.RequestID = result.ID;
                    ActionContext context = new ActionContext(handler, dc);
                    context.Execute();
                    if (!dc.AsyncResult)
                    {
                        if (context.Result is ActionResult)
                        {
                            result    = (ActionResult)context.Result;
                            result.ID = dc.RequestID;
                            if (result.Url == null)
                            {
                                result.Url = dc.ActionUrl;
                            }
                            dataFrame.Body = result;
                        }
                        else
                        {
                            result.Data = context.Result;
                        }
                        dataFrame.Send(request.Session);
                        //request.Session.Send(dataFrame);
                    }
                }
                catch (Exception e_)
                {
                    if (server.EnableLog(EventArgs.LogType.Error))
                    {
                        server.BaseServer.Log(EventArgs.LogType.Error, request.Session, "websocket {0} execute {1} inner error {2}@{3}", request.ClientIPAddress, request.Url, e_.Message, e_.StackTrace);
                    }
                    result.Code  = 500;
                    result.Error = e_.Message;
                    if (server.ServerConfig.OutputStackTrace)
                    {
                        result.StackTrace = e_.StackTrace;
                    }
                    dataFrame.Send(request.Session);
                    //request.Session.Send(dataFrame);
                }
            }
            return(result);
        }
コード例 #24
0
        private void OnWrite(PipeStream stream)
        {
            IResult result = mBody as IResult;

            if (result != null)
            {
                result.Setting(this);
            }
            byte[] buffer = HttpParse.GetByteBuffer();
            int    hlen   = 0;

            hlen         = hlen + Encoding.ASCII.GetBytes(HttpVersion, 0, HttpVersion.Length, buffer, hlen);
            buffer[hlen] = HeaderTypeFactory._SPACE_BYTE;
            hlen++;
            hlen         = hlen + Encoding.ASCII.GetBytes(Code, 0, Code.Length, buffer, hlen);
            buffer[hlen] = HeaderTypeFactory._SPACE_BYTE;
            hlen++;
            hlen = hlen + Encoding.ASCII.GetBytes(CodeMsg, 0, CodeMsg.Length, buffer, hlen);

            buffer[hlen] = HeaderTypeFactory._LINE_R;
            hlen++;
            buffer[hlen] = HeaderTypeFactory._LINE_N;
            hlen++;

            stream.Write(buffer, 0, hlen);
            stream.Write(HeaderTypeFactory.SERVAR_HEADER_BYTES, 0, HeaderTypeFactory.SERVAR_HEADER_BYTES.Length);
            Header.Write(stream);
            if (result != null)
            {
                result.ContentType.Write(stream);
            }
            var datebuffer = GMTDate.Default.DATE;

            stream.Write(datebuffer.Array, 0, datebuffer.Count);

            for (int i = 0; i < mSetCookies.Count; i++)
            {
                HeaderTypeFactory.Write(HeaderTypeFactory.SET_COOKIE, stream);
                stream.Write(mSetCookies[i]);
                stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
            }
            if (mBody != null)
            {
                if (mBody is IDataResponse dataResponse)
                {
                    stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
                    dataResponse.Write(stream);
                }
                else
                {
                    if (result.HasBody)
                    {
                        if (result.Length > 0)
                        {
                            stream.Write(HeaderTypeFactory.CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.CONTENT_LENGTH_BYTES.Length);
                            stream.Write(result.Length.ToString());
                            stream.Write(HeaderTypeFactory.TOW_LINE_BYTES, 0, 4);
                            result.Write(stream, this);
                        }
                        else
                        {
                            stream.Write(HeaderTypeFactory.CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.CONTENT_LENGTH_BYTES.Length);
                            MemoryBlockCollection contentLength = stream.Allocate(10);
                            stream.Write(HeaderTypeFactory.TOW_LINE_BYTES, 0, 4);
                            int len = stream.CacheLength;
                            result.Write(stream, this);
                            int count = stream.CacheLength - len;
                            // contentLength.Full(count.ToString().PadRight(10), stream.Encoding);
                            contentLength.Full(GetLengthBuffer(count.ToString()));
                        }
                    }
                    else
                    {
                        stream.Write(HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES.Length);
                        stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
                    }
                }
            }
            else
            {
                stream.Write(HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES.Length);
                stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
            }

            if (Session.Server.EnableLog(EventArgs.LogType.Debug))
            {
                Session.Server.Log(EventArgs.LogType.Debug, Session, "{0} {1}", Request.RemoteIPAddress, this.ToString());
            }

            if (Session.Server.EnableLog(EventArgs.LogType.Info))
            {
                Session.Server.Log(EventArgs.LogType.Info, Session, "{4} {0} {1} response {2} {3}", Request.Method, Request.Url, Code, CodeMsg, Request.RemoteIPAddress);
            }
        }