Inheritance: ConfigurationElement
 protected void LoadVirtualDirectory()
 {
     using (var iis = ServerManager.OpenRemote("localhost"))
     {
         var site = iis.Sites[WebSiteName];
         var appPath = "/" + VirtualDirectory;
         application = site.Applications[appPath];
         vDir = application.VirtualDirectories["/"];
         applicationPool = iis.ApplicationPools[application.ApplicationPoolName];
     }
 }
		private void Initialize(VirtualDirectory virtualDirectory, string siteName, string webApplicationName)
		{
			this.Key = GetVirtualDirectoryVariableName(siteName, virtualDirectory.Path);

			this.IsRootOfAnApplication = (virtualDirectory.Path == "/");

			AddAttribute("Name", virtualDirectory.Path);
			
			AddAttribute("Ensure", "Present");
			AddAttribute("Website", siteName);
			AddAttribute("PhysicalPath", virtualDirectory.PhysicalPath);
			AddAttribute("WebApplication", FormatWebApplicationName( webApplicationName));
			AddAttribute("DependsOn", "[cWebSite]" + SiteDesiredState.GetSiteKey(siteName));
		}
Ejemplo n.º 3
0
        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;
        }
        internal override void SetPassword(VirtualDirectory virtualDirectory, string password)
        {
            var directory = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
                "IIS Express");

            if (!Directory.Exists(directory))
            {
                // IMPORTANT: for x86 IIS 7 Express
                directory = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
                    "IIS Express");
                if (!Directory.Exists(directory))
                {
                    // IMPORTANT: fallback to default password setting. Should throw encryption exception.
                    virtualDirectory.Password = password;
                    return;
                }
            }

            // IMPORTANT: save vdir to config file.
            CommitChanges();
            var appcmd = Path.Combine(directory, "appcmd.exe");

            if (!File.Exists(appcmd))
            {
                // IMPORTANT: fallback to default password setting. Should throw encryption exception.
                virtualDirectory.Password = password;
                return;
            }

            {
                var command    = $"set vdir /vdir.name:\"{virtualDirectory.LocationPath()}\" /-password /apphostconfig:\"{FileName}\"";
                var resultFile = Path.GetTempFileName();
                using var process = new Process
                      {
                          StartInfo = new ProcessStartInfo
                          {
                              FileName        = "cmd",
                              Arguments       = $"/c \"\"{CertificateInstallerLocator.FileName}\" /verb:appcmd /launcher:\"{appcmd}\" /resultFile:\"{resultFile}\" /input:\"{command}\"\"",
                              CreateNoWindow  = true,
                              WindowStyle     = ProcessWindowStyle.Hidden,
                              Verb            = "runas",
                              UseShellExecute = true
                          }
                      };
                try
                {
                    process.Start();
                    process.WaitForExit();
                    if (process.ExitCode != 0)
                    {
                        var message = File.ReadAllText(resultFile);
                        File.Delete(resultFile);
                        throw new Exception($"{process.ExitCode} {message}");
                    }
                }
                catch (Win32Exception ex)
                {
                    // elevation is cancelled.
                    if (ex.NativeErrorCode != NativeMethods.ErrorCancelled)
                    {
                        RollbarLocator.RollbarInstance.Error(ex, new Dictionary <string, object> {
                            { "native", ex.NativeErrorCode }
                        });
                        // throw;
                    }
                }
            }

            {
                if (string.IsNullOrEmpty(password))
                {
                    return;
                }

                var command    = $"set vdir /vdir.name:\"{virtualDirectory.LocationPath()}\" /password:{password} /apphostconfig:\"{FileName}\"";
                var resultFile = Path.GetTempFileName();
                using var process = new Process
                      {
                          StartInfo = new ProcessStartInfo
                          {
                              FileName        = "cmd",
                              Arguments       = $"/c \"\"{CertificateInstallerLocator.FileName}\" /verb:appcmd /launcher:\"{appcmd}\" /resultFile:{resultFile} /input:\"{command}\"\"",
                              CreateNoWindow  = true,
                              WindowStyle     = ProcessWindowStyle.Hidden,
                              Verb            = "runas",
                              UseShellExecute = true
                          }
                      };
                try
                {
                    process.Start();
                    process.WaitForExit();
                    if (process.ExitCode != 0)
                    {
                        var message = File.ReadAllText(resultFile);
                        File.Delete(resultFile);
                        throw new Exception($"{process.ExitCode} {message}");
                    }

                    var message1 = File.ReadAllText(resultFile);
                }
                catch (Win32Exception ex)
                {
                    // elevation is cancelled.
                    if (ex.NativeErrorCode != NativeMethods.ErrorCancelled)
                    {
                        RollbarLocator.RollbarInstance.Error(ex, new Dictionary <string, object> {
                            { "native", ex.NativeErrorCode }
                        });
                        // throw;
                    }
                }
            }
        }
		public VirtualDirectoryDesiredState(VirtualDirectory VirtualDirectory, string siteName, string webApplicationName)
		{
			Initialize(VirtualDirectory, siteName, webApplicationName);
		}
Ejemplo n.º 6
0
 internal virtual void SetPassword(VirtualDirectory virtualDirectory, string password)
 {
 }
Ejemplo n.º 7
0
        public static void DeserializeVirtualDirectoryProperties(VirtualDirectory vDir, PropertyBag bag)
        {
            foreach (int num in bag.ModifiedKeys)
            {
                switch (num)
                {
					case FtpSiteGlobals.VirtualDirectory_PhysicalPath:
						vDir.PhysicalPath = (string)bag[num];
                        break;
					case FtpSiteGlobals.VirtualDirectory_UserName:
                        if (PasswordExistsAndSet(bag))
                        {
                            string str2 = (string)bag[num];
                            if (!String.IsNullOrEmpty(str2))
								vDir.UserName = str2;
                        }
                        break;
					case FtpSiteGlobals.VirtualDirectory_Password:
                        if (PasswordExistsAndSet(bag))
                        {
							string str3 = (string)bag[FtpSiteGlobals.VirtualDirectory_Password];
                            if (String.IsNullOrEmpty(str3))
								goto PASS_DELETE;
							//
                            vDir.Password = str3;
                        }
                        break;
                }
                vDir.UserName = string.Empty;
            PASS_DELETE:
                vDir.GetAttribute("password").Delete();
            }
        }
Ejemplo n.º 8
0
        internal override void SetPassword(VirtualDirectory virtualDirectory, string password)
        {
            var directory = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
                "IIS Express");

            if (!Directory.Exists(directory))
            {
                // IMPORTANT: for x86 IIS 7 Express
                directory = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
                    "IIS Express");
                if (!Directory.Exists(directory))
                {
                    // IMPORTANT: fallback to default password setting. Should throw encryption exception.
                    virtualDirectory.Password = password;
                    return;
                }
            }

            var appcmd = Path.Combine(directory, "appcmd.exe");

            if (!File.Exists(appcmd))
            {
                // IMPORTANT: fallback to default password setting. Should throw encryption exception.
                virtualDirectory.Password = password;
                return;
            }

            {
                using var process = new Process
                      {
                          StartInfo = new ProcessStartInfo
                          {
                              FileName        = appcmd,
                              Arguments       = $"set vdir /vdir.name:\"{virtualDirectory.LocationPath()}\" /-password /apphostconfig:\"{FileName}\"",
                              CreateNoWindow  = true,
                              WindowStyle     = ProcessWindowStyle.Hidden,
                              Verb            = "runas",
                              UseShellExecute = true
                          }
                      };
                try
                {
                    process.Start();
                    process.WaitForExit();
                    if (process.ExitCode != 0)
                    {
                        throw new Exception(process.ExitCode.ToString());
                    }
                }
                catch (Win32Exception ex)
                {
                    // elevation is cancelled.
                    if (ex.NativeErrorCode != NativeMethods.ErrorCancelled)
                    {
                        RollbarLocator.RollbarInstance.Error(ex, new Dictionary <string, object> {
                            { "native", ex.NativeErrorCode }
                        });
                        // throw;
                    }
                }
            }

            {
                using var process = new Process
                      {
                          StartInfo = new ProcessStartInfo
                          {
                              FileName        = appcmd,
                              Arguments       = $"set vdir /vdir.name:\"{virtualDirectory.LocationPath()}\" /password:{password} /apphostconfig:\"{FileName}\"",
                              CreateNoWindow  = true,
                              WindowStyle     = ProcessWindowStyle.Hidden,
                              Verb            = "runas",
                              UseShellExecute = true
                          }
                      };
                try
                {
                    process.Start();
                    process.WaitForExit();
                    if (process.ExitCode != 0)
                    {
                        throw new Exception(process.ExitCode.ToString());
                    }
                }
                catch (Win32Exception ex)
                {
                    // elevation is cancelled.
                    if (ex.NativeErrorCode != NativeMethods.ErrorCancelled)
                    {
                        RollbarLocator.RollbarInstance.Error(ex, new Dictionary <string, object> {
                            { "native", ex.NativeErrorCode }
                        });
                        // throw;
                    }
                }
            }
        }
 public VirtualDirectoryConfigurer(VirtualDirectory virtualDirectory)
 {
     _virtualDirectory = virtualDirectory;
 }
 internal static string LocationPath(this VirtualDirectory virtualDirectory)
 {
     return(virtualDirectory.Application.Site.Name + virtualDirectory.PathToSite());
 }
 internal static string PathToSite(this VirtualDirectory virtualDirectory)
 {
     return(virtualDirectory.Application.IsRoot()
         ? virtualDirectory.Path
         : virtualDirectory.Application.Path + virtualDirectory.Path);
 }
Ejemplo n.º 12
0
        internal override void SetPassword(VirtualDirectory virtualDirectory, string password)
        {
            var appcmd = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "inetsrv", "appcmd.exe");

            if (!File.Exists(appcmd))
            {
                // IMPORTANT: fallback to default password setting. Should throw encryption exception.
                virtualDirectory.Password = password;
                return;
            }

            // IMPORTANT: save vdir to config file.
            {
                var command    = $"set vdir /vdir.name:\"{virtualDirectory.LocationPath()}\" /-password";
                var resultFile = Path.GetTempFileName();
                using var process = new Process
                      {
                          StartInfo = new ProcessStartInfo
                          {
                              FileName        = "cmd",
                              Arguments       = $"/c \"\"{CertificateInstallerLocator.FileName}\" /verb:appcmd /launcher:\"{appcmd}\" /resultFile:{resultFile} /input:\"{command}\"\"",
                              CreateNoWindow  = true,
                              WindowStyle     = ProcessWindowStyle.Hidden,
                              Verb            = "runas",
                              UseShellExecute = true
                          }
                      };
                try
                {
                    process.Start();
                    process.WaitForExit();
                    if (process.ExitCode != 0)
                    {
                        var message = File.ReadAllText(resultFile);
                        File.Delete(resultFile);
                        throw new Exception($"{process.ExitCode} {message}");
                    }
                }
                catch (Win32Exception ex)
                {
                    // elevation is cancelled.
                    if (ex.NativeErrorCode != (int)Windows.Win32.Foundation.WIN32_ERROR.ERROR_CANCELLED && ex.NativeErrorCode != (int)Windows.Win32.Foundation.WIN32_ERROR.ERROR_ACCESS_DISABLED_BY_POLICY)
                    {
                        RollbarLocator.RollbarInstance.Error(ex, new Dictionary <string, object> {
                            { "native", ex.NativeErrorCode }
                        });
                        // throw;
                    }
                }
            }

            {
                if (string.IsNullOrEmpty(password))
                {
                    return;
                }

                var command    = $"set vdir /vdir.name:\"{virtualDirectory.LocationPath()}\" /password:{password}";
                var resultFile = Path.GetTempFileName();
                using var process = new Process
                      {
                          StartInfo = new ProcessStartInfo
                          {
                              FileName        = "cmd",
                              Arguments       = $"/c \"\"{CertificateInstallerLocator.FileName}\" /verb:appcmd /launcher:\"{appcmd}\" /resultFile:{resultFile} /input:\"{command}\"\"",
                              CreateNoWindow  = true,
                              WindowStyle     = ProcessWindowStyle.Hidden,
                              Verb            = "runas",
                              UseShellExecute = true
                          }
                      };
                try
                {
                    process.Start();
                    process.WaitForExit();
                    if (process.ExitCode != 0)
                    {
                        var message = File.ReadAllText(resultFile);
                        File.Delete(resultFile);
                        throw new Exception($"{process.ExitCode} {message}");
                    }
                }
                catch (Win32Exception ex)
                {
                    // elevation is cancelled.
                    if (ex.NativeErrorCode != (int)Windows.Win32.Foundation.WIN32_ERROR.ERROR_CANCELLED && ex.NativeErrorCode != (int)Windows.Win32.Foundation.WIN32_ERROR.ERROR_ACCESS_DISABLED_BY_POLICY)
                    {
                        RollbarLocator.RollbarInstance.Error(ex, new Dictionary <string, object> {
                            { "native", ex.NativeErrorCode }
                        });
                        // throw;
                    }
                }
            }
        }
        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;
        }
Ejemplo n.º 14
0
 private void loadVirtualDirectory()
 {
     using (var iis = ServerManager.OpenRemote("localhost"))
     {
         var site = iis.Sites[WebSiteName];
         var appPath = "/" + VirtualDirectory;
         _application = site.Applications[appPath];
         _virtualDirectory = _application.VirtualDirectories["/"];
         _appPool = iis.ApplicationPools[_application.ApplicationPoolName];
     }
 }