Esempio n. 1
0
        public static DcmAssociateProfile Find(DcmAssociate associate, bool matchImplentation)
        {
            List <DcmAssociateProfile> candidates = new List <DcmAssociateProfile>();

            foreach (DcmAssociateProfile profile in Profiles)
            {
                if (!Wildcard.Match(profile.CalledAE, associate.CalledAE) || !Wildcard.Match(profile.CallingAE, associate.CallingAE))
                {
                    continue;
                }
                if (matchImplentation &&
                    (!Wildcard.Match(profile.RemoteImplUID, associate.ImplementationClass.UID) ||
                     !Wildcard.Match(profile.RemoteVersion, associate.ImplementationVersion)))
                {
                    continue;
                }
                candidates.Add(profile);
            }
            if (candidates.Count > 0)
            {
                candidates.Sort(delegate(DcmAssociateProfile p1, DcmAssociateProfile p2) {
                    return(p1.GetWeight(matchImplentation) - p2.GetWeight(matchImplentation));
                });
                return(candidates[0]);
            }
            return(GenericStorage);
        }
Esempio n. 2
0
        private static bool IsCurrentClient(ClaimsPrincipal principal, string clientRange)
        {
            if (String.IsNullOrWhiteSpace(clientRange))
            {
                return(true);
            }

            var currentClient = principal.Claims.FirstOrDefault(c => c.Type == "client_id")?.Value;

            if (String.IsNullOrWhiteSpace(currentClient))
            {
                return(false);
            }

            var clients = Regex.Split(clientRange, @"[,|;]").Select(c => c.Trim());

            foreach (var client in clients)
            {
                if (String.IsNullOrWhiteSpace(client))
                {
                    return(true);
                }

                if (Wildcard.Match(currentClient, client, true))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 3
0
        private MiddlerRuleMatch CheckMatch(IMiddlerOptions middlerOptions, MiddlerRule rule, MiddlerContext middlerContext)
        {
            var allowedHttpMethods = (rule.HttpMethods?.IgnoreNullOrWhiteSpace().Any() == true ? rule.HttpMethods.IgnoreNullOrWhiteSpace() : middlerOptions.DefaultHttpMethods).ToList();

            if (allowedHttpMethods.Any() && !allowedHttpMethods.Contains(middlerContext.Request.HttpMethod, StringComparer.OrdinalIgnoreCase))
            {
                return(null);
            }

            //var uri = new Uri(context.Request.GetEncodedUrl());

            var allowedSchemes = (rule.Scheme?.IgnoreNullOrWhiteSpace().Any() == true ? rule.Scheme.IgnoreNullOrWhiteSpace() : middlerOptions.DefaultScheme).ToList();

            if (allowedSchemes.Any() && !allowedSchemes.Any(scheme => Wildcard.Match(middlerContext.MiddlerRequestContext.Uri.Scheme, scheme)))
            {
                return(null);
            }

            if (!Wildcard.Match($"{middlerContext.MiddlerRequestContext.Uri.Host}:{middlerContext.MiddlerRequestContext.Uri.Port}", rule.Hostname ?? "*"))
            {
                return(null);
            }

            if (String.IsNullOrWhiteSpace(rule.Path))
            {
                rule.Path = "{**path}";
            }

            var parsedTemplate = TemplateParser.Parse(rule.Path);

            var defaults = parsedTemplate.Parameters.Where(p => p.DefaultValue != null)
                           .Aggregate(new RouteValueDictionary(), (current, next) =>
            {
                current.Add(next.Name, next.DefaultValue);
                return(current);
            });

            var matcher = new TemplateMatcher(parsedTemplate, defaults);
            var rd      = middlerContext.MiddlerRequestContext.GetRouteData();
            var router  = rd.Routers.FirstOrDefault() ?? new RouteCollection();

            if (matcher.TryMatch(middlerContext.MiddlerRequestContext.Uri.AbsolutePath, rd.Values))
            {
                var constraints = GetConstraints(middlerContext.RequestServices.GetRequiredService <IInlineConstraintResolver>(), parsedTemplate, null);
                if (MiddlerRouteConstraintMatcher.Match(constraints, rd.Values, router, RouteDirection.IncomingRequest, ConstraintLogger))
                {
                    middlerContext.SetRouteData(constraints);

                    return(new MiddlerRuleMatch
                    {
                        MiddlerRule = rule,
                        AccessMode = rule.AccessAllowed(middlerContext.Request) ?? middlerOptions.DefaultAccessMode
                    });
                }
            }

            return(null);
        }
Esempio n. 4
0
 public bool Match(DcmDataset dataset)
 {
     if (dataset.Contains(_tag))
     {
         string value = dataset.GetValueString(_tag);
         return(Wildcard.Match(_pattern, value));
     }
     return(false);
 }
Esempio n. 5
0
        public void Wildcard010Test()
        {
            Assert.AreEqual(true, Wildcard.Match("Hello*", "Hello"));
            Assert.AreEqual(true, Wildcard.Match("Hello.*", "Hello"));
            Assert.AreEqual(true, Wildcard.Match("Hello.*", "Hello."));
            Assert.AreEqual(false, Wildcard.Match("Hello.Abc.*", "Hello."));

            Assert.AreEqual(true, Wildcard.Match("Hello.*", "Hello.Abc"));
            Assert.AreEqual(false, Wildcard.Match("Hello.*.Abc", "Hello.Abc"));
            Assert.AreEqual(true, Wildcard.Match("Hello.*.Abc", "Hello.Def.Abc"));
            Assert.AreEqual(true, Wildcard.Match("Hello.*.Abc", "Hello..Abc"));
            Assert.AreEqual(false, Wildcard.Match("Hello.*.Abc", "Hello..Abcdefh"));
            Assert.AreEqual(true, Wildcard.Match("Hello.*.Abc", "Hello.12345.Abc"));
        }
Esempio n. 6
0
        private IConfigSection GetLoggerConfig(Logger logger)
        {
            IConfigSection loggerSection = null;

            if (_config != null)
            {
                var loggerSections = _config.GetSections("loggers/logger")
                                     .Select(m => new { Section = m, Name = m.Get("@name") })
                                     .ToArray();

                loggerSection = loggerSections
                                .Where(m => Wildcard.Match(m.Name, logger.Name, ignoreCase: true))
                                .Select(m => m.Section).FirstOrDefault();
            }
            return(loggerSection);
        }
Esempio n. 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="processor"></param>
        /// <param name="fileName"></param>
        void BuildAsset(AssetProcessor processor, string[] args, AssetSource assetFile, ref BuildResult buildResult)
        {
            try {
                //	Is up-to-date?
                if (!context.Options.ForceRebuild)
                {
                    if (!Wildcard.Match(assetFile.KeyPath, context.Options.CleanPattern, true))
                    {
                        if (!context.Options.Files.Contains(assetFile.KeyPath))
                        {
                            if (assetFile.IsUpToDate)
                            {
                                buildResult.UpToDate++;
                                return;
                            }
                        }
                    }
                }


                var keyPath = assetFile.KeyPath;

                if (keyPath.Length > 40)
                {
                    keyPath = "..." + keyPath.Substring(keyPath.Length - 40 + 3);
                }

                Log.Message("{0,-40} {1,-5}   {3}", keyPath, Path.GetExtension(keyPath), string.Join(" ", args), assetFile.Hash);

                // Apply attribute :
                var parser = new CommandLineParser(processor.GetType());
                parser.OptionLeadingChar = '/';

                parser.ParseCommandLine(processor, args);

                //
                //	Build :
                //
                processor.Process(assetFile, context);

                buildResult.Succeded++;
            } catch (Exception e) {
                Log.Error("{0} : {1}", assetFile.KeyPath, e.Message);
                buildResult.Failed++;
            }
        }
Esempio n. 8
0
        private void PerformQuery()
        {
            lbElements.SuspendLayout();
            lbElements.Items.Clear();

            string NameQuery = tbSearch.Text + "*";
            string TagQuery  = tbSearch.Text.Replace(",", "").ToLower().PadRight(8, 'x');

            uint TagCard = 0, TagMask = 0;
            bool CheckTag = uint.TryParse(TagQuery.Replace('x', '0'), System.Globalization.NumberStyles.HexNumber, null, out TagCard);

            if (CheckTag)
            {
                StringBuilder msb = new StringBuilder();
                msb.Append(TagQuery.ToLower());
                msb.Replace('0', 'F').Replace('1', 'F').Replace('2', 'F')
                .Replace('3', 'F').Replace('4', 'F').Replace('5', 'F')
                .Replace('6', 'F').Replace('7', 'F').Replace('8', 'F')
                .Replace('9', 'F').Replace('a', 'F').Replace('b', 'F')
                .Replace('c', 'F').Replace('d', 'F').Replace('e', 'F')
                .Replace('f', 'F').Replace('x', '0');
                CheckTag = uint.TryParse(msb.ToString(), System.Globalization.NumberStyles.HexNumber, null, out TagMask);
            }

            foreach (DcmDictionaryEntry entry in DcmDictionary.Entries)
            {
                if (CheckTag)
                {
                    if ((entry.Tag & TagMask) == (TagCard & entry.Mask))
                    {
                        lbElements.Items.Add(entry);
                    }
                }
                else if (Wildcard.Match(NameQuery, entry.Name, false))
                {
                    lbElements.Items.Add(entry);
                }
            }
            if (lbElements.Items.Count > 0)
            {
                lbElements.SelectedIndex = 0;
            }
            lbElements.ResumeLayout();
        }
Esempio n. 9
0
        private static bool SourceIpAddressIsInRange(this IPAddress sourceIp, string range)
        {
            if (String.IsNullOrWhiteSpace(range))
            {
                range = "*";
            }

            try {
                var ips = Regex.Split(range, @"[,|;]");

                foreach (var ip in ips)
                {
                    if (ip.Contains("*") || ip.Contains("?"))
                    {
                        if (Wildcard.Match(sourceIp.ToString(), ip))
                        {
                            return(true);
                        }
                    }

                    if (ip.Contains("/") || ip.Contains("-"))
                    {
                        var net = IPAddressRange.Parse(ip);
                        if (net.Contains(sourceIp))
                        {
                            return(true);
                        }
                    }
                    else
                    {
                        if (IPAddress.Parse(ip).Equals(sourceIp))
                        {
                            return(true);
                        }
                    }
                }

                return(false);
            } catch (Exception e) {
                return(false);
            }
        }
Esempio n. 10
0
        public static AccessMode?AccessAllowed(this IEnumerable <MiddlerRulePermission> permissionRules, IMiddlerRequestContext middlerRequestContext)
        {
            var roles = middlerRequestContext.Principal.Claims.Where(c => c.Type.Equals("role", StringComparison.OrdinalIgnoreCase))
                        .Select(c => c.Value)
                        .ToList();

            var hasUser = !String.IsNullOrWhiteSpace(middlerRequestContext.Principal.Identity.Name);

            foreach (var permissionRule in permissionRules)
            {
                var inRange  = SourceIpAddressIsInRange(middlerRequestContext.SourceIPAddress, permissionRule.SourceAddress);
                var isClient = IsCurrentClient(middlerRequestContext.Principal, permissionRule.Client);


                switch (permissionRule.Type)
                {
                case PrincipalType.Everyone: {
                    if (inRange && isClient)
                    {
                        return(permissionRule.AccessMode);
                    }

                    break;
                }

                case PrincipalType.Authenticated: {
                    if (inRange && isClient && hasUser)
                    {
                        return(permissionRule.AccessMode);
                    }

                    break;
                }

                case PrincipalType.User: {
                    if (inRange && isClient && Wildcard.Match(middlerRequestContext.Principal.Identity.Name, permissionRule.PrincipalName.ToNull() ?? ""))
                    {
                        return(permissionRule.AccessMode);
                    }

                    break;
                }

                case PrincipalType.Role: {
                    if (isClient && inRange)
                    {
                        foreach (var role in roles)
                        {
                            if (Wildcard.Match(role, permissionRule.PrincipalName.ToNull() ?? ""))
                            {
                                return(permissionRule.AccessMode);
                            }
                        }
                    }

                    break;
                }
                }
            }

            return(null);
        }
Esempio n. 11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sourceFolder"></param>
        /// <returns></returns>
        List <AssetSource> GatherAssetFiles(string[] ignorePatterns, IniData iniData, BuildContext context, ref BuildResult result)
        {
            var assetSources = new List <AssetSource>();

            //	key contain key path
            //	value containt full path
            var files = new List <LocalFile>();

            //	gather files from all directories
            //	and then distinct them by key path.
            foreach (var contentDir in context.ContentDirectories)
            {
                var localFiles = Directory.EnumerateFiles(contentDir, "*", SearchOption.AllDirectories)
                                 .Where(f1 => Path.GetFileName(f1).ToLowerInvariant() != ".content");

                files.AddRange(localFiles.Select(fullpath => new LocalFile(contentDir, fullpath)));
            }

            files        = files.DistinctBy(file => file.KeyPath).ToList();
            result.Total = files.Count;


            //	ignore files by ignore pattern
            //	and count ignored files :
            result.Ignored = files.RemoveAll(file => {
                foreach (var pattern in ignorePatterns)
                {
                    if (Wildcard.Match(file.KeyPath, pattern))
                    {
                        return(true);
                    }
                }
                return(false);
            });



            foreach (var section in iniData.Sections)
            {
                //	'Ingore' is a special section.
                if (section.SectionName == "Ignore")
                {
                    continue;
                }
                if (section.SectionName == "ContentDirectories")
                {
                    continue;
                }
                if (section.SectionName == "BinaryDirectories")
                {
                    continue;
                }
                if (section.SectionName == "Download")
                {
                    continue;
                }

                //	get processor :
                if (!processors.ContainsKey(section.SectionName))
                {
                    Log.Warning("Asset processor '{0}' not found. Files will be skipped.", section.SectionName);
                    Log.Message("");
                    continue;
                }

                var procBind = processors[section.SectionName];

                //	get mask and arguments :
                var maskArgs = section.Keys
                               .Reverse()
                               .Select(key => new {
                    Mask = key.KeyName.Split(' ', '\t').FirstOrDefault(),
                    Args = CommandLineParser.SplitCommandLine(key.KeyName).Skip(1).ToArray()
                })
                               .ToList();


                foreach (var file in files)
                {
                    if (file.Handled)
                    {
                        continue;
                    }

                    foreach (var maskArg in maskArgs)
                    {
                        if (Wildcard.Match(file.KeyPath, maskArg.Mask, true))
                        {
                            file.Handled = true;
                            assetSources.Add(new AssetSource(file.KeyPath, file.BaseDir, procBind.Type, maskArg.Args, context));
                            break;
                        }
                    }
                }

                //	count unhandled files :
                result.Skipped = files.Count(f => !f.Handled);
            }


            return(assetSources);
        }