Ejemplo n.º 1
0
        private void TestEncodingHandler(HttpEntityManager http, UriTemplateMatch match)
        {
            var a = match.BoundVariables["a"];
            var b = match.BoundVariables["b"];

            http.Reply(new { a = a, b = b, rawSegment = http.RequestedUrl.Segments[2] }.ToJson(), 200, "OK", "application/json");
        }
 public bool IsMatch(Uri baseUri, Uri candidate)
 {
     if (Method.HttpMethod.ToString().Equals(WebOperationContext.Current.IncomingRequest.Method, StringComparison.CurrentCultureIgnoreCase))
     //&& Method.QueryType.Equals(WebOperationContext.Current.IncomingRequest.ContentType, StringComparison.CurrentCultureIgnoreCase))
     {
         match = Template.Match(baseUri, candidate);
         if (!(match == null))
         {
             if (Template.QueryValueVariableNames.Count == 0)
             {
                 if (Template.PathSegmentVariableNames.Count == 0)
                 {
                     if (Template.Url.Query.Count == 0)
                     {
                         MatchType = MatchType.Static;
                     }
                     else
                     {
                         MatchType = MatchType.Static | MatchType.Query;
                     }
                 }
                 else
                 {
                     MatchType = MatchType.Template;
                 }
             }
             else
             {
                 MatchType = MatchType.Query;
             }
             return true;
         }
     }
     return false;
 }
        private void AckMessages(HttpEntityManager http, UriTemplateMatch match)
        {
            var envelope = new NoopEnvelope();
            var groupname = match.BoundVariables["subscription"];
            var stream = match.BoundVariables["stream"];
            var messageIds = match.BoundVariables["messageIds"];
            var ids = new List<Guid>();
            foreach (var messageId in messageIds.Split(new[] { ',' }))
            {
                Guid id;
                if (!Guid.TryParse(messageId, out id))
                {
                    http.ReplyStatus(HttpStatusCode.BadRequest, "messageid should be a properly formed guid", exception => { });
                    return;
                }
                ids.Add(id);
            }

            var cmd = new ClientMessage.PersistentSubscriptionAckEvents(
                                             Guid.NewGuid(),
                                             Guid.NewGuid(),
                                             envelope,
                                             BuildSubscriptionGroupKey(stream, groupname),
                                             ids.ToArray(),
                                             http.User);
            Publish(cmd);
            http.ReplyStatus(HttpStatusCode.Accepted, "", exception => { });
        }
Ejemplo n.º 4
0
 private void TestAnonymousHandler(HttpEntityManager http, UriTemplateMatch match)
 {
     if (http.User != null)
         http.Reply("ERROR", 500, "ERROR", "text/plain");
     else 
         http.Reply("OK", 200, "OK", "text/plain");
 }
Ejemplo n.º 5
0
 private void Test1Handler(HttpEntityManager http, UriTemplateMatch match)
 {
     if (http.User != null) 
         http.Reply("OK", 200, "OK", "text/plain");
     else 
         http.Reply("Please authenticate yourself", 401, "Unauthorized", "text/plain");
 }
Ejemplo n.º 6
0
 private void OnPostShutdown(HttpEntity entity, UriTemplateMatch match)
 {
     Publish(new ClientMessage.RequestShutdown());
     entity.Manager.Reply(HttpStatusCode.OK,
                          "OK",
                          e => Log.ErrorException(e, "Error while closing http connection (admin controller)"));
 }
        private void OnGetFreshStats(HttpEntityManager entity, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                                  entity,
                                                  Format.GetFreshStatsCompleted,
                                                  Configure.GetFreshStatsCompleted);

            var statPath = match.BoundVariables["statPath"];
            var statSelector = GetStatSelector(statPath);

            bool useMetadata;
            if (!bool.TryParse(match.QueryParameters["metadata"], out useMetadata))
                useMetadata = false;

            bool useGrouping;
            if (!bool.TryParse(match.QueryParameters["group"], out useGrouping))
                useGrouping = true;

            if (!useGrouping && !string.IsNullOrEmpty(statPath))
            {
                SendBadRequest(entity, "Dynamic stats selection works only with grouping enabled");
                return;
            }
             
            Publish(new MonitoringMessage.GetFreshStats(envelope, statSelector, useMetadata, useGrouping));
        }
Ejemplo n.º 8
0
 public RouteHandler Find(HttpListenerRequest request, out UriTemplateMatch templateMatch)
 {
     var reqId = request.HttpMethod + ":" + request.Url.LocalPath;
     KeyValuePair<RouteHandler, Uri> rh;
     if (Cache.TryGetValue(reqId, out rh))
     {
         templateMatch = rh.Key.Template.Match(rh.Value, request.Url);
         return rh.Key;
     }
     templateMatch = null;
     List<RouteHandler> handlers;
     if (!MethodRoutes.TryGetValue(request.HttpMethod, out handlers))
         return null;
     var reqUrl = request.Url;
     var url = reqUrl.ToString();
     var baseAddr = new Uri(url.Substring(0, url.Length - request.RawUrl.Length));
     foreach (var h in handlers)
     {
         var match = h.Template.Match(baseAddr, reqUrl);
         if (match != null)
         {
             templateMatch = match;
             Cache.TryAdd(reqId, new KeyValuePair<RouteHandler, Uri>(h, baseAddr));
             return h;
         }
     }
     return null;
 }
Ejemplo n.º 9
0
 private bool TryUriTemplateMatch(string uri, out UriTemplateMatch uriTemplateMatch)
 {
     var uriTemplate = new UriTemplate(uri);
     var serverPath = Request.Url.GetServerBaseUri();
     uriTemplateMatch = uriTemplate.Match(new Uri(serverPath), Request.Url);
     return uriTemplateMatch != null;
 }
Ejemplo n.º 10
0
 private void OnGetTcpConnectionStats(HttpEntityManager entity, UriTemplateMatch match)
 {
     var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                           entity,
                                           Format.GetFreshTcpConnectionStatsCompleted,
                                           Configure.GetFreshTcpConnectionStatsCompleted);
     Publish(new MonitoringMessage.GetFreshTcpConnectionStats(envelope));
 }
 public UriToActionMatch(UriTemplateMatch templateMatch, 
                         ControllerAction controllerAction, 
                         Func<HttpEntityManager, UriTemplateMatch, RequestParams> requestHandler)
 {
     TemplateMatch = templateMatch;
     ControllerAction = controllerAction;
     RequestHandler = requestHandler;
 }
 public UriToActionMatch(UriTemplateMatch templateMatch, 
                         ControllerAction controllerAction, 
                         Action<HttpEntity, UriTemplateMatch> requestHandler)
 {
     TemplateMatch = templateMatch;
     ControllerAction = controllerAction;
     RequestHandler = requestHandler;
 }
 private void OnPostShutdown(HttpEntity entity, UriTemplateMatch match)
 {
     Log.Info("Request shut down of node because shutdown command has been received.");
     Publish(new ClientMessage.RequestShutdown(exitProcessOnShutdown: true));
     entity.Manager.ReplyStatus(HttpStatusCode.OK,
                          "OK",
                          e => Log.ErrorException(e, "Error while closing http connection (admin controller)"));
 }
Ejemplo n.º 14
0
 private void OnGetOptions(HttpEntityManager entity, UriTemplateMatch match)
 {
     entity.ReplyTextContent(Codec.Json.To(GetOptionsInfo(options)),
                             HttpStatusCode.OK,
                             "OK",
                             entity.ResponseCodec.ContentType,
                             null,
                             e => Log.ErrorException(e, "error while writing http response (options)"));
 }
 public SerializedResultArrayBeta(List<Result> x, UriTemplateMatch templateMatch, Uri Prefix, UriTemplate ResultResourceTemplate, UriTemplate ResourceArrayTemplate)
 {
     List<SerializedResultArrayEntry> r = new List<SerializedResultArrayEntry>();
     foreach (Result result in x)
     {
         r.Add(new SerializedResultArrayEntry(result, Prefix, ResultResourceTemplate));
     }
     Results = r;
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Virtual method to be able to extend principal.
        /// Returns "Guest" identity with no roles.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="match"></param>
        /// <returns></returns>
        public virtual IPrincipal GetPrincipal(HttpContext context, UriTemplateMatch match)
        {
            // using System.Security.Permissions;
            // using System.Security.Principal;

            GenericIdentity gi = new GenericIdentity("Guest");
            GenericPrincipal genPrincipal = new GenericPrincipal(gi, new string[]{});

            return genPrincipal;
        }
Ejemplo n.º 17
0
 private void OnGetPing(HttpEntityManager entity, UriTemplateMatch match)
 {
     var response = new HttpMessage.TextMessage("Ping request successfully handled");
     entity.ReplyTextContent(Format.TextMessage(entity, response),
                             HttpStatusCode.OK,
                             "OK",
                             entity.ResponseCodec.ContentType,
                             null,
                             e => Log.ErrorException(e, "Error while writing HTTP response (ping)"));
 }
Ejemplo n.º 18
0
 private void OnListNodeSubsystems(HttpEntityManager http, UriTemplateMatch match)
 {
     http.ReplyTextContent(
     Codec.Json.To(_enabledNodeSubsystems),
     200,
     "OK",
     "application/json",
     null,
     ex => Log.InfoException(ex, "Failed to prepare main menu")
     );
 }
Ejemplo n.º 19
0
 private void OnGetInfo(HttpEntityManager entity, UriTemplateMatch match)
 {
     entity.ReplyTextContent(Codec.Json.To(new
                             {
                                 ESVersion = VersionInfo.Version
                             }),
                             HttpStatusCode.OK,
                             "OK",
                             entity.ResponseCodec.ContentType,
                             null,
                             e => Log.ErrorException(e, "Error while writing http response (info)"));
 }
    public SerializedResultArrayV1(List<Result> x, UriTemplateMatch templateMatch, Uri Prefix, UriTemplate ResultResourceTemplate, UriTemplate ResourceArrayTemplate)
    {
        Pagination = createPagination(x.Count,templateMatch, Prefix, ResourceArrayTemplate);

        List<SerializedResultArrayEntry> r = new List<SerializedResultArrayEntry>();
        foreach (Result result in x)
        {
            r.Add(new SerializedResultArrayEntry(result, Prefix, ResultResourceTemplate));
        }
        Results = filterResults(r);
        ReferenceURI = ResourceArrayTemplate.BindByPosition(Prefix,templateMatch.BoundVariables["id"]);
    }
Ejemplo n.º 21
0
        private void OnGetFreshStats(HttpEntity entity, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope(
                    entity,
                    Format.GetFreshStatsCompleted,
                    Configure.GetFreshStatsCompleted);

            var statPath = match.BoundVariables["statPath"];
            var statSelector = GetStatSelector(statPath);

            Publish(new MonitoringMessage.GetFreshStats(envelope, statSelector));
        }
 private static ClientMessages.NakAction GetNackAction(HttpEntityManager manager, UriTemplateMatch match, NakAction nakAction = NakAction.Unknown)
 {
     var rawValue = match.BoundVariables["action"] ?? string.Empty;
     switch (rawValue.ToLowerInvariant())
     {
         case "park": return ClientMessages.NakAction.Park;
         case "retry": return ClientMessages.NakAction.Retry;
         case "skip": return ClientMessages.NakAction.Skip;
         case "stop": return ClientMessages.NakAction.Stop;
         default: return ClientMessages.NakAction.Unknown;
     }
 }
Ejemplo n.º 23
0
 private void OnPostScavenge(HttpEntityManager entity, UriTemplateMatch match)
 {
     if (entity.User != null && entity.User.IsInRole(SystemRoles.Admins))
     {
         Log.Info("Request scavenging because /admin/scavenge request has been received.");
         Publish(new ClientMessage.ScavengeDatabase(new NoopEnvelope(), Guid.Empty, entity.User));
         entity.ReplyStatus(HttpStatusCode.OK, "OK", LogReplyError);
     }
     else
     {
         entity.ReplyStatus(HttpStatusCode.Unauthorized, "Unauthorized", LogReplyError);
     }
 }
Ejemplo n.º 24
0
 private void OnPostShutdown(HttpEntityManager entity, UriTemplateMatch match)
 {
     if (entity.User != null && entity.User.IsInRole(SystemRoles.Admins))
     {
         Log.Info("Request shut down of node because shutdown command has been received.");
         Publish(new ClientMessage.RequestShutdown(exitProcess: true));
         entity.ReplyStatus(HttpStatusCode.OK, "OK", LogReplyError);
     }
     else
     {
         entity.ReplyStatus(HttpStatusCode.Unauthorized, "Unauthorized", LogReplyError);
     }
 }
Ejemplo n.º 25
0
        private void TestEncodingHandler(HttpEntityManager http, UriTemplateMatch match, string a)
        {
            var b = match.BoundVariables["b"];

            http.Reply(
                new
                    {
                        a = a,
                        b = b,
                        rawSegment = http.RequestedUrl.Segments[1],
                        requestUri = match.RequestUri,
                        rawUrl = http.HttpEntity.Request.RawUrl
                    }.ToJson(), 200, "OK", "application/json");
        }
Ejemplo n.º 26
0
        private static void InvokeDelegate(UriTemplateMatch results)
        {
            if (results == null)
            {
                Console.WriteLine("No Match");
            }
            else
            {
                Handler handler = (Handler)(results.Data);
                handler(results);
            }

            Console.WriteLine("");
        }
Ejemplo n.º 27
0
        private Func<ParameterInfo, object> CreateParameterBinder(UriTemplateMatch match)
        {
            QueryStringConverter converter = new QueryStringConverter();

            return delegate( ParameterInfo pi )
            {
                string value = match.BoundVariables[pi.Name];

                if (converter.CanConvert(pi.ParameterType) && value != null)
                    return converter.ConvertStringToValue(value, pi.ParameterType);
                else

                return value;
            };
        }
Ejemplo n.º 28
0
        void SetItems(IDictionary<string, object> items, UriTemplateMatch requestTemplateMatch)
        {
            items["owin.base_path"] = requestTemplateMatch.BaseUri;
            items["owin.server_name"] = requestTemplateMatch.RequestUri.Host;
            items["owin.server_port"] = requestTemplateMatch.RequestUri.Port;
            items["owin.request_protocol"] = "HTTP/1.1";
            items["owin.url_scheme"] = requestTemplateMatch.RequestUri.Scheme;

            OperationContext context = OperationContext.Current;

            var prop = context.IncomingMessageProperties;
            var endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            var ip = new IPEndPoint(IPAddress.Parse(endpoint.Address), requestTemplateMatch.RequestUri.Port);
            items["owin.remote_endpont"] = ip;
        }
Ejemplo n.º 29
0
        public Stream Handle(UriTemplateMatch match, HttpListenerContext listener)
        {
            var args = new string[TotalParams];
            for (int i = 0; i < match.BoundVariables.Count; i++)
                args[UppercaseArgumentOrder[match.BoundVariables.GetKey(i)]] = match.BoundVariables[i];

            // Fixes bug in Mono's TemplateMatch
            #if MONO
            var last = match.BoundVariables.Count - 1;
            if (last >= 0 && args[last].Length > 0 && args[last][0] == '/')
                args[last] = args[last].Substring(1);
            #endif

            return Invocation(args, listener.Request.InputStream);
        }
Ejemplo n.º 30
0
 internal UriTemplateMatch CreateTemplateMatch()
 {
     var result = new UriTemplateMatch();
     var bv = result.BoundVariables;
     foreach (var kv in BoundVars)
         bv.Add(kv.Key, kv.Value);
     var rs = result.RelativePathSegments;
     int pos = RawUrl.IndexOf('?');
     var maxLen = pos != -1 ? pos : RawUrl.Length;
     var nextSeg = RawUrl.IndexOf('/', 1) + 1;
     while (nextSeg != 0)
     {
         var lastSeg = nextSeg;
         nextSeg = RawUrl.IndexOf('/', nextSeg) + 1;
         if (nextSeg != 0)
             rs.Add(RawUrl.Substring(lastSeg, nextSeg - lastSeg - 1));
         else
             rs.Add(RawUrl.Substring(lastSeg, maxLen - lastSeg));
     }
     var qp = result.QueryParameters;
     if (QueryParams != null)
     {
         foreach (var kv in QueryParams)
             qp.Add(kv.Key, kv.Value);
         return result;
     }
     if (pos != -1)
     {
         var query = RawUrl;
         pos++;
         while (pos < query.Length)
         {
             int start = pos;
             while (pos < query.Length && query[pos] != '=') pos++;
             var key = HttpUtility.UrlDecode(query.Substring(start, pos - start));
             pos++;
             start = pos;
             while (pos < query.Length && query[pos] != '&') pos++;
             var value = HttpUtility.UrlDecode(query.Substring(start, pos - start));
             pos++;
             qp.Add(key, value);
         }
     }
     return result;
 }
Ejemplo n.º 31
0
        public UriTemplateMatch Match(Uri baseAddress, Uri candidate)
        {
            CheckBaseAddress(baseAddress);
            if (candidate == null)
            {
                throw new ArgumentNullException("candidate");
            }

            var us = baseAddress.LocalPath;

            if (us [us.Length - 1] != '/')
            {
                baseAddress = new Uri(
                    baseAddress.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + baseAddress.Query,
                    baseAddress.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
                    );
            }
            if (IgnoreTrailingSlash)
            {
                us = candidate.LocalPath;
                if (us.Length > 0 && us [us.Length - 1] != '/')
                {
                    candidate = new Uri(
                        candidate.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + candidate.Query,
                        candidate.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
                        );
                }
            }

            int i = 0, c = 0;
            UriTemplateMatch m = new UriTemplateMatch();

            m.BaseUri    = baseAddress;
            m.Template   = this;
            m.RequestUri = candidate;
            var vc             = m.BoundVariables;

            string cp = baseAddress.MakeRelativeUri(new Uri(
                                                        baseAddress,
                                                        candidate.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped)
                                                        ))
                        .ToString();

            if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
            {
                cp = cp.Substring(0, cp.Length - 1);
            }

            int tEndCp = cp.IndexOf('?');

            if (tEndCp >= 0)
            {
                cp = cp.Substring(0, tEndCp);
            }

            if (template.Length > 0 && template [0] == '/')
            {
                i++;
            }
            if (cp.Length > 0 && cp [0] == '/')
            {
                c++;
            }

            foreach (string name in path)
            {
                if (name == wild_path_name)
                {
                    vc [name] = Uri.UnescapeDataString(cp.Substring(c));                       // all remaining paths.
                    continue;
                }
                int n = StringIndexOf(template, '{' + name + '}', i);
                if (String.CompareOrdinal(cp, c, template, i, n - i) != 0)
                {
                    return(null);                    // doesn't match before current template part.
                }
                c += n - i;
                i  = n + 2 + name.Length;
                int ce = cp.IndexOf('/', c);
                if (ce < 0)
                {
                    ce = cp.Length;
                }
                string value          = cp.Substring(c, ce - c);
                string unescapedVaule = Uri.UnescapeDataString(value);
                if (value.Length == 0)
                {
                    return(null);                    // empty => mismatch
                }
                vc [name] = unescapedVaule;
                m.RelativePathSegments.Add(unescapedVaule);
                c += value.Length;
            }
            int  tEnd    = template.IndexOf('?');
            int  wildIdx = template.IndexOf('*');
            bool wild    = wildIdx >= 0;

            if (tEnd < 0)
            {
                tEnd = template.Length;
            }
            if (wild)
            {
                tEnd = Math.Max(wildIdx - 1, 0);
            }
            if (!wild && (cp.Length - c) != (tEnd - i) ||
                String.CompareOrdinal(cp, c, template, i, tEnd - i) != 0)
            {
                return(null);                // suffix doesn't match
            }
            if (wild)
            {
                c += tEnd - i;
                foreach (var pe in cp.Substring(c).Split(slashSep, StringSplitOptions.RemoveEmptyEntries))
                {
                    m.WildcardPathSegments.Add(pe);
                }
            }
            if (candidate.Query.Length == 0)
            {
                return(m);
            }


            string [] parameters = Uri.UnescapeDataString(candidate.Query.Substring(1)).Split('&');                // chop first '?'
            foreach (string parameter in parameters)
            {
                string [] pair = parameter.Split('=');
                if (pair.Length > 0)
                {
                    m.QueryParameters.Add(pair [0], pair.Length == 2 ? pair [1] : null);
                    if (!query_params.ContainsKey(pair [0]))
                    {
                        continue;
                    }
                    if (pair.Length > 1)
                    {
                        string templateName = query_params [pair [0]];
                        vc.Add(templateName, pair [1]);
                    }
                }
            }

            return(m);
        }
        public Collection <UriTemplateMatch> Match(Uri uri)
        {
            Collection <string> collection;
            IList <UriTemplateTableMatchCandidate> list;

            if (uri == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri");
            }
            if (!uri.IsAbsoluteUri)
            {
                return(None());
            }
            this.MakeReadOnly(true);
            if (!this.FastComputeRelativeSegmentsAndLookup(uri, out collection, out list))
            {
                return(None());
            }
            NameValueCollection query = null;

            if (!this.noTemplateHasQueryPart && AtLeastOneCandidateHasQueryPart(list))
            {
                Collection <UriTemplateTableMatchCandidate> collection2 = new Collection <UriTemplateTableMatchCandidate>();
                query = UriTemplateHelpers.ParseQueryString(uri.Query);
                bool mustBeEspeciallyInteresting = NoCandidateHasQueryLiteralRequirementsAndThereIsAnEmptyFallback(list);
                for (int j = 0; j < list.Count; j++)
                {
                    UriTemplateTableMatchCandidate candidate3 = list[j];
                    if (UriTemplateHelpers.CanMatchQueryInterestingly(candidate3.Template, query, mustBeEspeciallyInteresting))
                    {
                        collection2.Add(list[j]);
                    }
                }
                int count = collection2.Count;
                if (collection2.Count == 0)
                {
                    for (int k = 0; k < list.Count; k++)
                    {
                        UriTemplateTableMatchCandidate candidate4 = list[k];
                        if (UriTemplateHelpers.CanMatchQueryTrivially(candidate4.Template))
                        {
                            collection2.Add(list[k]);
                        }
                    }
                }
                if (collection2.Count == 0)
                {
                    return(None());
                }
                int num6 = collection2.Count;
                list = collection2;
            }
            if (NotAllCandidatesArePathFullyEquivalent(list))
            {
                Collection <UriTemplateTableMatchCandidate> collection3 = new Collection <UriTemplateTableMatchCandidate>();
                int num3 = -1;
                for (int m = 0; m < list.Count; m++)
                {
                    UriTemplateTableMatchCandidate item = list[m];
                    if (num3 == -1)
                    {
                        num3 = item.Template.segments.Count;
                        collection3.Add(item);
                    }
                    else if (item.Template.segments.Count < num3)
                    {
                        num3 = item.Template.segments.Count;
                        collection3.Clear();
                        collection3.Add(item);
                    }
                    else if (item.Template.segments.Count == num3)
                    {
                        collection3.Add(item);
                    }
                }
                list = collection3;
            }
            Collection <UriTemplateMatch> collection4 = new Collection <UriTemplateMatch>();

            for (int i = 0; i < list.Count; i++)
            {
                UriTemplateTableMatchCandidate candidate2 = list[i];
                UriTemplateMatch match = candidate2.Template.CreateUriTemplateMatch(this.originalUncanonicalizedBaseAddress, uri, candidate2.Data, candidate2.SegmentsCount, collection, query);
                collection4.Add(match);
            }
            return(collection4);
        }