コード例 #1
0
 private static void SetRule(Rule rule, dynamic model)
 {
     DynamicHelper.If <RuleAccessType>((object)model.access_type, v => rule.AccessType = v);
     DynamicHelper.If((object)model.users, v => rule.Users = v);
     DynamicHelper.If((object)model.roles, v => rule.Roles = v);
     DynamicHelper.If((object)model.verbs, v => rule.Verbs = v);
 }
コード例 #2
0
        public static void UpdateFeatureSettings(dynamic model, AuthorizationSection section)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }
            if (section == null)
            {
                throw new ArgumentNullException("section");
            }

            try {
                DynamicHelper.If <bool>((object)model.bypass_login_pages, v => section.BypassLoginPages = v);


                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => section.OverrideMode = v);
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #3
0
        public static void UpdateSection(dynamic model, Site site, string path, string configPath = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            InboundRulesSection section = GetSection(site, path, configPath);

            try {
                // UseOriginalURLEncoding introduced in 2.1
                if (section.Schema.HasAttribute(InboundRulesSection.UseOriginalUrlEncodingAttribute))
                {
                    DynamicHelper.If <bool>((object)model.use_original_url_encoding, v => section.UseOriginalURLEncoding = v);
                }

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => {
                        section.OverrideMode = v;
                    });
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #4
0
        public static void UpdateSettings(dynamic model, IFileProvider fileProvider, Site site, string path, string configPath = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            // Only editable at site level
            if (site != null && path == "/")
            {
                DynamicHelper.If((object)model.directory, v => {
                    v            = v.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                    var expanded = System.Environment.ExpandEnvironmentVariables(v);

                    if (!PathUtil.IsFullPath(expanded))
                    {
                        throw new ApiArgumentException("directory");
                    }
                    if (!fileProvider.IsAccessAllowed(expanded, FileAccess.Read))
                    {
                        throw new ForbiddenArgumentException("directory", expanded);
                    }

                    site.TraceFailedRequestsLogging.Directory = v;
                });

                DynamicHelper.If <bool>((object)model.enabled, v => site.TraceFailedRequestsLogging.Enabled = v);
                DynamicHelper.If((object)model.maximum_number_trace_files, 1, 10000, v => site.TraceFailedRequestsLogging.MaxLogFiles = v);
            }
        }
コード例 #5
0
        public static void UpdateSettings(dynamic model, Site site, string path, string configPath = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            var section = GetSection(site, path, configPath);

            try {
                DynamicHelper.If <bool>((object)model.enabled, v => section.Enabled = v);
                DynamicHelper.If((object)model.default_logon_domain, v => section.DefaultLogonDomain = v);
                DynamicHelper.If((object)model.realm, v => section.Realm = v);

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => {
                        section.OverrideMode = v;
                    });
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #6
0
        public static void UpdateFeatureSettings(dynamic model, HttpProtocolSection section)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }
            if (section == null)
            {
                throw new ArgumentNullException("section");
            }

            try {
                DynamicHelper.If <bool>((object)model.allow_keep_alive, v => section.AllowKeepAlive = v);

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => section.OverrideMode = v);
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #7
0
        public static void UpdateSettings(dynamic model, Site site, string path, string configPath = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            var section    = GetHttpCompressionSection(site, path, configPath);
            var urlSection = GetUrlCompressionSection(site, path);

            try {
                DynamicHelper.If((object)model.directory, v => section.Directory = v);
                DynamicHelper.If <bool>((object)model.do_disk_space_limitting, v => section.DoDiskSpaceLimiting       = v);
                DynamicHelper.If((object)model.max_disk_space_usage, 0, uint.MaxValue, v => section.MaxDiskSpaceUsage = v);
                DynamicHelper.If((object)model.min_file_size, 0, uint.MaxValue, v => section.MinFileSizeForComp       = v);
                DynamicHelper.If <bool>((object)model.do_dynamic_compression, v => urlSection.DoDynamicCompression    = v);
                DynamicHelper.If <bool>((object)model.do_static_compression, v => urlSection.DoStaticCompression      = v);

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => {
                        section.OverrideMode    = v;
                        urlSection.OverrideMode = v;
                    });
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #8
0
        public static void UpdateSection(dynamic model, Site site, string path, string configPath = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            OutboundRulesSection section = GetSection(site, path, configPath);

            try {
                DynamicHelper.If <bool>((object)model.rewrite_before_cache, v => section.RewriteBeforeCache = v);

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => {
                        section.OverrideMode = v;
                    });
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #9
0
        public static void UpdateFeatureSettings(dynamic model, Site site, string path, string configPath = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            AllowedServerVariablesSection section = ServerVariablesHelper.GetSection(site, path, configPath);

            try {
                if (model.entries != null)
                {
                    IEnumerable <dynamic> variables = model.entries as IEnumerable <dynamic>;

                    if (variables == null)
                    {
                        throw new ApiArgumentException("entries", ForbiddenArgumentException.EXPECTED_ARRAY);
                    }

                    List <string> variableList = new List <string>();

                    // Validate all verbs provided
                    foreach (dynamic variable in variables)
                    {
                        string var = DynamicHelper.Value(variable);

                        if (string.IsNullOrEmpty(var))
                        {
                            throw new ApiArgumentException("entries.item");
                        }

                        variableList.Add(var);
                    }

                    // Clear configuration's collection
                    section.AllowedServerVariables.Clear();

                    // Move from temp list to the configuration's collection
                    variableList.ForEach(v => section.AllowedServerVariables.Add(v));
                }


                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => {
                        section.OverrideMode = v;
                    });
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #10
0
        private static void SetApplication(Application app, dynamic model)
        {
            string path = DynamicHelper.Value(model.path);

            if (!string.IsNullOrEmpty(path))
            {
                // Make sure path starts with '/'
                if (path[0] != '/')
                {
                    path = '/' + path;
                }

                app.Path = path;
            }

            DynamicHelper.If((object)model.enabled_protocols, v => app.EnabledProtocols = v);

            string physicalPath = DynamicHelper.Value(model.physical_path);

            if (physicalPath != null)
            {
                if (!Directory.Exists(System.Environment.ExpandEnvironmentVariables(physicalPath)))
                {
                    throw new ApiArgumentException("physical_path", "Directory does not exist.");
                }

                var rootVDir = app.VirtualDirectories["/"];
                if (rootVDir == null)
                {
                    throw new ApiArgumentException("application/physical_path", "Root virtual directory does not exist.");
                }

                rootVDir.PhysicalPath = physicalPath.Replace('/', '\\');
            }

            if (model.application_pool != null)
            {
                // Change application pool
                if (model.application_pool.id == null)
                {
                    throw new ApiArgumentException("application_pool.id");
                }

                string          poolName = AppPools.AppPoolId.CreateFromUuid(DynamicHelper.Value(model.application_pool.id)).Name;
                ApplicationPool pool     = AppPoolHelper.GetAppPool(poolName);

                if (pool != null)
                {
                    app.ApplicationPoolName = pool.Name;
                }
            }
        }
コード例 #11
0
        public static void UpdateSettings(dynamic model, Site site, string path, string configPath = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            // Only editable at site level
            if (site != null && path == "/")
            {
                DynamicHelper.If((object)model.directory, v => site.TraceFailedRequestsLogging.Directory    = v);
                DynamicHelper.If <bool>((object)model.enabled, v => site.TraceFailedRequestsLogging.Enabled = v);
                DynamicHelper.If((object)model.maximum_number_trace_files, 1, 10000, v => site.TraceFailedRequestsLogging.MaxLogFiles = v);
            }
        }
コード例 #12
0
        private static void UpdatePriority(dynamic model, InboundRule rule, InboundRulesSection section)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            DynamicHelper.If((object)model.priority, 0, int.MaxValue, v => {
                v = v >= section.InboundRules.Count ? section.InboundRules.Count - 1 : v;
                if (section.InboundRules.IndexOf(rule) != -1)
                {
                    section.InboundRules.Move(rule, (int)v);
                }
            });
        }
コード例 #13
0
        public static void UpdateSettings(dynamic model, IFileProvider fileProvider, Site site, string path, string configPath = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            var section    = GetHttpCompressionSection(site, path, configPath);
            var urlSection = GetUrlCompressionSection(site, path);

            try {
                DynamicHelper.If((object)model.directory, v => {
                    v            = v.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                    var expanded = System.Environment.ExpandEnvironmentVariables(v);

                    if (!PathUtil.IsFullPath(expanded))
                    {
                        throw new ApiArgumentException("directory");
                    }
                    if (!fileProvider.IsAccessAllowed(expanded, FileAccess.Read))
                    {
                        throw new ForbiddenArgumentException("directory", expanded);
                    }

                    section.Directory = v;
                });

                DynamicHelper.If <bool>((object)model.do_disk_space_limitting, v => section.DoDiskSpaceLimiting       = v);
                DynamicHelper.If((object)model.max_disk_space_usage, 0, uint.MaxValue, v => section.MaxDiskSpaceUsage = v);
                DynamicHelper.If((object)model.min_file_size, 0, uint.MaxValue, v => section.MinFileSizeForComp       = v);
                DynamicHelper.If <bool>((object)model.do_dynamic_compression, v => urlSection.DoDynamicCompression    = v);
                DynamicHelper.If <bool>((object)model.do_static_compression, v => urlSection.DoStaticCompression      = v);

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => {
                        section.OverrideMode    = v;
                        urlSection.OverrideMode = v;
                    });
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #14
0
        public static Extension UpdateExtension(Extension extension, dynamic model)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }
            if (extension == null)
            {
                throw new ApiArgumentException("extension");
            }

            DynamicHelper.If((object)model.extension, ext => extension.FileExtension = ext.StartsWith(".") ? ext : "." + ext);
            extension.Allowed = DynamicHelper.To <bool>(model.allow) ?? extension.Allowed;

            return(extension);
        }
コード例 #15
0
        public static void UpdateFeatureSettings(dynamic model, DefaultDocumentSection section)
        {
            try {
                DynamicHelper.If <bool>((object)model.enabled, v => section.Enabled = v);

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => section.OverrideMode = v);
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #16
0
        public static void UpdateFeatureSettings(dynamic model, StaticContentSection section)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }
            if (section == null)
            {
                throw new ArgumentException("section");
            }

            if (model.client_cache != null)
            {
                dynamic cache = model.client_cache;

                DynamicHelper.If((object)cache.max_age, 0, (long)TimeSpan.MaxValue.TotalMinutes, v => section.ClientCache.CacheControlMaxAge = TimeSpan.FromMinutes(v));
                DynamicHelper.If((object)cache.control_mode, v => section.ClientCache.CacheControlMode     = JsonToCacheControlMode(v));
                DynamicHelper.If((object)cache.control_custom, v => section.ClientCache.CacheControlCustom = v);
                DynamicHelper.If <bool>((object)cache.set_e_tag, v => section.ClientCache.SetETag          = v);
                DynamicHelper.If((object)cache.http_expires, v => {
                    DateTime httpExpires;
                    if (!DateTime.TryParseExact(v, "r", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out httpExpires))
                    {
                        throw new ApiArgumentException("http_expires");
                    }

                    section.ClientCache.HttpExpires = httpExpires;
                });
            }

            DynamicHelper.If((object)model.default_doc_footer, v => section.DefaultDocFooter = v);
            DynamicHelper.If <bool>((object)model.is_doc_footer_file_name, v => {
                if (section.IsDocFooterFileName != v)
                {
                    section.IsDocFooterFileName = v;
                }
            });
            DynamicHelper.If <bool>((object)model.enable_doc_footer, v => section.EnableDocFooter = v);

            if (model.metadata != null)
            {
                DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => section.OverrideMode = v);
            }
        }
コード例 #17
0
        public object Patch(string id, [FromBody] dynamic model)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            // Decode default document id from uuid parameter
            DefaultDocumentId docId = new DefaultDocumentId(id);

            Site site = docId.SiteId == null ? null : SiteHelper.GetSite(docId.SiteId.Value);

            if (docId.SiteId != null && site == null)
            {
                // The document id specified a site but we couldn't find it,
                // therefore we can't get the settings for that site
                return(NotFound());
            }

            string configPath = model == null ? null : ManagementUnit.ResolveConfigScope(model);
            DefaultDocumentSection section = DefaultDocumentHelper.GetDefaultDocumentSection(site, docId.Path, configPath);

            try {
                // Handle patching of any feature settings
                DynamicHelper.If <bool>((object)model.enabled, v => section.Enabled = v);

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => section.OverrideMode = v);
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }

            ManagementUnit.Current.Commit();

            return(DefaultDocumentHelper.ToJsonModel(site, docId.Path));
        }
コード例 #18
0
        public object Patch(string id, [FromBody] dynamic model)
        {
            ModulesId modulesId = new ModulesId(id);

            Site site = modulesId.SiteId == null ? null : SiteHelper.GetSite(modulesId.SiteId.Value);

            if (modulesId.SiteId != null && site == null)
            {
                Context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(null);
            }

            ModuleHelper.EnsureValidScope(site, modulesId.Path);

            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            // Check for config_scope
            string         configPath = model == null ? null : ManagementUnit.ResolveConfigScope(model);
            ModulesSection section    = ModuleHelper.GetModulesSection(site, modulesId.Path, configPath);

            try {
                DynamicHelper.If <bool>((object)model.run_all_managed_modules_for_all_requests, v => section.RunAllManagedModulesForAllRequests = v);

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => section.OverrideMode = v);
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }

            ManagementUnit.Current.Commit();

            return(ModuleHelper.ModuleFeatureToJsonModel(site, modulesId.Path));
        }
コード例 #19
0
        private static void SetProvider(TraceProviderDefinition provider, dynamic model)
        {
            DynamicHelper.If((object)model.name, v => provider.Name = v);
            DynamicHelper.If((object)model.guid, v => {
                Guid guid;
                if (!Guid.TryParse(v, out guid))
                {
                    throw new ApiArgumentException("guid");
                }

                provider.Guid = guid;
            });

            if (model.areas != null)
            {
                if (!(model.areas is JArray))
                {
                    throw new ApiArgumentException("areas", ApiArgumentException.EXPECTED_ARRAY);
                }

                IEnumerable <dynamic> areas = model.areas;
                provider.Areas.Clear();
                long uniqueFlag = 1;

                foreach (var area in areas)
                {
                    string a = DynamicHelper.Value(area);

                    if (a == null)
                    {
                        throw new ApiArgumentException("areas");
                    }

                    var elem = provider.Areas.CreateElement();
                    elem.Name   = a;
                    elem.Value  = uniqueFlag;
                    uniqueFlag *= 2;
                    provider.Areas.Add(elem);
                }
            }
        }
コード例 #20
0
        public static void UpdateFeatureSettings(dynamic model, HttpRedirectSection section)
        {
            try {
                DynamicHelper.If <bool>((object)model.enabled, v => section.Enabled               = v);
                DynamicHelper.If <bool>((object)model.preserve_filename, v => section.ChildOnly   = v);
                DynamicHelper.If((object)model.destination, v => section.Destination              = v);
                DynamicHelper.If <bool>((object)model.absolute, v => section.ExactDestination     = v);
                DynamicHelper.If <int>((object)model.status_code, v => section.HttpResponseStatus = (RedirectHttpResponseStatus)v);

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => section.OverrideMode = v);
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #21
0
        private static void SetVirtualDirectory(VirtualDirectory vdir, dynamic model)
        {
            string path = DynamicHelper.Value(model.path);

            if (!string.IsNullOrEmpty(path))
            {
                // Make sure path starts with '/'
                if (path[0] != '/')
                {
                    path = '/' + path;
                }

                vdir.Path = path;
            }

            string physicalPath = DynamicHelper.Value(model.physical_path);

            if (physicalPath != null)
            {
                if (!Directory.Exists(System.Environment.ExpandEnvironmentVariables(physicalPath)))
                {
                    throw new ApiArgumentException("physical_path", "Directory does not exist.");
                }
                vdir.PhysicalPath = physicalPath.Replace('/', '\\');
            }

            if (model.identity != null)
            {
                var identity = model.identity;

                if (!(model.identity is JObject))
                {
                    throw new ApiArgumentException("model.identity", ApiArgumentException.EXPECTED_OBJECT);
                }

                DynamicHelper.If((object)identity.logon_method, v => vdir.LogonMethod = ToLogonMethod(v));
                vdir.Password = DynamicHelper.Value(identity.password) ?? vdir.Password;
                vdir.UserName = DynamicHelper.Value(identity.username) ?? vdir.UserName;
            }
        }
コード例 #22
0
        public static void UpdateSettings(dynamic model, Site site, string path, string configPath = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            var section = GetSection(site, path, configPath);

            try {
                DynamicHelper.If <bool>((object)model.enabled, v => section.Enabled = v);
                DynamicHelper.If((object)model.user, v => section.UserName          = v);
                DynamicHelper.If((object)model.password, v => section.Password      = v);

                string user = DynamicHelper.Value(model.user);

                // Empty username is for application pool identity
                bool deletePassword = (user != null) && (user.Equals(string.Empty) || user.Equals("iusr", StringComparison.OrdinalIgnoreCase));
                if (deletePassword)
                {
                    ConfigurationAttribute passwordAttr = section.GetAttribute("password");
                    passwordAttr.Delete();
                }

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => {
                        section.OverrideMode = v;
                    });
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #23
0
        private static Site SetSite(Site site, dynamic model, IFileProvider fileProvider)
        {
            Debug.Assert(site != null);
            Debug.Assert((bool)(model != null));

            //
            // Name
            DynamicHelper.If((object)model.name, v => { site.Name = v; });

            //
            // Server Auto Start
            site.ServerAutoStart = DynamicHelper.To <bool>(model.server_auto_start) ?? site.ServerAutoStart;


            //
            // Physical Path
            string physicalPath = DynamicHelper.Value(model.physical_path);

            if (physicalPath != null)
            {
                physicalPath = physicalPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                var expanded = System.Environment.ExpandEnvironmentVariables(physicalPath);

                if (!PathUtil.IsFullPath(expanded))
                {
                    throw new ApiArgumentException("physical_path");
                }
                if (!fileProvider.IsAccessAllowed(expanded, FileAccess.Read))
                {
                    throw new ForbiddenArgumentException("physical_path", physicalPath);
                }
                if (!Directory.Exists(expanded))
                {
                    throw new NotFoundException("physical_path");
                }

                var rootApp = site.Applications["/"];
                if (rootApp != null)
                {
                    var rootVDir = rootApp.VirtualDirectories["/"];

                    if (rootVDir != null)
                    {
                        rootVDir.PhysicalPath = physicalPath;
                    }
                }
            }

            //
            // Enabled Protocols
            string enabledProtocols = DynamicHelper.Value(model.enabled_protocols);

            if (enabledProtocols != null)
            {
                var rootApp = site.Applications["/"];

                if (rootApp != null)
                {
                    rootApp.EnabledProtocols = enabledProtocols;
                }
            }

            //
            // Limits
            if (model.limits != null)
            {
                dynamic limits = model.limits;

                site.Limits.MaxBandwidth   = DynamicHelper.To(limits.max_bandwidth, 0, uint.MaxValue) ?? site.Limits.MaxBandwidth;
                site.Limits.MaxConnections = DynamicHelper.To(limits.max_connections, 0, uint.MaxValue) ?? site.Limits.MaxConnections;

                if (site.Limits.Schema.HasAttribute(MaxUrlSegmentsAttribute))
                {
                    site.Limits.MaxUrlSegments = DynamicHelper.To(limits.max_url_segments, 0, 16383) ?? site.Limits.MaxUrlSegments;
                }

                long?connectionTimeout = DynamicHelper.To(limits.connection_timeout, 0, ushort.MaxValue);
                site.Limits.ConnectionTimeout = (connectionTimeout != null) ? TimeSpan.FromSeconds(connectionTimeout.Value) : site.Limits.ConnectionTimeout;
            }

            //
            // Bindings
            if (model.bindings != null)
            {
                IEnumerable <dynamic> bindings = (IEnumerable <dynamic>)model.bindings;

                // If the user passes an object for the bindings property rather than an array we will hit an exception when we try to access any property in
                // the foreach loop.
                // This means that the bindings collection won't be deleted, so the bindings are safe from harm.

                List <Binding> newBindings = new List <Binding>();

                // Iterate over the bindings to create a new binding list
                foreach (dynamic b in bindings)
                {
                    Binding binding = site.Bindings.CreateElement();
                    SetBinding(binding, b);

                    foreach (Binding addedBinding in newBindings)
                    {
                        if (addedBinding.Protocol.Equals(binding.Protocol, StringComparison.OrdinalIgnoreCase) &&
                            addedBinding.BindingInformation.Equals(binding.BindingInformation, StringComparison.OrdinalIgnoreCase))
                        {
                            throw new AlreadyExistsException("binding");
                        }
                    }

                    // Add to bindings list
                    newBindings.Add(binding);
                }

                // All bindings have been verified and added to the list
                // Clear the old list, and add the new
                site.Bindings.Clear();
                newBindings.ForEach(binding => site.Bindings.Add(binding));
            }

            //
            // App Pool
            if (model.application_pool != null)
            {
                // Extract the uuid from the application_pool object provided in model
                string appPoolUuid = DynamicHelper.Value(model.application_pool.id);

                // It is an error to provide an application pool object without specifying its id property
                if (appPoolUuid == null)
                {
                    throw new ApiArgumentException("application_pool.id");
                }

                // Create application pool id object from uuid provided, use this to obtain the application pool
                AppPoolId       appPoolId = AppPoolId.CreateFromUuid(appPoolUuid);
                ApplicationPool pool      = AppPoolHelper.GetAppPool(appPoolId.Name);

                Application rootApp = site.Applications["/"];

                if (rootApp == null)
                {
                    throw new ApiArgumentException("application_pool", "Root application does not exist.");
                }

                // REVIEW: Should we create the root application if it doesn't exist and they specify an application pool?
                // We decided not to do this for physical_path.
                // Application pool for a site is extracted from the site's root application
                rootApp.ApplicationPoolName = pool.Name;
            }

            return(site);
        }
コード例 #24
0
        private static void SetMap(dynamic model, RewriteMap map, RewriteMapsSection section)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            try {
                //
                // Name, check for already existing name
                string name = DynamicHelper.Value(model.name);
                if (!string.IsNullOrEmpty(name))
                {
                    if (!name.Equals(map.Name, StringComparison.OrdinalIgnoreCase) &&
                        section.RewriteMaps.Any(r => r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
                    {
                        throw new AlreadyExistsException("name");
                    }

                    map.Name = name;
                }

                DynamicHelper.If((object)model.default_value, v => map.DefaultValue    = v);
                DynamicHelper.If <bool>((object)model.ignore_case, v => map.IgnoreCase = v);

                //
                // mappings
                if (model.mappings != null)
                {
                    IEnumerable <dynamic> mappings = model.mappings as IEnumerable <dynamic>;

                    if (mappings == null)
                    {
                        throw new ApiArgumentException("mappings", ApiArgumentException.EXPECTED_ARRAY);
                    }

                    map.KeyValuePairCollection.Clear();

                    foreach (dynamic item in mappings)
                    {
                        if (!(item is JObject))
                        {
                            throw new ApiArgumentException("mappings.item");
                        }

                        string itemName = DynamicHelper.Value(item.name);
                        string value    = DynamicHelper.Value(item.value);

                        if (string.IsNullOrEmpty(itemName))
                        {
                            throw new ApiArgumentException("mappings.item.name", "Required");
                        }

                        if (string.IsNullOrEmpty(value))
                        {
                            throw new ApiArgumentException("mappings.item.value", "Required");
                        }

                        KeyValueElement kvp = map.KeyValuePairCollection.CreateElement();
                        kvp.Key   = itemName;
                        kvp.Value = value;

                        map.KeyValuePairCollection.Add(kvp);
                    }
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #25
0
        public static void UpdateFeatureSettings(dynamic model, HandlersSection section)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }
            if (section == null)
            {
                throw new ArgumentNullException("section");
            }

            try {
                if (model.allowed_access != null)
                {
                    Dictionary <string, bool> accessPolicyDictionary = null;

                    try {
                        accessPolicyDictionary = JsonConvert.DeserializeObject <Dictionary <string, bool> >(model.allowed_access.ToString());
                    }
                    catch (JsonSerializationException e) {
                        throw new ApiArgumentException("allowed_access", e);
                    }

                    if (accessPolicyDictionary == null)
                    {
                        throw new ApiArgumentException("allowed_access");
                    }

                    Dictionary <string, HandlerAccessPolicy> accessPolicyMap = new Dictionary <string, HandlerAccessPolicy>()
                    {
                        { "read", HandlerAccessPolicy.Read },
                        { "write", HandlerAccessPolicy.Write },
                        { "execute", HandlerAccessPolicy.Execute },
                        { "source", HandlerAccessPolicy.Source },
                        { "script", HandlerAccessPolicy.Script }
                    };

                    foreach (var key in accessPolicyMap.Keys)
                    {
                        if (accessPolicyDictionary.ContainsKey(key))
                        {
                            if (accessPolicyDictionary[key])
                            {
                                section.AccessPolicy |= accessPolicyMap[key];
                            }
                            else
                            {
                                section.AccessPolicy &= ~accessPolicyMap[key];
                            }
                        }
                    }
                }

                if (model.remote_access_prevention != null)
                {
                    Dictionary <string, bool> remoteAccessDictionary = null;

                    try {
                        remoteAccessDictionary = JsonConvert.DeserializeObject <Dictionary <string, bool> >(model.remote_access_prevention.ToString());
                    }
                    catch (JsonSerializationException e) {
                        throw new ApiArgumentException("remote_access_prevention", e);
                    }

                    if (remoteAccessDictionary == null)
                    {
                        throw new ApiArgumentException("remote_access_prevention");
                    }

                    Dictionary <string, HandlerAccessPolicy> remoteAccessMap = new Dictionary <string, HandlerAccessPolicy>()
                    {
                        { "read", HandlerAccessPolicy.NoRemoteRead },
                        { "write", HandlerAccessPolicy.NoRemoteWrite },
                        { "execute", HandlerAccessPolicy.NoRemoteExecute },
                        { "script", HandlerAccessPolicy.NoRemoteScript }
                    };

                    foreach (var key in remoteAccessMap.Keys)
                    {
                        if (remoteAccessDictionary.ContainsKey(key))
                        {
                            if (remoteAccessDictionary[key])
                            {
                                section.AccessPolicy |= remoteAccessMap[key];
                            }
                            else
                            {
                                section.AccessPolicy &= ~remoteAccessMap[key];
                            }
                        }
                    }
                }

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => section.OverrideMode = v);
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #26
0
        public static void SetFeatureSettings(dynamic model, Site site, string path, string configPath = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            var hasDynamic = ManagementUnit.ServerManager.GetApplicationHostConfiguration().HasSection(IPRestrictionsGlobals.DynamicIPSecuritySectionName);

            var mainSection = GetSection(site, path, configPath);
            DynamicIPSecuritySection dynamicSection = null;

            if (hasDynamic)
            {
                dynamicSection = GetDynamicSecuritySection(site, path, configPath);
            }

            try {
                DynamicHelper.If <bool>((object)model.allow_unlisted, v => mainSection.AllowUnlisted        = v);
                DynamicHelper.If <bool>((object)model.enable_reverse_dns, v => mainSection.EnableReverseDns = v);

                if (mainSection.Schema.HasAttribute(EnableProxyModeAttribute))
                {
                    DynamicHelper.If <bool>((object)model.enable_proxy_mode, v => mainSection.EnableProxyMode = v);
                }
                if (mainSection.Schema.HasAttribute(DenyActionAttribute))
                {
                    DynamicHelper.If <DenyActionType>((object)model.deny_action, v => mainSection.DenyAction = v);
                }

                if (hasDynamic)
                {
                    DynamicHelper.If <bool>((object)model.logging_only_mode, v => dynamicSection.LoggingOnlyMode = v);

                    // Concurrent request restrictions
                    if (model.deny_by_concurrent_requests != null)
                    {
                        if (!(model.deny_by_concurrent_requests is JObject))
                        {
                            throw new ApiArgumentException("deny_by_concurrent_requests");
                        }

                        dynamic denyConcurrent = model.deny_by_concurrent_requests;

                        DynamicHelper.If <bool>((object)denyConcurrent.enabled, v => dynamicSection.DenyByConcurrentRequests.Enabled = v);
                        DynamicHelper.If((object)denyConcurrent.max_concurrent_requests, 1, 4294967295, v => dynamicSection.DenyByConcurrentRequests.MaxConcurrentRequests = v);
                    }

                    // Request rate restrictions
                    if (model.deny_by_request_rate != null)
                    {
                        if (!(model.deny_by_request_rate is JObject))
                        {
                            throw new ApiArgumentException("deny_by_request_rate");
                        }

                        dynamic denyRequestRate = model.deny_by_request_rate;

                        DynamicHelper.If <bool>((object)denyRequestRate.enabled, v => dynamicSection.DenyByRequestRate.Enabled = v);
                        DynamicHelper.If((object)denyRequestRate.max_requests, 1, 4294967295, v => dynamicSection.DenyByRequestRate.MaxRequests = v);
                        DynamicHelper.If((object)denyRequestRate.time_period, 1, 4294967295, v => dynamicSection.DenyByRequestRate.TimePeriod   = v);
                    }
                }

                // Enabled
                DynamicHelper.If <bool>((object)model.enabled, v => {
                    if (!v)
                    {
                        mainSection.AllowUnlisted    = true;
                        mainSection.EnableReverseDns = false;

                        if (mainSection.Schema.HasAttribute(EnableProxyModeAttribute))
                        {
                            mainSection.EnableProxyMode = false;
                        }

                        if (hasDynamic)
                        {
                            dynamicSection.DenyByConcurrentRequests.Enabled = false;
                            dynamicSection.DenyByRequestRate.Enabled        = false;
                        }

                        mainSection.IpAddressFilters.Clear();
                    }
                });

                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => {
                        mainSection.OverrideMode = v;

                        if (hasDynamic)
                        {
                            dynamicSection.OverrideMode = v;
                        }
                    });
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(mainSection.SectionPath + "|" + dynamicSection.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #27
0
        private static Site SetSite(Site site, dynamic model)
        {
            Debug.Assert(site != null);
            Debug.Assert((bool)(model != null));

            DynamicHelper.If((object)model.name, v => { site.Name = v; });

            site.ServerAutoStart = DynamicHelper.To <bool>(model.server_auto_start) ?? site.ServerAutoStart;

            string physicalPath = DynamicHelper.Value(model.physical_path);

            if (physicalPath != null)
            {
                if (!Directory.Exists(System.Environment.ExpandEnvironmentVariables(physicalPath)))
                {
                    throw new ApiArgumentException("physical_path", "Directory does not exist.");
                }

                var rootApp = site.Applications["/"];
                if (rootApp == null)
                {
                    throw new ApiArgumentException("site/physical_path", "Root application does not exist.");
                }

                var rootVDir = rootApp.VirtualDirectories["/"];
                if (rootVDir == null)
                {
                    throw new ApiArgumentException("site/physical_path", "Root virtual directory does not exist.");
                }

                rootVDir.PhysicalPath = physicalPath.Replace('/', '\\');
            }

            string enabledProtocols = DynamicHelper.Value(model.enabled_protocols);

            if (enabledProtocols != null)
            {
                var rootApp = site.Applications["/"];

                if (rootApp != null)
                {
                    rootApp.EnabledProtocols = enabledProtocols;
                }
            }

            // Limits
            if (model.limits != null)
            {
                dynamic limits = model.limits;

                site.Limits.MaxBandwidth   = DynamicHelper.To(limits.max_bandwidth, 0, uint.MaxValue) ?? site.Limits.MaxBandwidth;
                site.Limits.MaxConnections = DynamicHelper.To(limits.max_connections, 0, uint.MaxValue) ?? site.Limits.MaxConnections;

                if (site.Limits.Schema.HasAttribute(MaxUrlSegmentsAttribute))
                {
                    site.Limits.MaxUrlSegments = DynamicHelper.To(limits.max_url_segments, 0, 16383) ?? site.Limits.MaxUrlSegments;
                }

                long?connectionTimeout = DynamicHelper.To(limits.connection_timeout, 0, ushort.MaxValue);
                site.Limits.ConnectionTimeout = (connectionTimeout != null) ? TimeSpan.FromSeconds(connectionTimeout.Value) : site.Limits.ConnectionTimeout;
            }

            // Bindings
            if (model.bindings != null)
            {
                IEnumerable <dynamic> bindings = (IEnumerable <dynamic>)model.bindings;

                // If the user passes an object for the bindings property rather than an array we will hit an exception when we try to access any property in
                // the foreach loop.
                // This means that the bindings collection won't be deleted, so the bindings are safe from harm.

                List <Binding> newBindings = new List <Binding>();

                // Iterate over the bindings to create a new binding list
                foreach (dynamic binding in bindings)
                {
                    // Extract data from binding
                    string ipAddress = DynamicHelper.Value(binding.ip_address);
                    long?  port      = DynamicHelper.To(binding.port, 1, 65535);
                    string hostname  = DynamicHelper.Value(binding.hostname) ?? "";

                    bool?  isHttps              = DynamicHelper.To <bool>(binding.is_https);
                    string certificateHash      = null;
                    string certificateStoreName = null;

                    byte[] hashBytes = null;

                    // Validate that data forms valid binding
                    if (ipAddress == null)
                    {
                        throw new ApiArgumentException("binding.ip_address");
                    }
                    else if (port == null)
                    {
                        throw new ApiArgumentException("binding.port");
                    }
                    else if (isHttps == null)
                    {
                        throw new ApiArgumentException("binding.is_https");
                    }

                    if (isHttps.Value)
                    {
                        if (binding.certificate == null || !(binding.certificate is JObject))
                        {
                            throw new ApiArgumentException("certificate");
                        }

                        dynamic certificate = binding.certificate;
                        string  uuid        = DynamicHelper.Value(certificate.id);

                        if (string.IsNullOrEmpty(uuid))
                        {
                            throw new ApiArgumentException("certificate.id");
                        }

                        CertificateId id = new CertificateId(uuid);
                        certificateHash      = id.Thumbprint;
                        certificateStoreName = Enum.GetName(typeof(StoreName), id.StoreName);

                        List <byte> bytes = new List <byte>();

                        // Decode the hex string of the certificate hash into bytes
                        for (int i = 0; i < id.Thumbprint.Length; i += 2)
                        {
                            bytes.Add(Convert.ToByte(id.Thumbprint.Substring(i, 2), 16));
                        }

                        hashBytes = bytes.ToArray();
                    }

                    // Create binding
                    Binding newBinding = site.Bindings.CreateElement();

                    // If format of the information is incorrect throws ArgumentException but does not populate ParamName
                    newBinding.BindingInformation = $"{ipAddress}:{port}:{hostname}";
                    newBinding.Protocol           = isHttps.Value ? "https" : "http";

                    // Attempting to get or set the certificate hash when the protocol is not https will raise an error -msdn
                    if (isHttps.Value)
                    {
                        // The specified certificate must be in the store with a private key or else there will be an exception when we commit
                        newBinding.CertificateHash      = hashBytes;
                        newBinding.CertificateStoreName = certificateStoreName;
                    }

                    // Add to bindings list
                    newBindings.Add(newBinding);
                }

                // All bindings have been verified and added to the list
                // Clear the old list, and add the new
                site.Bindings.Clear();
                newBindings.ForEach(binding => site.Bindings.Add(binding));
            }

            // Set the app pool
            if (model.application_pool != null)
            {
                // Extract the uuid from the application_pool object provided in model
                string appPoolUuid = DynamicHelper.Value(model.application_pool.id);

                // It is an error to provide an application pool object without specifying its id property
                if (appPoolUuid == null)
                {
                    throw new ApiArgumentException("application_pool.id");
                }

                // Create application pool id object from uuid provided, use this to obtain the application pool
                AppPools.AppPoolId appPoolId = AppPoolId.CreateFromUuid(appPoolUuid);
                ApplicationPool    pool      = AppPoolHelper.GetAppPool(appPoolId.Name);

                Application rootApp = site.Applications["/"];

                if (rootApp == null)
                {
                    throw new ApiArgumentException("application_pool", "Root application does not exist.");
                }

                // REVIEW: Should we create the root application if it doesn't exist and they specify an application pool?
                // We decided not to do this for physical_path.
                // Application pool for a site is extracted from the site's root application
                rootApp.ApplicationPoolName = pool.Name;
            }

            return(site);
        }
コード例 #28
0
        private static void AssignRuleFromModel(dynamic model, InboundRule rule, InboundRulesSection section, AllowedServerVariablesSection serverVariablesSection)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            //
            // Name, check for already existing name
            string name = DynamicHelper.Value(model.name);

            if (!string.IsNullOrEmpty(name))
            {
                if (!name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase) &&
                    section.InboundRules.Any(r => r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
                {
                    throw new AlreadyExistsException("name");
                }

                rule.Name = name;
            }

            DynamicHelper.If((object)model.pattern, v => rule.Match.Pattern = v);
            DynamicHelper.If <bool>((object)model.ignore_case, v => rule.Match.IgnoreCase   = v);
            DynamicHelper.If <bool>((object)model.negate, v => rule.Match.Negate            = v);
            DynamicHelper.If <bool>((object)model.stop_processing, v => rule.StopProcessing = v);
            DynamicHelper.If((object)model.pattern_syntax, v => rule.PatternSyntax          = PatternSyntaxHelper.FromJsonModel(v));

            //
            // Action
            dynamic action = model.action;

            if (action != null)
            {
                if (!(action is JObject))
                {
                    throw new ApiArgumentException("action", ApiArgumentException.EXPECTED_OBJECT);
                }

                DynamicHelper.If((object)action.type, v => rule.Action.Type = ActionTypeHelper.FromJsonModel(v));
                DynamicHelper.If((object)action.url, v => rule.Action.Url   = v);
                DynamicHelper.If <bool>((object)action.append_query_string, v => rule.Action.AppendQueryString = v);
                DynamicHelper.If <bool>((object)action.log_rewritten_url, v => rule.Action.LogRewrittenUrl     = v);
                DynamicHelper.If <long>((object)action.status_code, v => rule.Action.StatusCode        = v);
                DynamicHelper.If <long>((object)action.sub_status_code, v => rule.Action.SubStatusCode = v);
                DynamicHelper.If((object)action.description, v => rule.Action.StatusDescription        = v);
                DynamicHelper.If((object)action.reason, v => rule.Action.StatusReason = v);
                DynamicHelper.If <RedirectType>((object)action.redirect_type, v => rule.Action.RedirectType = v);
            }

            //
            // Server variables
            if (model.server_variables != null)
            {
                IEnumerable <dynamic> serverVariables = model.server_variables as IEnumerable <dynamic>;

                if (serverVariables == null)
                {
                    throw new ApiArgumentException("server_variables", ApiArgumentException.EXPECTED_ARRAY);
                }

                rule.ServerVariableAssignments.Clear();

                foreach (dynamic serverVariable in serverVariables)
                {
                    if (!(serverVariable is JObject))
                    {
                        throw new ApiArgumentException("server_variables.item");
                    }

                    string svName    = DynamicHelper.Value(serverVariable.name);
                    string svValue   = DynamicHelper.Value(serverVariable.value);
                    bool   svReplace = DynamicHelper.To <bool>(serverVariable.replace) ?? false;

                    if (string.IsNullOrEmpty(svName))
                    {
                        throw new ApiArgumentException("server_variables.item.name", "Required");
                    }

                    if (string.IsNullOrEmpty(svValue))
                    {
                        throw new ApiArgumentException("server_variables.item.value", "Required");
                    }

                    var svAssignment = rule.ServerVariableAssignments.CreateElement();
                    svAssignment.Name    = svName;
                    svAssignment.Value   = svValue;
                    svAssignment.Replace = svReplace;

                    AddAllowedServerVariable(serverVariablesSection, svAssignment.Name);

                    rule.ServerVariableAssignments.Add(svAssignment);
                }
            }

            DynamicHelper.If((object)model.condition_match_constraints, v => rule.Conditions.LogicalGrouping = LogicalGroupingHelper.FromJsonModel(v));
            DynamicHelper.If <bool>((object)model.track_all_captures, v => rule.Conditions.TrackAllCaptures  = v);

            //
            // Conditions
            if (model.conditions != null)
            {
                IEnumerable <dynamic> conditions = model.conditions as IEnumerable <dynamic>;

                if (conditions == null)
                {
                    throw new ApiArgumentException("conditions", ApiArgumentException.EXPECTED_ARRAY);
                }

                rule.Conditions.Clear();

                foreach (dynamic condition in conditions)
                {
                    if (!(condition is JObject))
                    {
                        throw new ApiArgumentException("conditions.item");
                    }

                    string input        = DynamicHelper.Value(condition.input);
                    string rawMatchType = DynamicHelper.Value(condition.match_type);

                    if (string.IsNullOrEmpty(input))
                    {
                        throw new ApiArgumentException("conditions.item.input", "Required");
                    }

                    if (string.IsNullOrEmpty(rawMatchType))
                    {
                        throw new ApiArgumentException("conditions.item.match_type", "Required");
                    }

                    MatchType matchType = MatchTypeHelper.FromJsonModel(rawMatchType);

                    var con = rule.Conditions.CreateElement();
                    con.Input      = input;
                    con.MatchType  = matchType;
                    con.Pattern    = DynamicHelper.Value(condition.pattern);
                    con.Negate     = DynamicHelper.To <bool>(condition.negate);
                    con.IgnoreCase = DynamicHelper.To <bool>(condition.ignore_case);

                    rule.Conditions.Add(con);
                }
            }

            if (rule.Schema.HasAttribute(InboundRule.ResponseCacheDirectiveAttribute))
            {
                DynamicHelper.If((object)model.response_cache_directive, v => rule.ResponseCacheDirective = ResponseCacheDirectiveHelper.FromJsonModel(v));
            }

            //
            // Check set to valid state
            if ((rule.Action.Type == ActionType.Redirect || rule.Action.Type == ActionType.Rewrite) && string.IsNullOrEmpty(rule.Action.Url))
            {
                throw new ApiArgumentException("action.url");
            }

            UpdatePriority(model, rule, section);
        }
コード例 #29
0
        private static void SetProvider(dynamic model, Provider provider, ProvidersSection section)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            try {
                //
                // Name, check for already existing name
                string name = DynamicHelper.Value(model.name);
                if (!string.IsNullOrEmpty(name))
                {
                    if (!name.Equals(provider.Name, StringComparison.OrdinalIgnoreCase) &&
                        section.Providers.Any(r => r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
                    {
                        throw new AlreadyExistsException("name");
                    }

                    provider.Name = name;
                }

                DynamicHelper.If((object)model.type, v => provider.TypeName = v);

                //
                // settings
                if (model.settings != null)
                {
                    IEnumerable <dynamic> settings = model.settings as IEnumerable <dynamic>;

                    if (settings == null)
                    {
                        throw new ApiArgumentException("settings", ApiArgumentException.EXPECTED_ARRAY);
                    }

                    provider.Settings.Clear();

                    foreach (dynamic setting in settings)
                    {
                        if (!(setting is JObject))
                        {
                            throw new ApiArgumentException("settings.item");
                        }

                        string settingName = DynamicHelper.Value(setting.name);
                        string value       = DynamicHelper.Value(setting.value);

                        if (string.IsNullOrEmpty(settingName))
                        {
                            throw new ApiArgumentException("settings.item.name", "Required");
                        }

                        if (string.IsNullOrEmpty(value))
                        {
                            throw new ApiArgumentException("settings.item.value", "Required");
                        }

                        var set = provider.Settings.CreateElement();
                        set.Key   = settingName;
                        set.Value = value;

                        provider.Settings.Add(set);
                    }
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(section.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }
コード例 #30
0
        public static void Update(dynamic model, Site site, string path, string configScope = null)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            // Cannot configure at any path below site
            if (site != null && path != "/")
            {
                throw new InvalidScopeTypeException(string.Format("{0}{1}", (site == null ? "" : site.Name), path ?? ""));
            }

            LogSection         logSection         = GetLogSection(site, path, configScope);
            HttpLoggingSection httpLoggingSection = GetHttpLoggingSection(site, path, configScope);

            // Site log settings are set in the site defaults if Configuration target is server
            // If target is a site then the site's logfile element is used
            SiteLogFile siteLogFile = site == null ? ManagementUnit.Current.ServerManager.SiteDefaults.LogFile : site.LogFile;

            try {
                bool?enabled = DynamicHelper.To <bool>(model.enabled);
                if (enabled != null)
                {
                    TrySetLoggingEnabled(enabled.Value, httpLoggingSection, logSection, siteLogFile, site, configScope);
                }

                // Extract rollover from model
                dynamic rollover = model.rollover;
                if (rollover != null && !(rollover is JObject))
                {
                    throw new ApiArgumentException("rollover", ApiArgumentException.EXPECTED_OBJECT);
                }

                // Only accessible at server level
                if (site == null)
                {
                    DynamicHelper.If <bool>((object)model.log_per_site, v => logSection.CentralLogFileMode = v ? CentralLogFileMode.Site : CentralLogFileMode.CentralW3C);
                    DynamicHelper.If <FileLogFormat>((object)model.log_file_format, v => {
                        // Site log mode exposes 4 possible log formats
                        if (logSection.CentralLogFileMode == CentralLogFileMode.Site)
                        {
                            switch (v)
                            {
                            case FileLogFormat.Custom:
                                siteLogFile.LogFormat = LogFormat.Custom;
                                break;

                            case FileLogFormat.Iis:
                                siteLogFile.LogFormat = LogFormat.Iis;
                                break;

                            case FileLogFormat.W3c:
                                siteLogFile.LogFormat = LogFormat.W3c;
                                break;

                            case FileLogFormat.Ncsa:
                                siteLogFile.LogFormat = LogFormat.Ncsa;
                                break;

                            default:
                                throw new ApiArgumentException("log_file_format");
                            }
                        }
                        // Server log mode exposes 2 possible log formats
                        else
                        {
                            switch (v)
                            {
                            case FileLogFormat.W3c:
                                logSection.CentralLogFileMode = CentralLogFileMode.CentralW3C;
                                break;

                            case FileLogFormat.Binary:
                                logSection.CentralLogFileMode = CentralLogFileMode.CentralBinary;
                                break;

                            default:
                                throw new ApiArgumentException("log_file_format");
                            }
                        }
                    });
                    DynamicHelper.If((object)model.log_file_encoding, v => {
                        switch (v.ToLower())
                        {
                        case "utf-8":
                            logSection.LogInUTF8 = true;
                            break;

                        case "ansi":
                            logSection.LogInUTF8 = false;
                            break;

                        default:
                            throw new ApiArgumentException("log_file_encoding");
                        }
                    });

                    // Binary log mode settings
                    if (logSection.CentralLogFileMode == CentralLogFileMode.CentralBinary)
                    {
                        dynamic bSettings = model;


                        CentralBinaryLogFile bFile = logSection.CentralBinaryLogFile;

                        DynamicHelper.If((object)bSettings.directory, v => bFile.Directory = v);

                        if (rollover != null)
                        {
                            DynamicHelper.If <LoggingRolloverPeriod>((object)PeriodFromRepresentation(rollover.period), v => bFile.Period = v);
                            DynamicHelper.If((object)rollover.truncate_size, 1048576, 4294967295, v => bFile.TruncateSize = v);
                            DynamicHelper.If <bool>((object)rollover.use_local_time, v => bFile.LocalTimeRollover         = v);
                        }
                    }

                    // W3C log mode settings
                    if (logSection.CentralLogFileMode == CentralLogFileMode.CentralW3C)
                    {
                        dynamic wSettings = model;

                        CentralW3CLogFile wFile = logSection.CentralW3CLogFile;

                        DynamicHelper.If((object)wSettings.directory, v => wFile.Directory = v);

                        if (rollover != null)
                        {
                            DynamicHelper.If <LoggingRolloverPeriod>((object)PeriodFromRepresentation(rollover.period), v => wFile.Period = v);
                            DynamicHelper.If((object)rollover.truncate_size, 1048576, 4294967295, v => wFile.TruncateSize = v);
                            DynamicHelper.If <bool>((object)rollover.use_local_time, v => wFile.LocalTimeRollover         = v);
                        }

                        if (wSettings.log_fields != null)
                        {
                            try {
                                wFile.LogExtFileFlags = SetLogFieldFlags(wFile.LogExtFileFlags, wSettings.log_fields);
                            }
                            catch (ApiArgumentException e) {
                                throw new ApiArgumentException("w3c_settings.log_fields", e);
                            }
                            catch (JsonSerializationException e) {
                                throw new ApiArgumentException("w3c_settings.log_fields", e);
                            }
                        }
                    }
                }

                //
                // Per site mode format
                DynamicHelper.If <FileLogFormat>((object)model.log_file_format, v => {
                    if (logSection.CentralLogFileMode == CentralLogFileMode.Site)
                    {
                        switch (v)
                        {
                        case FileLogFormat.Custom:
                            siteLogFile.LogFormat = LogFormat.Custom;
                            break;

                        case FileLogFormat.Iis:
                            siteLogFile.LogFormat = LogFormat.Iis;
                            break;

                        case FileLogFormat.W3c:
                            siteLogFile.LogFormat = LogFormat.W3c;
                            break;

                        case FileLogFormat.Ncsa:
                            siteLogFile.LogFormat = LogFormat.Ncsa;
                            break;

                        default:
                            throw new ApiArgumentException("log_file_format");
                        }
                    }
                });

                // Site settings
                if (logSection.CentralLogFileMode == CentralLogFileMode.Site)
                {
                    dynamic siteSettings = model;

                    DynamicHelper.If((object)siteSettings.directory, v => siteLogFile.Directory = v);

                    if (rollover != null)
                    {
                        DynamicHelper.If <LoggingRolloverPeriod>((object)PeriodFromRepresentation(rollover.period), v => siteLogFile.Period = v);
                        DynamicHelper.If((object)rollover.truncate_size, 1048576, 4294967295, v => siteLogFile.TruncateSize = v);
                        DynamicHelper.If <bool>((object)rollover.use_local_time, v => siteLogFile.LocalTimeRollover         = v);
                    }

                    if (siteSettings.log_fields != null)
                    {
                        try {
                            siteLogFile.LogExtFileFlags = SetLogFieldFlags(siteLogFile.LogExtFileFlags, siteSettings.log_fields);
                        }
                        catch (ApiArgumentException e) {
                            throw new ApiArgumentException("site_settings.log_fields", e);
                        }
                        catch (JsonSerializationException e) {
                            throw new ApiArgumentException("site_settings.log_fields", e);
                        }
                    }

                    if (siteSettings.log_target != null && siteLogFile.Schema.HasAttribute(LogTargetW3CAttribute))
                    {
                        try {
                            Dictionary <string, bool> logTargets = JsonConvert.DeserializeObject <Dictionary <string, bool> >(siteSettings.log_target.ToString());

                            if (logTargets == null)
                            {
                                throw new ApiArgumentException("site_settings.log_target_w3c");
                            }

                            LogTargetW3C logTargetW3C = siteLogFile.LogTargetW3C;

                            if (logTargets.ContainsKey("etw"))
                            {
                                if (logTargets["etw"])
                                {
                                    logTargetW3C |= LogTargetW3C.ETW;
                                }
                                else
                                {
                                    logTargetW3C &= ~LogTargetW3C.ETW;
                                }
                            }
                            if (logTargets.ContainsKey("file"))
                            {
                                if (logTargets["file"])
                                {
                                    logTargetW3C |= LogTargetW3C.File;
                                }
                                else
                                {
                                    logTargetW3C &= ~LogTargetW3C.File;
                                }
                            }

                            siteLogFile.LogTargetW3C = logTargetW3C;
                        }
                        catch (JsonSerializationException e) {
                            throw new ApiArgumentException("site_settings.log_fields", e);
                        }
                    }

                    if (siteSettings.custom_log_fields != null && siteLogFile.Schema.HasChildElement(CustomFieldsElement))
                    {
                        IEnumerable <dynamic> customFields = siteSettings.custom_log_fields;

                        List <CustomField> tempCustFields = new List <CustomField>();

                        foreach (dynamic field in customFields)
                        {
                            string fieldName  = DynamicHelper.Value(field.field_name);
                            string sourceName = DynamicHelper.Value(field.source_name);
                            CustomLogFieldSourceType?sourceType = SourceTypeFromRepresentation(field.source_type);

                            if (string.IsNullOrEmpty(fieldName))
                            {
                                throw new ApiArgumentException("custom_log_field.field_name");
                            }
                            if (string.IsNullOrEmpty(sourceName))
                            {
                                throw new ApiArgumentException("custom_log_field.source_name");
                            }
                            if (sourceType == null)
                            {
                                throw new ApiArgumentException("custom_log_field.source_type");
                            }

                            tempCustFields.Add(new CustomField()
                            {
                                FieldName  = fieldName,
                                SourceName = sourceName,
                                SourceType = sourceType.Value
                            });
                        }

                        siteLogFile.CustomLogFields.Clear();
                        tempCustFields.ForEach(f => siteLogFile.CustomLogFields.Add(f.FieldName, f.SourceName, f.SourceType));
                    }
                }


                if (model.metadata != null)
                {
                    DynamicHelper.If <OverrideMode>((object)model.metadata.override_mode, v => httpLoggingSection.OverrideMode = v);
                }
            }
            catch (FileLoadException e) {
                throw new LockedException(logSection.SectionPath + "|" + httpLoggingSection.SectionPath, e);
            }
            catch (DirectoryNotFoundException e) {
                throw new ConfigScopeNotFoundException(e);
            }
        }