예제 #1
0
파일: HttpAuth.cs 프로젝트: dstimac/revenj
        public virtual AuthorizeOrError TryAuthorize(string authorization, string url, RouteHandler route)
        {
            if (authorization == null)
                return AuthorizeOrError.Unauthorized("Authorization header not provided.", true);

            var splt = authorization.Split(' ');
            var authType = splt[0];
            if (splt.Length != 2)
                return AuthorizeOrError.Unauthorized("Invalid authorization header.", false);

            var cred = Encoding.UTF8.GetString(Convert.FromBase64String(splt[1])).Split(':');
            if (cred.Length != 2)
                return AuthorizeOrError.Unauthorized("Invalid authorization header content.", false);

            var user = cred[0];

            if (string.IsNullOrEmpty(user))
                return AuthorizeOrError.Fail("User not specified in authorization header.", HttpStatusCode.Unauthorized);

            var isAuthenticated = authType == "Hash"
                ? HashAuthentication.IsAuthenticated(user, Convert.FromBase64String(cred[1]))
                : PassAuthentication.IsAuthenticated(user, cred[1]);

            var identity = new RestIdentity(authType, isAuthenticated, user);
            if (!identity.IsAuthenticated)
            {
                if ((PublicUrl.Contains(url)
                    || PublicTemplate.Contains(route.Template)))
                    return AuthorizeOrError.Success(PrincipalFactory.Create(identity));
                return AuthorizeOrError.Fail("User {0} was not authenticated.".With(user), HttpStatusCode.Forbidden);
            }
            return AuthorizeOrError.Success(PrincipalFactory.Create(identity));
        }
예제 #2
0
파일: HttpAuth.cs 프로젝트: nutrija/revenj
        public virtual AuthorizeOrError TryAuthorize(HttpListenerContext context, RouteHandler route)
        {
            var request = context.Request;
            var authorization = request.Headers["Authorization"] ?? DefaultAuthorization;
            if (authorization == null)
            {
                context.Response.AddHeader("WWW-Authenticate", MissingBasicAuth);
                return AuthorizeOrError.Fail("Authorization header not provided.", HttpStatusCode.Unauthorized);
            }

            var splt = authorization.Split(' ');
            var authType = splt[0];
            if (splt.Length != 2)
                return AuthorizeOrError.Fail("Invalid authorization header.", HttpStatusCode.Unauthorized);

            var cred = Encoding.UTF8.GetString(Convert.FromBase64String(splt[1])).Split(':');
            if (cred.Length != 2)
                return AuthorizeOrError.Fail("Invalid authorization header content.", HttpStatusCode.Unauthorized);

            var user = cred[0];

            if (string.IsNullOrEmpty(user))
                return AuthorizeOrError.Fail("User not specified in authorization header.", HttpStatusCode.Unauthorized);

            var identity = new RestIdentity(authType, Authentication.IsAuthenticated(user, cred[1]), user);
            if (!identity.IsAuthenticated)
            {
                if ((PublicUrl.Contains(request.RawUrl)
                    || PublicTemplate.Contains(route.Template)))
                    return AuthorizeOrError.Success(PrincipalFactory.Create(identity));
                return AuthorizeOrError.Fail("User {0} was not authenticated.".With(user), HttpStatusCode.Forbidden);
            }
            return AuthorizeOrError.Success(PrincipalFactory.Create(identity));
        }
예제 #3
0
        private RouteMatch?ReadUrl(int rowEnd, out RouteHandler handler)
        {
            var httpLen1 = HttpMethod.Length + 1;
            var charBuf  = TmpCharBuf;
            var end      = rowEnd - 2 - HttpProtocolVersion.Length;

            for (int x = httpLen1; x < end; x++)
            {
                var tb = InputTemp[x];
                if (tb > 250)
                {
                    RawUrl = UTF8.GetString(InputTemp, httpLen1, end - httpLen1);
                    var askSign      = RawUrl.IndexOf('?');
                    var absolutePath = askSign == -1 ? RawUrl : RawUrl.Substring(0, askSign);
                    return(Routes.Find(HttpMethod, RawUrl, absolutePath, out handler));
                }
                charBuf[x - httpLen1] = (char)tb;
            }
            var match = Routes.Find(HttpMethod, charBuf, end - httpLen1, out handler);

            if (match == null)
            {
                RawUrl = new string(charBuf, 0, end - httpLen1);
            }
            else
            {
                RawUrl = match.Value.RawUrl;
            }
            return(match);
        }
예제 #4
0
파일: Routes.cs 프로젝트: nutrija/revenj
 private void Add(string method, RouteHandler handler)
 {
     List<RouteHandler> list;
     if (!MethodRoutes.TryGetValue(method, out list))
         MethodRoutes[method] = list = new List<RouteHandler>();
     list.Add(handler);
 }
예제 #5
0
        private void Add(string method, RouteHandler handler)
        {
            Dictionary <string, List <RouteHandler> > dict;

            if (!MethodRoutes.TryGetValue(method, out dict))
            {
                MethodRoutes[method] = dict = new Dictionary <string, List <RouteHandler> >();
            }
            List <RouteHandler> list;

            if (!dict.TryGetValue(handler.Service, out list))
            {
                dict[handler.Service] = list = new List <RouteHandler>();
            }
            var first = list.FindIndex(it => it.Pattern.Groups < handler.Pattern.Groups);

            if (first != -1)
            {
                list.Insert(first, handler);
            }
            else
            {
                list.Add(handler);
            }
        }
예제 #6
0
        private void ConfigureService(IServiceProvider locator, IWireSerialization serialization, string name, Type type)
        {
            var instance = locator.GetService(type);

            foreach (var i in new[] { type }.Union(type.GetInterfaces()))
            {
                foreach (var m in i.GetMethods())
                {
                    var inv   = (WebInvokeAttribute[])m.GetCustomAttributes(typeof(WebInvokeAttribute), false);
                    var get   = (WebGetAttribute[])m.GetCustomAttributes(typeof(WebGetAttribute), false);
                    var route = (RouteAttribute[])m.GetCustomAttributes(typeof(RouteAttribute), false);
                    foreach (var at in inv)
                    {
                        var rh = new RouteHandler(name, at.UriTemplate, instance, true, m, locator, serialization);
                        Add(at.Method, rh);
                    }
                    foreach (var at in get)
                    {
                        var rh = new RouteHandler(name, at.UriTemplate, instance, true, m, locator, serialization);
                        Add("GET", rh);
                    }
                    foreach (var at in route)
                    {
                        var rh = new RouteHandler(name, at.Path, instance, at.IsAsync, m, locator, serialization);
                        Add(at.Method, rh);
                    }
                }
            }
        }
예제 #7
0
파일: Routes.cs 프로젝트: ngs-doo/revenj
 public RouteMatch? Find(string httpMethod, string rawUrl, string absolutePath, out RouteHandler handler)
 {
     var reqHash = StringCache.CalcHash(httpMethod, absolutePath);
     if (Cache.TryGetValue(reqHash, out handler))
     {
         return handler.Pattern.ExtractMatch(rawUrl, handler.Service.Length);
     }
     return FindRoute(httpMethod, rawUrl, reqHash, out handler);
 }
예제 #8
0
 public ThreadArgs(Socket socket, HttpSocketContext context, ManualResetEventSlim resetEvent, HttpAuth.AuthorizeOrError auth, RouteHandler route, RouteMatch match)
 {
     this.Socket     = socket;
     this.Context    = context;
     this.ResetEvent = resetEvent;
     this.Auth       = auth;
     this.Route      = route;
     this.Match      = match;
 }
예제 #9
0
 public ThreadArgs(RequestInfo request, HttpSocketContext context, ManualResetEvent resetEvent, HttpAuth.AuthorizeOrError auth, RouteHandler route, RouteMatch match)
 {
     this.Request    = request;;
     this.Context    = context;
     this.ResetEvent = resetEvent;
     this.Auth       = auth;
     this.Route      = route;
     this.Match      = match;
 }
예제 #10
0
        private void Add(string method, RouteHandler handler)
        {
            List <RouteHandler> list;

            if (!MethodRoutes.TryGetValue(method, out list))
            {
                MethodRoutes[method] = list = new List <RouteHandler>();
            }
            list.Add(handler);
        }
예제 #11
0
        public virtual AuthorizeOrError TryAuthorize(HttpListenerContext context, RouteHandler route)
        {
            var request       = context.Request;
            var authorization = request.Headers["Authorization"] ?? DefaultAuthorization;

            if (authorization == null)
            {
                context.Response.AddHeader("WWW-Authenticate", MissingBasicAuth);
                return(AuthorizeOrError.Fail("Authorization header not provided.", HttpStatusCode.Unauthorized));
            }

            var splt     = authorization.Split(' ');
            var authType = splt[0];

            if (splt.Length != 2)
            {
                return(AuthorizeOrError.Fail("Invalid authorization header.", HttpStatusCode.Unauthorized));
            }

            var cred = Encoding.UTF8.GetString(Convert.FromBase64String(splt[1])).Split(':');

            if (cred.Length != 2)
            {
                return(AuthorizeOrError.Fail("Invalid authorization header content.", HttpStatusCode.Unauthorized));
            }

            var user = cred[0];

            if (string.IsNullOrEmpty(user))
            {
                return(AuthorizeOrError.Fail("User not specified in authorization header.", HttpStatusCode.Unauthorized));
            }

            var isAuthenticated = authType == "Hash"
                                ? HashAuthentication.IsAuthenticated(user, Convert.FromBase64String(cred[1]))
                                : PassAuthentication.IsAuthenticated(user, cred[1]);

            var identity = new RestIdentity(authType, isAuthenticated, user);

            if (!identity.IsAuthenticated)
            {
                if ((PublicUrl.Contains(request.RawUrl) ||
                     PublicTemplate.Contains(route.Template)))
                {
                    return(AuthorizeOrError.Success(PrincipalFactory.Create(identity)));
                }
                return(AuthorizeOrError.Fail("User {0} was not authenticated.".With(user), HttpStatusCode.Forbidden));
            }
            return(AuthorizeOrError.Success(PrincipalFactory.Create(identity)));
        }
예제 #12
0
파일: Routes.cs 프로젝트: zhxjdwh/revenj
        private RouteMatch?FindRoute(string httpMethod, string rawUrl, int reqHash, out RouteHandler handler)
        {
            handler = null;
            Dictionary <string, List <RouteHandler> > handlers;

            if (!MethodRoutes.TryGetValue(httpMethod, out handlers))
            {
                return(null);
            }
            if (rawUrl.IndexOf('/') == rawUrl.LastIndexOf('/'))
            {
                return(null);
            }
            string service;
            int    pos = rawUrl.IndexOf('/', 1);

            if (pos == -1)
            {
                service = rawUrl.ToLowerInvariant();
            }
            else
            {
                service = rawUrl.Substring(0, pos).ToLowerInvariant();
            }
            List <RouteHandler> routes;

            if (!handlers.TryGetValue(service, out routes))
            {
                return(null);
            }
            foreach (var h in routes)
            {
                var match = h.Pattern.Match(rawUrl, service.Length);
                if (match != null)
                {
                    var newCache = new Dictionary <int, RouteHandler>(Cache);
                    newCache[reqHash] = h;
                    Cache             = newCache;
                    handler           = h;
                    return(match);
                }
            }
            return(null);
        }
예제 #13
0
        private void ConfigureService(XElement service, IServiceLocator locator)
        {
            var attributes = service.Attributes().ToList();
            var ra         = attributes.FirstOrDefault(it => "relativeAddress".Equals(it.Name.LocalName, StringComparison.InvariantCultureIgnoreCase));
            var serv       = attributes.FirstOrDefault(it => "service".Equals(it.Name.LocalName, StringComparison.InvariantCultureIgnoreCase));

            if (serv == null || string.IsNullOrEmpty(serv.Value))
            {
                throw new ConfigurationErrorsException("Missing service type on serviceActivation element: " + service.ToString());
            }
            if (ra == null || string.IsNullOrEmpty(ra.Value))
            {
                throw new ConfigurationErrorsException("Missing relative address on serviceActivation element: " + service.ToString());
            }
            var type = Type.GetType(serv.Value);

            if (type == null)
            {
                throw new ConfigurationErrorsException("Invalid service defined in " + ra.Value + ". Type " + serv.Value + " not found.");
            }
            var instance = locator.Resolve(type);

            foreach (var i in type.GetInterfaces())
            {
                foreach (var m in i.GetMethods())
                {
                    var inv = (WebInvokeAttribute[])m.GetCustomAttributes(typeof(WebInvokeAttribute), false);
                    var get = (WebGetAttribute[])m.GetCustomAttributes(typeof(WebGetAttribute), false);
                    foreach (var at in inv)
                    {
                        var rh = new RouteHandler(ra.Value, at.UriTemplate, instance, m);
                        Add(at.Method, rh);
                    }
                    foreach (var at in get)
                    {
                        var rh = new RouteHandler(ra.Value, at.UriTemplate, instance, m);
                        Add("GET", rh);
                    }
                }
            }
        }
예제 #14
0
파일: Routes.cs 프로젝트: zhxjdwh/revenj
        internal RouteMatch?Find(string httpMethod, char[] buffer, int len, out RouteHandler handler)
        {
            var reqHash = StringCache.CalcHash(httpMethod, buffer, len);
            int askSign = -1;

            for (int i = 0; i < len; i++)
            {
                if (buffer[i] == '?')
                {
                    askSign = i;
                    break;
                }
            }
            if (askSign == -1 && Cache.TryGetValue(reqHash, out handler))
            {
                if (handler.Pattern.IsStatic)
                {
                    return(handler.Pattern.ExtractMatch(handler.Url, 0));
                }
            }
            var rawUrl = new string(buffer, 0, len);

            return(FindRoute(httpMethod, rawUrl, reqHash, out handler));
        }
예제 #15
0
파일: NoAuth.cs 프로젝트: rpetrano/revenj
 public override AuthorizeOrError TryAuthorize(HttpListenerContext context, RouteHandler route)
 {
     return AuthorizeOrError.Success(new GenericPrincipal(new GenericIdentity("guest"), NoRoles));
 }
예제 #16
0
 private void ConfigureService(XElement service, IServiceLocator locator)
 {
     var attributes = service.Attributes().ToList();
     var ra = attributes.FirstOrDefault(it => "relativeAddress".Equals(it.Name.LocalName, StringComparison.InvariantCultureIgnoreCase));
     var serv = attributes.FirstOrDefault(it => "service".Equals(it.Name.LocalName, StringComparison.InvariantCultureIgnoreCase));
     if (serv == null || string.IsNullOrEmpty(serv.Value))
         throw new ConfigurationErrorsException("Missing service type on serviceActivation element: " + service.ToString());
     if (ra == null || string.IsNullOrEmpty(ra.Value))
         throw new ConfigurationErrorsException("Missing relative address on serviceActivation element: " + service.ToString());
     var type = Type.GetType(serv.Value);
     if (type == null)
         throw new ConfigurationErrorsException("Invalid service defined in " + ra.Value + ". Type " + serv.Value + " not found.");
     var instance = locator.Resolve(type);
     foreach (var i in new[] { type }.Union(type.GetInterfaces()))
     {
         foreach (var m in i.GetMethods())
         {
             var inv = (WebInvokeAttribute[])m.GetCustomAttributes(typeof(WebInvokeAttribute), false);
             var get = (WebGetAttribute[])m.GetCustomAttributes(typeof(WebGetAttribute), false);
             foreach (var at in inv)
             {
                 var rh = new RouteHandler(ra.Value, at.UriTemplate, instance, m);
                 Add(at.Method, rh);
             }
             foreach (var at in get)
             {
                 var rh = new RouteHandler(ra.Value, at.UriTemplate, instance, m);
                 Add("GET", rh);
             }
         }
     }
 }
예제 #17
0
        public bool Parse(Socket socket, out RouteMatch?match, out RouteHandler route)
        {
            positionInTmp = 0;
            Pipeline      = false;
            var methodEnd = ReadUntil(socket, Space, 0);

            if (methodEnd == -1)
            {
                match = null;
                route = null;
                if (!socket.Connected)
                {
                    offsetInOutput = 0;
                    return(false);
                }
                else if (positionInTmp == 0)
                {
                    if (offsetInOutput != 0)
                    {
                        socket.Send(OutputTemp, offsetInOutput, SocketFlags.None);
                        offsetInOutput = 0;
                        socket.Close();
                        return(false);
                    }
                    else
                    {
                        return(ReturnError(socket, 408));
                    }
                }
                else
                {
                    return(ReturnError(socket, 505));
                }
            }
            HttpMethod = ReadMethod(methodEnd, InputTemp);
            var rowEnd = ReadUntil(socket, LF, methodEnd + 1);

            if (rowEnd == -1 || rowEnd < 12)
            {
                match = null;
                route = null;
                return(ReturnError(socket, 505));
            }
            RequestHeadersLength  = 0;
            ResponseHeadersLength = 0;
            HttpProtocolVersion   = ReadProtocol(rowEnd - 2);
            if (HttpProtocolVersion == null)
            {
                match = null;
                route = null;
                ReturnError(socket, 505, "Only HTTP/1.1 and HTTP/1.0 supported (partially)", false);
                return(false);
            }
            match = ReadUrl(rowEnd, out route);
            if (route == null)
            {
                var unknownRoute = "Unknown route " + RawUrl + " on method " + HttpMethod;
                ReturnError(socket, 404, unknownRoute, false);
                return(false);
            }
            ResponseStatus           = HttpStatusCode.OK;
            ResponseLength           = null;
            ResponseContentType      = null;
            TemplateMatch            = null;
            ResponseIsJson           = false;
            ContentTypeResponseIndex = -1;
            do
            {
                var start = rowEnd + 1;
                rowEnd = ReadUntil(socket, CR, start);
                if (rowEnd == start)
                {
                    break;
                }
                else if (rowEnd == -1)
                {
                    return(ReturnError(socket, 414));
                }
                else
                {
                    int i = start;
                    for (; i < rowEnd; i++)
                    {
                        if (InputTemp[i] == ':')
                        {
                            break;
                        }
                    }
                    if (i == rowEnd)
                    {
                        return(ReturnError(socket, 414));
                    }
                    var nameBuf = TmpCharBuf;
                    for (int x = start; x < i; x++)
                    {
                        nameBuf[x - start] = Lower[InputTemp[x]];
                    }
                    var name = KeyCache.Get(nameBuf, i - start);
                    if (InputTemp[i + 1] == 32)
                    {
                        i++;
                    }
                    for (int x = i + 1; x < rowEnd; x++)
                    {
                        nameBuf[x - i - 1] = (char)InputTemp[x];
                    }
                    var value = ValueCache.Get(nameBuf, rowEnd - i - 1);
                    if (RequestHeadersLength == RequestHeaders.Length)
                    {
                        var newHeaders = new HeaderPair[RequestHeaders.Length * 2];
                        Array.Copy(RequestHeaders, newHeaders, RequestHeaders.Length);
                        RequestHeaders = newHeaders;
                    }
                    RequestHeaders[RequestHeadersLength++] = new HeaderPair(name, value);
                }
                rowEnd++;
            } while (positionInTmp <= InputTemp.Length);
            rowEnd += 2;
            if (HttpMethod == "POST" || HttpMethod == "PUT")
            {
                int len = 0;
                var ct  = GetRequestHeader("content-length");
                if (ct != null)
                {
                    if (!int.TryParse(ct, out len))
                    {
                        return(ReturnError(socket, 411));
                    }
                    if (len > Limit)
                    {
                        return(ReturnError(socket, 413));
                    }
                }
                else
                {
                    return(ReturnError(socket, 411));
                }
                InputStream.Reset();
                var size = totalBytes - rowEnd;
                InputStream.Write(InputTemp, rowEnd, size);
                len -= size;
                var oldTimeout = socket.ReceiveTimeout;
                socket.ReceiveTimeout = 10000;
                while (len > 0)
                {
                    size = socket.Receive(InputTemp, Math.Min(len, InputTemp.Length), SocketFlags.None);
                    if (size < 1)
                    {
                        return(ReturnError(socket, 408));
                    }
                    InputStream.Write(InputTemp, 0, size);
                    len -= size;
                }
                socket.ReceiveTimeout = oldTimeout;
                InputStream.Position  = 0;
                rowEnd     = totalBytes;
                totalBytes = 0;
            }
            else
            {
                Pipeline = rowEnd < totalBytes;
                if (Pipeline)
                {
                    Buffer.BlockCopy(InputTemp, rowEnd, InputTemp, 0, totalBytes - rowEnd);
                    totalBytes -= rowEnd;
                }
                else
                {
                    totalBytes = 0;
                }
            }
            return(true);
        }
예제 #18
0
파일: HttpAuth.cs 프로젝트: zhxjdwh/revenj
        public virtual AuthorizeOrError TryAuthorize(string authorization, string url, RouteHandler route)
        {
            if (authorization == null)
            {
                return(AuthorizeOrError.Unauthorized("Authorization header not provided.", true));
            }

            var splt     = authorization.Split(' ');
            var authType = splt[0];

            if (splt.Length != 2)
            {
                return(AuthorizeOrError.Unauthorized("Invalid authorization header.", false));
            }

            var cred = Encoding.UTF8.GetString(Convert.FromBase64String(splt[1])).Split(':');

            if (cred.Length != 2)
            {
                return(AuthorizeOrError.Unauthorized("Invalid authorization header content.", false));
            }

            var user = cred[0];

            if (string.IsNullOrEmpty(user))
            {
                return(AuthorizeOrError.Fail("User not specified in authorization header.", HttpStatusCode.Unauthorized));
            }

            var isAuthenticated = authType == "Hash"
                                ? HashAuthentication.IsAuthenticated(user, Convert.FromBase64String(cred[1]))
                                : PassAuthentication.IsAuthenticated(user, cred[1]);

            var identity = new RestIdentity(authType, isAuthenticated, user);

            if (!identity.IsAuthenticated)
            {
                if ((PublicUrl.Contains(url) ||
                     PublicTemplate.Contains(route.Template)))
                {
                    return(AuthorizeOrError.Success(PrincipalFactory.Create(identity)));
                }
                return(AuthorizeOrError.Fail("User {0} was not authenticated.".With(user), HttpStatusCode.Forbidden));
            }
            return(AuthorizeOrError.Success(PrincipalFactory.Create(identity)));
        }
예제 #19
0
 public bool Parse(Socket socket, out RouteMatch? match, out RouteHandler route)
 {
     positionInTmp = 0;
     Pipeline = false;
     var methodEnd = ReadUntil(socket, Space, 0);
     if (methodEnd == -1)
     {
         match = null;
         route = null;
         if (!socket.Connected)
         {
             offsetInOutput = 0;
             return false;
         }
         else if (positionInTmp == 0)
         {
             if (offsetInOutput != 0)
             {
                 socket.Send(OutputTemp, offsetInOutput, SocketFlags.None);
                 offsetInOutput = 0;
                 socket.Close();
                 return false;
             }
             else return ReturnError(socket, 408);
         }
         else return ReturnError(socket, 505);
     }
     HttpMethod = ReadMethod(methodEnd, InputTemp);
     var rowEnd = ReadUntil(socket, LF, methodEnd + 1);
     if (rowEnd == -1 || rowEnd < 12)
     {
         match = null;
         route = null;
         return ReturnError(socket, 505);
     }
     RequestHeadersLength = 0;
     ResponseHeadersLength = 0;
     HttpProtocolVersion = ReadProtocol(rowEnd - 2);
     if (HttpProtocolVersion == null)
     {
         match = null;
         route = null;
         ReturnError(socket, 505, "Only HTTP/1.1 and HTTP/1.0 supported (partially)", false);
         return false;
     }
     match = ReadUrl(rowEnd, out route);
     if (route == null)
     {
         var unknownRoute = "Unknown route " + RawUrl + " on method " + HttpMethod;
         ReturnError(socket, 404, unknownRoute, false);
         return false;
     }
     ResponseStatus = HttpStatusCode.OK;
     ResponseLength = null;
     ResponseContentType = null;
     TemplateMatch = null;
     ResponseIsJson = false;
     ContentTypeResponseIndex = -1;
     do
     {
         var start = rowEnd + 1;
         rowEnd = ReadUntil(socket, CR, start);
         if (rowEnd == start) break;
         else if (rowEnd == -1) return ReturnError(socket, 414);
         else
         {
             int i = start;
             for (; i < rowEnd; i++)
                 if (InputTemp[i] == ':')
                     break;
             if (i == rowEnd) return ReturnError(socket, 414);
             var nameBuf = TmpCharBuf;
             for (int x = start; x < i; x++)
                 nameBuf[x - start] = Lower[InputTemp[x]];
             var name = KeyCache.Get(nameBuf, i - start);
             if (InputTemp[i + 1] == 32) i++;
             for (int x = i + 1; x < rowEnd; x++)
                 nameBuf[x - i - 1] = (char)InputTemp[x];
             var value = ValueCache.Get(nameBuf, rowEnd - i - 1);
             if (RequestHeadersLength == RequestHeaders.Length)
             {
                 var newHeaders = new HeaderPair[RequestHeaders.Length * 2];
                 Array.Copy(RequestHeaders, newHeaders, RequestHeaders.Length);
                 RequestHeaders = newHeaders;
             }
             RequestHeaders[RequestHeadersLength++] = new HeaderPair(name, value);
         }
         rowEnd++;
     } while (positionInTmp <= InputTemp.Length);
     rowEnd += 2;
     if (HttpMethod == "POST" || HttpMethod == "PUT")
     {
         int len = 0;
         var ct = GetRequestHeader("content-length");
         if (ct != null)
         {
             if (!int.TryParse(ct, out len)) return ReturnError(socket, 411);
             if (len > Limit) return ReturnError(socket, 413);
         }
         else return ReturnError(socket, 411);
         InputStream.Reset();
         var size = totalBytes - rowEnd;
         InputStream.Write(InputTemp, rowEnd, size);
         len -= size;
         var oldTimeout = socket.ReceiveTimeout;
         socket.ReceiveTimeout = 10000;
         while (len > 0)
         {
             size = socket.Receive(InputTemp, Math.Min(len, InputTemp.Length), SocketFlags.None);
             if (size < 1) return ReturnError(socket, 408);
             InputStream.Write(InputTemp, 0, size);
             len -= size;
         }
         socket.ReceiveTimeout = oldTimeout;
         InputStream.Position = 0;
         rowEnd = totalBytes;
         totalBytes = 0;
     }
     else
     {
         Pipeline = rowEnd < totalBytes;
         if (Pipeline)
         {
             Buffer.BlockCopy(InputTemp, rowEnd, InputTemp, 0, totalBytes - rowEnd);
             totalBytes -= rowEnd;
         }
         else
         {
             totalBytes = 0;
         }
     }
     return true;
 }
예제 #20
0
파일: Routes.cs 프로젝트: ngs-doo/revenj
 internal RouteMatch? Find(string httpMethod, char[] buffer, int len, out RouteHandler handler)
 {
     var reqHash = StringCache.CalcHash(httpMethod, buffer, len);
     int askSign = -1;
     for (int i = 0; i < len; i++)
     {
         if (buffer[i] == '?')
         {
             askSign = i;
             break;
         }
     }
     if (askSign == -1 && Cache.TryGetValue(reqHash, out handler))
     {
         if (handler.Pattern.IsStatic)
             return handler.Pattern.ExtractMatch(handler.Url, 0);
     }
     var rawUrl = new string(buffer, 0, len);
     return FindRoute(httpMethod, rawUrl, reqHash, out handler);
 }
예제 #21
0
 private RouteMatch? ReadUrl(int rowEnd, out RouteHandler handler)
 {
     var httpLen1 = HttpMethod.Length + 1;
     var charBuf = TmpCharBuf;
     var end = rowEnd - 2 - HttpProtocolVersion.Length;
     for (int x = httpLen1; x < end; x++)
     {
         var tb = InputTemp[x];
         if (tb > 250)
         {
             RawUrl = UTF8.GetString(InputTemp, httpLen1, end - httpLen1);
             var askSign = RawUrl.IndexOf('?');
             var absolutePath = askSign == -1 ? RawUrl : RawUrl.Substring(0, askSign);
             return Routes.Find(HttpMethod, RawUrl, absolutePath, out handler);
         }
         charBuf[x - httpLen1] = (char)tb;
     }
     var match = Routes.Find(HttpMethod, charBuf, end - httpLen1, out handler);
     if (match == null)
         RawUrl = new string(charBuf, 0, end - httpLen1);
     else
         RawUrl = match.Value.RawUrl;
     return match;
 }
예제 #22
0
파일: Routes.cs 프로젝트: ngs-doo/revenj
 private RouteMatch? FindRoute(string httpMethod, string rawUrl, int reqHash, out RouteHandler handler)
 {
     handler = null;
     Dictionary<string, List<RouteHandler>> handlers;
     if (!MethodRoutes.TryGetValue(httpMethod, out handlers))
         return null;
     if (rawUrl.IndexOf('/') == rawUrl.LastIndexOf('/'))
         return null;
     string service;
     int pos = rawUrl.IndexOf('/', 1);
     if (pos == -1)
         service = rawUrl.ToLowerInvariant();
     else
         service = rawUrl.Substring(0, pos).ToLowerInvariant();
     List<RouteHandler> routes;
     if (!handlers.TryGetValue(service, out routes))
         return null;
     foreach (var h in routes)
     {
         var match = h.Pattern.Match(rawUrl, service.Length);
         if (match != null)
         {
             var newCache = new Dictionary<int, RouteHandler>(Cache);
             newCache[reqHash] = h;
             Cache = newCache;
             handler = h;
             return match;
         }
     }
     return null;
 }
예제 #23
0
파일: Routes.cs 프로젝트: ngs-doo/revenj
 private void ConfigureService(IServiceProvider locator, IWireSerialization serialization, string name, Type type)
 {
     var instance = locator.GetService(type);
     foreach (var i in new[] { type }.Union(type.GetInterfaces()))
     {
         foreach (var m in i.GetMethods())
         {
             var inv = (WebInvokeAttribute[])m.GetCustomAttributes(typeof(WebInvokeAttribute), false);
             var get = (WebGetAttribute[])m.GetCustomAttributes(typeof(WebGetAttribute), false);
             var route = (RouteAttribute[])m.GetCustomAttributes(typeof(RouteAttribute), false);
             foreach (var at in inv)
             {
                 var rh = new RouteHandler(name, at.UriTemplate, instance, true, m, locator, serialization);
                 Add(at.Method, rh);
             }
             foreach (var at in get)
             {
                 var rh = new RouteHandler(name, at.UriTemplate, instance, true, m, locator, serialization);
                 Add("GET", rh);
             }
             foreach (var at in route)
             {
                 var rh = new RouteHandler(name, at.Path, instance, at.IsAsync, m, locator, serialization);
                 Add(at.Method, rh);
             }
         }
     }
 }
예제 #24
0
 public ThreadArgs(RequestInfo request, HttpSocketContext context, ManualResetEvent resetEvent, HttpAuth.AuthorizeOrError auth, RouteHandler route, RouteMatch match)
 {
     this.Request = request; ;
     this.Context = context;
     this.ResetEvent = resetEvent;
     this.Auth = auth;
     this.Route = route;
     this.Match = match;
 }
예제 #25
0
파일: NoAuth.cs 프로젝트: zhxjdwh/revenj
 public override AuthorizeOrError TryAuthorize(string authorization, string url, RouteHandler route)
 {
     return(AuthorizeOrError.Success(Guest));
 }
예제 #26
0
파일: Routes.cs 프로젝트: zhxjdwh/revenj
        public RouteMatch?Find(string httpMethod, string rawUrl, string absolutePath, out RouteHandler handler)
        {
            var reqHash = StringCache.CalcHash(httpMethod, absolutePath);

            if (Cache.TryGetValue(reqHash, out handler))
            {
                return(handler.Pattern.ExtractMatch(rawUrl, handler.Service.Length));
            }
            return(FindRoute(httpMethod, rawUrl, reqHash, out handler));
        }
예제 #27
0
파일: Routes.cs 프로젝트: ngs-doo/revenj
 private void Add(string method, RouteHandler handler)
 {
     Dictionary<string, List<RouteHandler>> dict;
     if (!MethodRoutes.TryGetValue(method, out dict))
         MethodRoutes[method] = dict = new Dictionary<string, List<RouteHandler>>();
     List<RouteHandler> list;
     if (!dict.TryGetValue(handler.Service, out list))
         dict[handler.Service] = list = new List<RouteHandler>();
     var first = list.FindIndex(it => it.Pattern.Groups < handler.Pattern.Groups);
     if (first != -1)
         list.Insert(first, handler);
     else
         list.Add(handler);
 }
예제 #28
0
 public override AuthorizeOrError TryAuthorize(HttpListenerContext context, RouteHandler route)
 {
     return(AuthorizeOrError.Success(new GenericPrincipal(new GenericIdentity("guest"), NoRoles)));
 }