internal SiteCollection(ConfigurationElement element, ServerManager parent) : base(element, "sites", parent.SiteCollection?.Schema, null, parent.SiteCollection?.InnerEntity, null) { Parent = parent; Section = element?.Section; if (element == null) { return; } foreach (ConfigurationElement node in element.GetCollection()) { if (Schema.CollectionSchema.ContainsAddElement(node.ElementTagName)) { InternalAdd(new Site(node, this)); } } }
private static void ConfigureCertificateRules(ConfigurationElement element) { var rulesCollection = element.GetCollection("rules"); var issuerRule = rulesCollection.CreateElement("add"); issuerRule["certificateField"] = @"Issuer"; issuerRule["certificateSubField"] = @"CN"; issuerRule["matchCriteria"] = @"CARoot"; issuerRule["compareCaseSensitive"] = true; var subjectRule = rulesCollection.CreateElement("add"); subjectRule["certificateField"] = @"Subject"; subjectRule["certificateSubField"] = @"CN"; subjectRule["matchCriteria"] = @"ClientCert"; subjectRule["compareCaseSensitive"] = true; rulesCollection.Add(issuerRule); rulesCollection.Add(subjectRule); }
private void CheckName(string name) { bool isAttribute = (_lockType & ConfigurationLockType.Attribute) == ConfigurationLockType.Attribute; if (_valid_name_hash == null) { _valid_name_hash = new Hashtable(); foreach (ConfigurationAttributeSchema prop in _element.Schema.AttributeSchemas) { _valid_name_hash.Add(prop.Name, true); } /* add the add/remove/clear names of the * default collection if there is one */ if (!isAttribute) { ConfigurationElementCollection c = _element.GetCollection(); foreach (var addName in _element.Schema.CollectionSchema.AddElementNames.Split(',')) { _valid_name_hash.Add(addName, true); } _valid_name_hash.Add(c.Schema.CollectionSchema.ClearElementName, true); _valid_name_hash.Add(c.Schema.CollectionSchema.RemoveElementName, true); } string[] valid_name_array = new string[_valid_name_hash.Keys.Count]; _valid_name_hash.Keys.CopyTo(valid_name_array, 0); _valid_names = String.Join(",", valid_name_array); } if (_valid_name_hash[name] == null) { throw new ServerManagerException( String.Format("The {2} '{0}' is not valid in the locked list for this section. The following {3} can be locked: '{1}'", name, _valid_names, isAttribute ? "attribute" : "element", isAttribute ? "attributes" : "elements")); } }
private void CheckName(string name) { bool isAttribute = (_lockType & ConfigurationLockType.Attribute) == ConfigurationLockType.Attribute; if (_valid_name_hash == null) { _valid_name_hash = new Hashtable(); foreach (ConfigurationAttributeSchema prop in _element.Schema.AttributeSchemas) { _valid_name_hash.Add(prop.Name, true); } /* add the add/remove/clear names of the * default collection if there is one */ if (!isAttribute) { ConfigurationElementCollection c = _element.GetCollection(); foreach (var addName in _element.Schema.CollectionSchema.AddElementNames.Split(',')) { _valid_name_hash.Add(addName, true); } _valid_name_hash.Add(c.Schema.CollectionSchema.ClearElementName, true); _valid_name_hash.Add(c.Schema.CollectionSchema.RemoveElementName, true); } string[] valid_name_array = new string[_valid_name_hash.Keys.Count]; _valid_name_hash.Keys.CopyTo(valid_name_array, 0); _valid_names = String.Join(",", valid_name_array); } if (_valid_name_hash[name] == null) { throw new ArgumentException($"lockAttributes contains unknown attribute '{name}'"); } }
public async Task SaveAsync(Application application) { var variables = new SortedDictionary <string, List <string> >(); foreach (var item in application.Extra) { variables.Add(item.Key, item.Value); } var vDir = application.VirtualDirectories[0]; Configuration config = application.GetWebConfiguration(); ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument"); ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files"); ConfigurationSection httpLoggingSection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/httpLogging", application.Location); ConfigurationSection ipSecuritySection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/security/ipSecurity", application.Location); ConfigurationSection requestFilteringSection = config.GetSection("system.webServer/security/requestFiltering"); ConfigurationElement hiddenSegmentsElement = requestFilteringSection.GetChildElement("hiddenSegments"); ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection(); ConfigurationSection httpErrorsSection = config.GetSection("system.webServer/httpErrors"); ConfigurationElementCollection httpErrorsCollection = httpErrorsSection.GetCollection(); var urlCompressionSection = config.GetSection("system.webServer/urlCompression"); ConfigurationSection httpProtocolSection = config.GetSection("system.webServer/httpProtocol"); ConfigurationSection rewriteSection = config.GetSection("system.webServer/rewrite/rules"); ConfigurationElementCollection rewriteCollection = rewriteSection.GetCollection(); variables.Add("usehttps", new List <string> { (application.Site.Bindings[0].Protocol == "https").ToString() }); variables.Add("addr", new List <string> { application.Site.Bindings[0].EndPoint.Address.ToString() }); variables.Add("port", new List <string> { application.Site.Bindings[0].EndPoint.Port.ToString() }); variables.Add("hosts", new List <string> { application.Site.Bindings[0].Host }); variables.Add("root", new List <string> { string.Format("{0} {1}", vDir.Path, vDir.PhysicalPath) }); variables.Add("nolog", new List <string> { httpLoggingSection["dontLog"].ToString() }); variables.Add("keep_alive", new List <string> { httpProtocolSection["allowKeepAlive"].ToString() }); var indexes = new StringBuilder(); foreach (ConfigurationElement item in filesCollection) { indexes.AppendFormat("{0},", item.RawAttributes["value"]); } if (indexes.Length > 0) { indexes.Length--; } variables.Add("indexes", new List <string> { indexes.ToString() }); var allows = new List <string>(); var denys = new List <string>(); foreach (ConfigurationElement item in ipSecuritySection.GetCollection()) { string element = string.IsNullOrEmpty((string)item["subnetMask"]) ? (string)item["ipAddress"] : string.Format("{0}/{1}", item["ipAddress"], item["subnetMask"]); if ((bool)item["allowed"]) { allows.Add(element); } else { denys.Add(element); } } variables.Add("allowfrom", allows); variables.Add("denyfrom", denys); var segments = new StringBuilder(); foreach (ConfigurationElement item in hiddenSegmentsCollection) { segments.AppendFormat("{0},", item["segment"]); } if (segments.Length > 0) { segments.Length--; } variables.Add("denydirs", new List <string> { segments.ToString() }); foreach (ConfigurationElement item in httpErrorsCollection) { if ((uint)item["statusCode"] == 404 && (int)item["subStatusCode"] == 0 && (string)item["prefixLanguageFilePath"] == @"%SystemDrive%\inetpub\custerr" && (long)item["responseMode"] == 1) { variables.Add("nofile", new List <string> { item["path"].ToString() }); } } variables.Add("usegzip", new List <string> { urlCompressionSection["doStaticCompression"].ToString() }); var rules = new List <string>(); foreach (ConfigurationElement item in rewriteCollection) { var action = item.GetChildElement("action"); var match = item.GetChildElement("match"); if ((long)action["type"] == 2) { rules.Add(string.Format("{0}{2} {1}", match["url"], action["url"], (bool)match["ignoreCase"] ? "/i" : string.Empty)); } } variables.Add("rewrite", rules); if (string.IsNullOrEmpty(application.Server.HostName)) { var rows = new List <string>(); foreach (var item in variables) { foreach (var line in item.Value) { rows.Add(string.Format("{0}={1}", item.Key, line)); } } var fileName = Path.Combine("siteconf", application.ToFileName()); File.WriteAllLines(fileName, rows); } else { using (var client = GetClient()) { HttpResponseMessage response = await client.PutAsJsonAsync(string.Format("api/site/{0}", application.ToFileName()), variables); if (response.IsSuccessStatusCode) { } } } }
public async Task LoadAsync(Application application, string file, string appName, SortedDictionary <string, List <string> > variables) { if (variables == null) { if (Credentials == null) { var rows = File.ReadAllLines(file); variables = new SortedDictionary <string, List <string> >(); foreach (var line in rows) { var index = line.IndexOf('#'); var content = index == -1 ? line : line.Substring(0, index); var parts = content.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { continue; } var key = parts[0].Trim().ToLowerInvariant(); var value = parts[1].Trim(); if (variables.ContainsKey(key)) { variables[key].Add(value); continue; } variables.Add(key, new List <string> { value }); } } else { using (var client = GetClient()) { HttpResponseMessage response = await client.GetAsync(string.Format("api/app/get/{0}", appName)); if (response.IsSuccessStatusCode) { variables = (SortedDictionary <string, List <string> >) await response.Content.ReadAsAsync(typeof(SortedDictionary <string, List <string> >)); } } } } variables.Load(new List <string> { "false" }, "usehttps"); variables.Load(new List <string> { "*" }, "hosts", "host"); variables.Load(new List <string> { IPAddress.Any.ToString() }, "addr", "address"); variables.Load(new List <string> { "80" }, "port"); var root = variables.Load(new List <string> { "/ /var/www/default" }, "root")[0]; var split = root.IndexOf(' '); if (split == -1 || split == 0) { throw new ServerManagerException("invalid root mapping"); } var virtualDirectory = new VirtualDirectory(null, application.VirtualDirectories); virtualDirectory.Path = root.Substring(0, split); virtualDirectory.PhysicalPath = root.Substring(split + 1); application.VirtualDirectories.Add(virtualDirectory); var configuration = application.GetWebConfiguration(); var defaultDocument = configuration.GetSection("system.webServer/defaultDocument"); defaultDocument["enabled"] = true; var collection = defaultDocument.GetCollection("files"); collection.Clear(); var names = variables.Load(new List <string> { Constants.DefaultDocumentList }, "indexes", "indexs")[0]; var pageNames = names.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var name in pageNames) { var file1 = collection.CreateElement(); file1.Attributes["value"].Value = name; collection.Add(file1); } ConfigurationSection httpLoggingSection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/httpLogging", application.Location); var dontLog = Convert.ToBoolean(variables.Load(new List <string> { "false" }, "nolog")[0]); httpLoggingSection["dontLog"] = dontLog; var ipSecuritySection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/security/ipSecurity", application.Location); ipSecuritySection["enableReverseDns"] = false; ipSecuritySection["allowUnlisted"] = true; ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection(); ipSecurityCollection.Clear(); var deny = variables.Load(new List <string>(), "denyfrom", "ip.deny"); foreach (var denyEntry in deny) { var denyItems = denyEntry.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in denyItems) { ConfigurationElement addElement = ipSecurityCollection.CreateElement("add"); if (item.Contains("/")) { var parts = item.Split('/'); addElement["ipAddress"] = parts[0]; addElement["subnetMask"] = parts[1]; } else { addElement["ipAddress"] = item; } addElement["allowed"] = false; ipSecurityCollection.Add(addElement); } } var allow = variables.Load(new List <string>(), "allowfrom", "ip.allow"); foreach (var allowEntry in allow) { var allowItems = allowEntry.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in allowItems) { ConfigurationElement addElement = ipSecurityCollection.CreateElement("add"); if (item.Contains("/")) { var parts = item.Split('/'); addElement["ipAddress"] = parts[0]; addElement["subnetMask"] = parts[1]; } else { addElement["ipAddress"] = item; } addElement["allowed"] = true; ipSecurityCollection.Add(addElement); } } ConfigurationSection requestFilteringSection = configuration.GetSection("system.webServer/security/requestFiltering"); ConfigurationElement hiddenSegmentsElement = requestFilteringSection.ChildElements["hiddenSegments"]; ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection(); hiddenSegmentsCollection.Clear(); var hidden = variables.Load(new List <string> { string.Empty }, "denydirs")[0]; var hiddenItems = hidden.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in hiddenItems) { ConfigurationElement add = hiddenSegmentsCollection.CreateElement("add"); add["segment"] = item; hiddenSegmentsCollection.Add(add); } ConfigurationSection httpErrorsSection = configuration.GetSection("system.webServer/httpErrors"); ConfigurationElementCollection httpErrorsCollection = httpErrorsSection.GetCollection(); httpErrorsCollection.Clear(); Debug.Assert(variables != null, "variables != null"); if (variables.ContainsKey("nofile")) { var error = variables["nofile"][0]; ConfigurationElement errorElement = httpErrorsCollection.CreateElement("error"); errorElement["statusCode"] = 404; errorElement["subStatusCode"] = 0; errorElement["prefixLanguageFilePath"] = @"%SystemDrive%\inetpub\custerr"; errorElement["responseMode"] = "ExecuteURL"; errorElement["path"] = error; httpErrorsCollection.Add(errorElement); variables.Remove("nofile"); } var urlCompressionSection = configuration.GetSection("system.webServer/urlCompression"); urlCompressionSection["doStaticCompression"] = Convert.ToBoolean(variables.Load(new List <string> { "true" }, "usegzip")[0]); ConfigurationSection httpProtocolSection = configuration.GetSection("system.webServer/httpProtocol"); httpProtocolSection["allowKeepAlive"] = Convert.ToBoolean(variables.Load(new List <string> { "true" }, "keep_alive")[0]); ConfigurationSection rulesSection = configuration.GetSection("system.webServer/rewrite/rules"); ConfigurationElementCollection rulesCollection = rulesSection.GetCollection(); rulesCollection.Clear(); if (variables.ContainsKey("rewrite")) { var rules = variables["rewrite"]; for (int i = 0; i < rules.Count; i++) { var rule = rules[i]; ConfigurationElement ruleElement = rulesCollection.CreateElement("rule"); ruleElement["name"] = @"rule" + i; ruleElement["enabled"] = true; ruleElement["patternSyntax"] = 0; ruleElement["stopProcessing"] = false; var parts = rule.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); ConfigurationElement matchElement = ruleElement.GetChildElement("match"); matchElement["ignoreCase"] = parts[0].EndsWith("/i", StringComparison.Ordinal); matchElement["url"] = parts[0].EndsWith("/i", StringComparison.Ordinal) ? parts[0].Substring(0, parts[0].Length - 2) : parts[0]; ConfigurationElement actionElement = ruleElement.GetChildElement("action"); actionElement["type"] = 2; actionElement["url"] = parts[1]; actionElement["appendQueryString"] = true; rulesCollection.Add(ruleElement); } variables.Remove("rewrite"); } application.Extra = variables; }
static internal IEnumerable<string> GetApplicationPaths(ConfigurationElement site) { List<string> appPaths = new List<string>(); ConfigurationElementCollection applications = site.GetCollection(); foreach (ConfigurationElement application in applications) { string appPath = (string)application["path"]; appPaths.Add(appPath); } return appPaths; }
// translate IIS setting on extended protection to NCL object static internal void ReadIisExtendedProtectionPolicy(ConfigurationElement element, out ExtendedProtectionTokenChecking tokenChecking, out ExtendedProtectionFlags flags, out List<string> spnList) { tokenChecking = (ExtendedProtectionTokenChecking)element.GetAttributeValue(MetabaseSettingsIis7Constants.TokenCheckingAttributeName); flags = (ExtendedProtectionFlags)element.GetAttributeValue(MetabaseSettingsIis7Constants.FlagsAttributeName); spnList = new List<string>(); foreach (ConfigurationElement configElement in element.GetCollection()) { spnList.Add((string)configElement[MetabaseSettingsIis7Constants.NameAttributeName]); } }
static internal List<string> GetProviderList(ConfigurationElement section) { List<string> providerList = new List<string>(); foreach (ConfigurationElement element in section.GetCollection(MetabaseSettingsIis7Constants.ProviderElementName)) { providerList.Add((string)element[MetabaseSettingsIis7Constants.ValueAttributeName]); } return providerList; }
static internal string GetEnabledProtocols(ConfigurationElement site) { ConfigurationElement application = FindElement( site.GetCollection(), MetabaseSettingsIis7Constants.PathAttributeName, HostingEnvironment.ApplicationVirtualPath ); DiagnosticUtility.DebugAssert(application != null, "Unable to find application."); return (string)application[MetabaseSettingsIis7Constants.EnabledProtocolsAttributeName]; }
static internal IDictionary<string, List<string>> GetProtocolBindingTable(ConfigurationElement site) { IDictionary<string, List<string>> bindingList = new Dictionary<string, List<string>>(); foreach (ConfigurationElement binding in site.GetCollection(MetabaseSettingsIis7Constants.BindingsElementName)) { string protocol = ((string)binding[MetabaseSettingsIis7Constants.ProtocolAttributeName]).ToLowerInvariant(); string bindingInformation = (string)binding[MetabaseSettingsIis7Constants.BindingInfoAttributeName]; Debug.Print("MetabaseSettingsIis7V2.ctor() adding Protocol: " + protocol + " BindingInformation: " + bindingInformation); if (!bindingList.ContainsKey(protocol)) { bindingList.Add(protocol, new List<string>()); } bindingList[protocol].Add(bindingInformation); } return bindingList; }
private ConfigurationElement GetServer(ConfigurationElement farm, string address) { ConfigurationElementCollection servers = farm.GetCollection(); ConfigurationElement server = servers.FirstOrDefault(f => f.GetAttributeValue("address").ToString() == address); if (server == null) { _Log.Information("The server '{0}' does not exists.", address); } return server; }
public bool DeleteBinding(string domainName) { var siteName = System.Configuration.ConfigurationManager.AppSettings["webSiteName"]; using (ServerManager serverManager = new ServerManager()) { Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration(); Microsoft.Web.Administration.ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites"); Microsoft.Web.Administration.ConfigurationElementCollection sitesCollection = sitesSection.GetCollection(); Microsoft.Web.Administration.ConfigurationElement siteElement = FindElement(sitesCollection, "site", "name", siteName); if (siteElement == null) { throw new InvalidOperationException("Element not found!"); } Microsoft.Web.Administration.ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings"); var binding = FindElement(bindingsCollection, "binding", "bindingInformation", "*:80:" + domainName); if (binding == null) { throw new InvalidOperationException("Binding not found!"); } bindingsCollection.Remove(binding); var binding1 = FindElement(bindingsCollection, "binding", "bindingInformation", "*:80:www." + domainName); if (binding1 == null) { throw new InvalidOperationException("Binding not found!"); } bindingsCollection.Remove(binding1); serverManager.CommitChanges(); } return(true); }
public bool AddBinding(string domainName) { var siteName = System.Configuration.ConfigurationManager.AppSettings["webSiteName"]; using (ServerManager serverManager = new ServerManager()) { Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration(); Microsoft.Web.Administration.ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites"); Microsoft.Web.Administration.ConfigurationElementCollection sitesCollection = sitesSection.GetCollection(); Microsoft.Web.Administration.ConfigurationElement siteElement = FindElement(sitesCollection, "site", "name", siteName); if (siteElement == null) { throw new InvalidOperationException("Element not found!"); } Microsoft.Web.Administration.ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings"); Microsoft.Web.Administration.ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding"); bindingElement["protocol"] = @"http"; bindingElement["bindingInformation"] = @"*:80:" + domainName; bindingsCollection.Add(bindingElement); Microsoft.Web.Administration.ConfigurationElement bindingElement1 = bindingsCollection.CreateElement("binding"); bindingElement1["protocol"] = @"http"; bindingElement1["bindingInformation"] = @"*:80:www." + domainName; bindingsCollection.Add(bindingElement1); serverManager.CommitChanges(); } return(true); }
/// <summary> /// 添加IIS mime类型 /// </summary> /// <param name="mimeDic"></param> /// <returns></returns> private static bool AddMIMEType(Microsoft.Web.Administration.Configuration confg, Dictionary <string, string> mimeDic) { try { Microsoft.Web.Administration.ConfigurationSection section; section = confg.GetSection("system.webServer/staticContent"); //取得MimeMap所有节点(路径为:%windir%\Windows\System32\inetsrv\config\applicationHost.config) Microsoft.Web.Administration.ConfigurationElement filesElement = section.GetCollection(); Microsoft.Web.Administration.ConfigurationElementCollection filesCollection = filesElement.GetCollection(); foreach (var key in mimeDic.Keys) { Microsoft.Web.Administration.ConfigurationElement newElement = filesCollection.CreateElement(); //新建MimeMap节点 newElement.Attributes["fileExtension"].Value = key; newElement.Attributes["mimeType"].Value = mimeDic[key]; if (!filesCollection.Contains(newElement)) { filesCollection.Add(newElement); } } server.CommitChanges();//更改 return(true); } catch (Exception) { return(false); } }