Inheritance: ConfigurationElement
Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
        public virtual Application CreateApplication(string appName, Site site, string Path, string physicsPath, string appPoolName)
        {
            try
            {
                Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();
                Application newApp = site.Applications[Path];
                if (newApp != null)
                {
                    site.Applications.Remove(newApp);                                    //delete this application
                    config.RemoveLocationPath(string.Format("{0}{1}", site.Name, Path)); //delete the node of the applicationHostConfig.config file with this application
                }
                newApp = site.Applications.Add(Path, physicsPath);
                newApp.ApplicationPoolName = appPoolName;

                //开启目录浏览
                string path = "system.webServer/directoryBrowse";//the attribue path in the applictionHostConfig.config file.
                Microsoft.Web.Administration.ConfigurationSection dbS = config.GetSection(path, string.Format("{0}{1}", site.Name, Path));
                dbS.Attributes["enabled"].Value = true;
                serverManager_CommitChanges();
                return(newApp);
            }
            catch (Exception error)
            {
                throw new Exception(string.Format("创建应用程序[{0}]时出错:{1}", appName, error.Message));
            }
        }
Exemplo n.º 3
0
        public static void Install(UdpInstallerOptions options)
        {
            if (options.ListenerAdapterChecked)
            {
                WebAdmin.ServerManager                  sm = new WebAdmin.ServerManager();
                WebAdmin.Configuration                  wasConfiguration           = sm.GetApplicationHostConfiguration();
                WebAdmin.ConfigurationSection           section                    = wasConfiguration.GetSection(ListenerAdapterPath);
                WebAdmin.ConfigurationElementCollection listenerAdaptersCollection = section.GetCollection();
                WebAdmin.ConfigurationElement           element                    = listenerAdaptersCollection.CreateElement();
                element.GetAttribute("name").Value     = UdpConstants.Scheme;
                element.GetAttribute("identity").Value = WindowsIdentity.GetCurrent().User.Value;
                listenerAdaptersCollection.Add(element);
                sm.CommitChanges();
                wasConfiguration = null;
                sm = null;
            }

            if (options.ProtocolHandlerChecked)
            {
                Configuration    rootWebConfig = GetRootWebConfiguration();
                ProtocolsSection section       = (ProtocolsSection)rootWebConfig.GetSection(ProtocolsPath);
                ProtocolElement  element       = new ProtocolElement(UdpConstants.Scheme);

                element.ProcessHandlerType   = typeof(UdpProcessProtocolHandler).AssemblyQualifiedName;
                element.AppDomainHandlerType = typeof(UdpAppDomainProtocolHandler).AssemblyQualifiedName;
                element.Validate             = false;

                section.Protocols.Add(element);
                rootWebConfig.Save();
            }
        }
Exemplo n.º 4
0
        public static void Uninstall(UdpInstallerOptions options)
        {
            if (options.ListenerAdapterChecked)
            {
                WebAdmin.ServerManager                  sm = new WebAdmin.ServerManager();
                WebAdmin.Configuration                  wasConfiguration           = sm.GetApplicationHostConfiguration();
                WebAdmin.ConfigurationSection           section                    = wasConfiguration.GetSection(ListenerAdapterPath);
                WebAdmin.ConfigurationElementCollection listenerAdaptersCollection = section.GetCollection();

                for (int i = 0; i < listenerAdaptersCollection.Count; i++)
                {
                    WebAdmin.ConfigurationElement element = listenerAdaptersCollection[i];

                    if (string.Compare((string)element.GetAttribute("name").Value,
                                       UdpConstants.Scheme, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        listenerAdaptersCollection.RemoveAt(i);
                    }
                }

                sm.CommitChanges();
                wasConfiguration = null;
                sm = null;
            }

            if (options.ProtocolHandlerChecked)
            {
                Configuration    rootWebConfig = GetRootWebConfiguration();
                ProtocolsSection section       = (ProtocolsSection)rootWebConfig.GetSection(ProtocolsPath);
                section.Protocols.Remove(UdpConstants.Scheme);
                rootWebConfig.Save();
            }
        }
Exemplo n.º 5
0
        public static void DirectoryBrowsing(this Application app, Activation activation)
        {
            ConfigurationSection directoryBrowseSection = app.GetWebConfiguration().GetSection("system.webServer/directoryBrowse");
            var b = activation == Activation.Enable;

            directoryBrowseSection["enabled"]   = b;
            directoryBrowseSection["showFlags"] = @"Date, Time, Size, Extension";
        }
        private static void ConfigureOneToOneMappings(ConfigurationSection iisClientCertificateMappingAuthenticationSection)
        {
            var oneToOneMappings = iisClientCertificateMappingAuthenticationSection.GetCollection("oneToOneMappings");

            var oneToOneElement = oneToOneMappings.CreateElement("add");
            oneToOneElement["enabled"] = true;
            oneToOneElement["userName"] = @"ValidUsernameOfServerUser";
            oneToOneElement["password"] = @"PasswordForTheValidUser";
            oneToOneElement["certificate"] = @"Base64-Encoded-Certificate-Data";

            oneToOneMappings.Add(oneToOneElement);
        }
Exemplo n.º 7
0
 static void AllowIP(string IP)
 {
     using (ServerManager serverManager = new ServerManager())
     {
         Microsoft.Web.Administration.Configuration        config            = serverManager.GetApplicationHostConfiguration();
         Microsoft.Web.Administration.ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", "BrandsMarketing");
         ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();
         var ipAddress = ipSecurityCollection.Where(x => x["ipAddress"].ToString() == IP).SingleOrDefault();
         ipSecurityCollection.Remove(ipAddress);
         serverManager.CommitChanges();
     }
 }
        private static void ConfigureManyToOneMappings(ConfigurationSection iisClientCertificateMappingAuthenticationSection)
        {
            var manyToOneMappings = iisClientCertificateMappingAuthenticationSection.GetCollection("manyToOneMappings");

            var element = manyToOneMappings.CreateElement("add");
            element["name"] = @"Allowed Clients";
            element["enabled"] = true;
            element["permissionMode"] = @"Allow";
            element["userName"] = @"ValidUsernameOfServerUser";
            element["password"] = @"PasswordForTheValidUser";

            manyToOneMappings.Add(element);

            ConfigureCertificateRules(element);
        }
Exemplo n.º 9
0
        static void BlockIP(string IP)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                Microsoft.Web.Administration.Configuration        config            = serverManager.GetApplicationHostConfiguration();
                Microsoft.Web.Administration.ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", "BrandsMarketing");
                ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();

                ConfigurationElement addElement = ipSecurityCollection.CreateElement("add");
                addElement["ipAddress"] = IP;
                addElement["allowed"]   = false;
                ipSecurityCollection.Add(addElement);


                serverManager.CommitChanges();
            }
        }
Exemplo n.º 10
0
        private static void EnsureDefaultDocument(ServerManager iis)
        {
            IIS.Configuration        applicationHostConfiguration = iis.GetApplicationHostConfiguration();
            IIS.ConfigurationSection defaultDocumentSection       = applicationHostConfiguration.GetSection("system.webServer/defaultDocument");

            IIS.ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");

            if (filesCollection.Any(ConfigurationElementContainsHostingStart))
            {
                return;
            }

            IIS.ConfigurationElement addElement = filesCollection.CreateElement("add");
            addElement["value"] = HostingStartHtml;
            filesCollection.Add(addElement);

            iis.CommitChanges();
        }
Exemplo n.º 11
0
        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);
        }
Exemplo n.º 12
0
        static List <IPSecurity> GetBlockedIP()
        {
            List <IPSecurity> sec = new List <IPSecurity>();

            using (ServerManager serverManager = new ServerManager())
            {
                Microsoft.Web.Administration.Configuration        config            = serverManager.GetApplicationHostConfiguration();
                Microsoft.Web.Administration.ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", "BrandsMarketing");
                ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();

                foreach (var ip in ipSecurityCollection)
                {
                    if ((bool)ip["allowed"] == false)
                    {
                        sec.Add(new IPSecurity {
                            IP = ip["ipAddress"].ToString()
                        });
                    }
                }


                return(sec);
            }
        }
Exemplo n.º 13
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;
        }
Exemplo n.º 14
0
        internal bool Add(ConfigurationSection section, Location location, FileContext top)
        {
            var definition = DefinitionCache.FirstOrDefault(item => item.Path == section.ElementTagName);

            if (definition != null)
            {
                if (definition.AllowLocation == SectionGroup.KEYWORD_FALSE && location != null && location.FromTag)
                {
                    throw new ServerManagerException("Section is not allowed in location tag");
                }

                section.OverrideMode = location?.OverrideMode == null
                    ? OverrideMode.Inherit
                    : (OverrideMode)Enum.Parse(typeof(OverrideMode), location.OverrideMode);

                if (section.OverrideMode == OverrideMode.Inherit)
                {
                    var parent = location?.Path == null ? null : section.FileContext.FindSection(section.SectionPath, location.Path.GetParentLocation(), section.FileContext);
                    if (parent == null)
                    {
                        section.OverrideModeEffective = (OverrideMode)Enum.Parse(typeof(OverrideMode), definition.OverrideModeDefault);
                    }
                    else
                    {
                        if (parent.OverrideModeEffective == OverrideMode.Deny && parent.FileContext != this)
                        {
                            throw new FileLoadException(
                                      $"Filename: \\\\?\\{section.FileContext.FileName}\r\nLine number: {(section.Entity as IXmlLineInfo).LineNumber}\r\nError: This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=\"Deny\"), or set explicitly by a location tag with overrideMode=\"Deny\" or the legacy allowOverride=\"false\".\r\n\r\n");
                        }

                        section.OverrideModeEffective = parent.OverrideModeEffective;
                    }
                }
                else
                {
                    section.OverrideModeEffective = section.OverrideMode;
                }

                section.IsLocked = section.FileContext.FileName != definition.FileContext.FileName &&
                                   section.OverrideModeEffective != OverrideMode.Allow;
                section.IsLocallyStored = section.FileContext.FileName == definition.FileContext.FileName;
                top.ConfigurationSections.Add(section);
                return(true);
            }

            if (Parent != null)
            {
                var parentContext = Parent.Add(section, location, top);
                if (parentContext)
                {
                    return(true);
                }
            }

            if (definition == null)
            {
                throw new COMException(
                          $"Line number: {(section.Entity as IXmlLineInfo).LineNumber}\r\nError: The configuration section '{section.ElementTagName}' cannot be read because it is missing section definition\r\n");
            }
            else
            {
                throw new FileLoadException(
                          $"Filename: \\\\?\\{section.FileContext.FileName}\r\nLine number: {(section.Entity as IXmlLineInfo).LineNumber}\r\nError: This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=\"Deny\"), or set explicitly by a location tag with overrideMode=\"Deny\" or the legacy allowOverride=\"false\".\r\n\r\n");
            }
        }
Exemplo n.º 15
0
        private bool ParseSections(XElement element, ConfigurationElement parent, Location location)
        {
            var result = false;
            var path   = element.GetPath();
            ConfigurationElement node = null;
            var schema = FindSchema(path);
            var sec    = FindSectionSchema(path);
            var name   = element.Name.LocalName;

            if (schema != null)
            {
                if (sec != null)
                {
                    var section = new ConfigurationSection(path, sec.Root, location?.Path, this, element);
                    RootSectionGroup.Add(section, location);
                    node = section;
                }
                else
                {
                    node = schema.CollectionSchema == null
                               ? new ConfigurationElement(null, name, schema, parent, element, this)
                               : new ConfigurationElementCollection(
                        name,
                        schema,
                        parent,
                        element,
                        this);
                }

                parent?.AddChild(node);
                result = true;
            }
            else
            {
                var found = RootSectionGroup.GetSectionDefinition(path);
                if (found != null && found.Ignore && path != "system.webServer")
                {
                    return(true);
                }
            }

            foreach (var item in element.Nodes())
            {
                var child = item as XElement;
                if (child == null)
                {
                    continue;
                }

                var childAdded = ParseSections(child, node, location);
                result = result || childAdded;
            }

            if (!result && !_dontThrow && name != "location")
            {
                throw new COMException(
                          string.Format(
                              "Line number: {0}\r\nError: Unrecognized element '{1}'\r\n",
                              (element as IXmlLineInfo).LineNumber,
                              name));
            }

            return(result);
        }
Exemplo n.º 16
0
        private void context_EndRequest(object sender, EventArgs e)
        {
            HttpResponse response = HttpContext.Current.Response;
            HttpRequest  request  = HttpContext.Current.Request;

            //
            // Check for the X-Send headers
            //
            string filePath = response.Headers.Get("X-Sendfile");

            if (filePath == null)
            {
                filePath = response.Headers.Get("X-Accel-Redirect");
            }

            if (filePath != null)
            {
                //
                // Determine the file path and ready the response
                //
                if (ConfigurationManager.AppSettings["XSendDir"] != null)
                {
                    filePath = Path.Combine(ConfigurationManager.AppSettings["XSendDir"], filePath);    // if there is a base path set (file will be located above this)
                }
                else if (ConfigurationManager.AppSettings["XAccelLocation"] != null)
                {
                    filePath = filePath.Replace(ConfigurationManager.AppSettings["XAccelLocation"], ConfigurationManager.AppSettings["XAccelRoot"]);
                }

                response.Clear();                               // Clears output buffer
                response.Headers.Remove("X-Sendfile");          // Remove unwanted headers
                response.Headers.Remove("X-Accel-Redirect");


                //
                // Set the cache policy
                //
                if (ConfigurationManager.AppSettings["XSendCache"] == null)
                {
                    response.Cache.SetCacheability(HttpCacheability.NoCache);
                }
                else if (ConfigurationManager.AppSettings["XSendCache"] == "Public")
                {
                    response.Cache.SetCacheability(HttpCacheability.Public);
                }
                else
                {
                    response.Cache.SetCacheability(HttpCacheability.Private);
                }


                //
                // Get the file information and set headers appropriately
                //
                FileInfo file = new FileInfo(filePath);
                if (!file.Exists)
                {
                    throw new HttpException(404, "File_does_not_exist");
                }

                if (filePath[filePath.Length - 1] == '.')
                {
                    throw new HttpException(404, "File_does_not_exist");
                }


                response.Cache.SetLastModified(file.LastWriteTimeUtc);
                response.Headers.Remove("Content-Length");


                if (!String.IsNullOrEmpty(request.ServerVariables["HTTP_RANGE"]))
                {
                    //request for chunk
                    RangeDownload(file.FullName, HttpContext.Current);
                }
                else
                {
                    response.AddHeader("Content-Length", file.Length.ToString());
                    response.AppendHeader("Accept-Ranges", "bytes");


                    //
                    // Check if we want to detect the mime type of the current content
                    //
                    if (ConfigurationManager.AppSettings["XSendMime"] == null)
                    {
                        Microsoft.Web.Administration.ConfigurationSection           staticContentSection    = WebConfigurationManager.GetSection(HttpContext.Current, "system.webServer/staticContent");
                        Microsoft.Web.Administration.ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection();

                        var mt = staticContentCollection.Where(
                            a => a.Attributes["fileExtension"].Value.ToString().ToLower() == file.Extension.ToLower()
                            ).FirstOrDefault();

                        if (mt != null)
                        {
                            response.ContentType = mt.GetAttributeValue("mimeType").ToString();
                        }
                        else
                        {
                            response.ContentType = "application/octet-stream";
                        }
                    }


                    //
                    // Set a content disposition if it is not already set by the application
                    //
                    if (response.Headers["Content-Disposition"] == null)
                    {
                        response.AppendHeader("Content-Disposition", "inline;filename=" + file.Name);
                    }


                    //
                    //  Send the file without loading it into memory
                    //
                    response.TransmitFile(file.FullName);
                }
            }
        }
        internal bool Add(ConfigurationSection section)
        {
            var index = section.ElementTagName.IndexOf(Path, StringComparison.Ordinal);
            if (index != 0)
            {
                return false;
            }

            if (this.Path.Length != 0)
            {
                if (section.ElementTagName.Length != this.Path.Length && section.ElementTagName[this.Path.Length] != '/')
                {
                    return false;
                }
            }

            var definition = Sections.FirstOrDefault(item => item.Path == section.ElementTagName);
            if (definition != null)
            {
                if (definition.AllowLocation == KEYWORD_FALSE && section.Location != null)
                {
                    throw new ServerManagerException("Section is not allowed in location tag");
                }

                section.OverrideMode = OverrideMode.Inherit;
                section.OverrideModeEffective =
                    (OverrideMode)Enum.Parse(typeof(OverrideMode), definition.OverrideModeDefault);

                section.IsLocked = section.FileContext.FileName != definition.FileContext.FileName
                                   && section.OverrideModeEffective != OverrideMode.Allow;
                section.IsLocallyStored = section.FileContext.FileName == definition.FileContext.FileName;
                ConfigurationSections.Add(section);
                return true;
            }

            if (SectionGroups.Select(@group => @group.Add(section)).Any(result => result))
            {
                return true;
            }

            if (section.SectionPath == "configProtectedData")
            {
                ConfigurationSections.Add(section);
                return true;
            }

            throw new FileLoadException(string.Format(
                "Filename: \\\\?\\{0}\r\nLine number: {1}\r\nError: This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=\"Deny\"), or set explicitly by a location tag with overrideMode=\"Deny\" or the legacy allowOverride=\"false\".\r\n\r\n",
                section.FileContext.FileName,
                (section.Entity as IXmlLineInfo).LineNumber));
        }
        private ConfigurationSection CreateSection(string sectionPath, string locationPath, FileContext core, FileContext top)
        {
            var index = sectionPath.IndexOf(Path, StringComparison.Ordinal);
            if (index != 0)
            {
                return null;
            }

            if (this.Path.Length != 0)
            {
                if (sectionPath.Length != this.Path.Length && sectionPath[this.Path.Length] != '/')
                {
                    return null;
                }
            }

            var definition = Sections.FirstOrDefault(item => item.Path == sectionPath);
            if (definition?.Schema != null)
            {
                var section = new ConfigurationSection(sectionPath, definition.Schema.Root, locationPath,
                    top, null);
                section.OverrideMode = OverrideMode.Inherit;
                section.OverrideModeEffective =
                    (OverrideMode)Enum.Parse(typeof(OverrideMode), definition.OverrideModeDefault);
                section.IsLocked = section.FileContext.FileName != definition.FileContext.FileName && section.OverrideModeEffective != OverrideMode.Allow;
                section.IsLocallyStored = section.FileContext.FileName == definition.FileContext.FileName;
                ConfigurationSections.Add(section);
                return section;
            }

            foreach (SectionGroup group in SectionGroups)
            {
                var created = group.CreateSection(sectionPath, locationPath, core, top);
                if (created != null)
                {
                    return created;
                }
            }

            var sectionBasedOnParent = core.Parent?.RootSectionGroup.CreateSection(sectionPath, locationPath, core.Parent, top);
            return sectionBasedOnParent;
        }
Exemplo n.º 19
0
        private bool ParseSections(XElement element, ConfigurationElement parent, Location location)
        {
            var result = false;
            var path   = element.GetPath();
            ConfigurationElement node = null;
            var schema = FindSchema(path);
            var sec    = FindSectionSchema(path);
            var name   = element.Name.LocalName;

            if (schema != null)
            {
                if (sec != null)
                {
                    var section = new ConfigurationSection(path, sec.Root, location?.Path, this, element);
                    RootSectionGroup.Add(section, location);
                    node = section;
                }
                else
                {
                    node = schema.CollectionSchema == null
                               ? new ConfigurationElement(null, name, schema, parent, element, this)
                               : new ConfigurationElementCollection(
                        name,
                        schema,
                        parent,
                        element,
                        this);
                }

                parent?.AddChild(node);
                result = true;
            }
            else
            {
                var found = RootSectionGroup.GetSectionDefinition(path);
                if (found != null && found.Ignore && path != "system.webServer")
                {
                    return(true);
                }
            }

            foreach (var item in element.Nodes())
            {
                var child = item as XElement;
                if (child == null)
                {
                    continue;
                }

                var childAdded = ParseSections(child, node, location);
                result = result || childAdded;
            }

            if (!result && !_dontThrow && name != "location")
            {
                string link = null;
                string oob  = null;
                if (path.StartsWith("system.webServer/aspNetCore/"))
                {
                    oob  = "ASP.NET Core Module (system.webServer/aspNetCore/)";
                    link = "https://docs.microsoft.com/en-us/aspnet/core/publishing/iis?tabs=aspnetcore2x#install-the-net-core-windows-server-hosting-bundle";
                }
                else if (path.StartsWith("system.webServer/rewrite/"))
                {
                    oob  = "URL Rewrite Module (system.webServer/rewrite/)";
                    link = "https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/using-the-url-rewrite-module#where-to-get-the-url-rewrite-module";
                }
                else if (path.StartsWith("system.webServer/webFarms/"))
                {
                    oob  = "Application Request Routing Module (system.webServer/webFarms/)";
                    link = "https://docs.microsoft.com/en-us/iis/extensions/configuring-application-request-routing-arr/define-and-configure-an-application-request-routing-server-farm#prerequisites";
                }

                var exception = new COMException(
                    string.Format(
                        "Line number: {0}\r\nError: Unrecognized element '{1}'\r\n",
                        (element as IXmlLineInfo).LineNumber,
                        name));
                if (oob != null)
                {
                    exception.Data.Add("oob", oob);
                    exception.Data.Add("link", link);
                }

                throw exception;
            }

            return(result);
        }
Exemplo n.º 20
0
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            string targetDir  = Context.Parameters[Argument.TargetDir].TrimEnd('\\');
            string configFile = Path.Combine(targetDir, Assembly.GetExecutingAssembly().Location + ".config");

            System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(configFile);

            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);

            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(delegate(object sender, ResolveEventArgs args)
            {
                return(Assembly.LoadFile(Path.Combine(targetDir, args.Name + ".dll")));
            });

            UhuruSection section = (UhuruSection)config.GetSection("uhuru");

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.Capacity]))
            {
                section.Service.Capacity = int.Parse(Context.Parameters[Argument.Capacity], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.BaseDir]))
            {
                section.Service.BaseDir = Context.Parameters[Argument.BaseDir];
                if (!Directory.Exists(section.Service.BaseDir))
                {
                    Directory.CreateDirectory(section.Service.BaseDir);
                }
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.Index]))
            {
                section.Service.Index = int.Parse(Context.Parameters[Argument.Index], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.StatusPort]))
            {
                int port = Convert.ToInt32(Context.Parameters[Argument.StatusPort], CultureInfo.InvariantCulture);
                section.Service.StatusPort = port;
                if (port != 0)
                {
                    FirewallTools.OpenPort(port, "FileService Status");
                }
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.LocalDb]))
            {
                section.Service.LocalDB = Context.Parameters[Argument.LocalDb];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.LocalRoute]))
            {
                section.Service.LocalRoute = Context.Parameters[Argument.LocalRoute];
            }
            else
            {
                string ip = string.Empty;
                foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                {
                    if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ip = address.ToString();
                        break;
                    }
                }

                section.Service.LocalRoute = ip;
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.Mbus]))
            {
                section.Service.MBus = Context.Parameters[Argument.Mbus];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.MigrationNfs]))
            {
                section.Service.MigrationNFS = Context.Parameters[Argument.MigrationNfs];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.NodeId]))
            {
                section.Service.NodeId = Context.Parameters[Argument.NodeId];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.ZInterval]))
            {
                section.Service.ZInterval = int.Parse(Context.Parameters[Argument.ZInterval], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.Plan]))
            {
                section.Service.Plan = Context.Parameters[Argument.Plan];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.UseVhd]))
            {
                section.Service.Uhurufs.UseVHD = bool.Parse(Context.Parameters[Argument.UseVhd]);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.MaxStorageSize]))
            {
                section.Service.Uhurufs.MaxStorageSize = long.Parse(Context.Parameters[Argument.MaxStorageSize], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.VhdFixedSize]))
            {
                section.Service.Uhurufs.VHDFixedSize = bool.Parse(Context.Parameters[Argument.VhdFixedSize]);
            }

            section.DEA = null;
            config.Save();

            int lowPort  = 5000;
            int highPort = 6000;

            using (ServerManager serverManager = new ServerManager())
            {
                Microsoft.Web.Administration.Configuration iisConfig = serverManager.GetApplicationHostConfiguration();

                Microsoft.Web.Administration.ConfigurationSection firewallSupportSection = iisConfig.GetSection("system.ftpServer/firewallSupport");
                firewallSupportSection["lowDataChannelPort"]  = lowPort;
                firewallSupportSection["highDataChannelPort"] = highPort;

                Microsoft.Web.Administration.ConfigurationSection sitesSection           = iisConfig.GetSection("system.applicationHost/sites");
                Microsoft.Web.Administration.ConfigurationElement siteDefaultsElement    = sitesSection.GetChildElement("siteDefaults");
                Microsoft.Web.Administration.ConfigurationElement ftpServerElement       = siteDefaultsElement.GetChildElement("ftpServer");
                Microsoft.Web.Administration.ConfigurationElement firewallSupportElement = ftpServerElement.GetChildElement("firewallSupport");
                firewallSupportElement["externalIp4Address"] = @"0.0.0.0";

                serverManager.CommitChanges();
            }

            FirewallTools.OpenPortRange(lowPort, highPort, "UhuruFS Ports");
        }
Exemplo n.º 21
0
        private bool ParseSections(XElement element, ConfigurationElement parent, Location location)
        {
            var result = false;
            var path   = element.GetPath();
            ConfigurationElement node = null;
            var schema = FindSchema(path);
            var sec    = FindSectionSchema(path);
            var name   = element.Name.LocalName;

            if (schema != null)
            {
                if (sec != null)
                {
                    var section = new ConfigurationSection(path, sec.Root, location?.Path, this, element);
                    Add(section, location, this);
                    node = section;
                }
                else
                {
                    node = schema.CollectionSchema == null
                               ? new ConfigurationElement(null, name, schema, parent, element, this)
                               : new ConfigurationElementCollection(
                        name,
                        schema,
                        parent,
                        element,
                        this);
                }

                parent?.AddChild(node);
                result = true;
            }
            else
            {
                var found = DefinitionCache.FirstOrDefault(item => item.Path == path);
                if (found != null)
                {
                    if (found.Ignore)
                    {
                        if (path == "runtime")
                        {
                            // examples: <runtime> in machine.config.
                            return(true);
                        }
                        else
                        {
                            if (!element.HasElements)
                            {
                                // like empty tag in web.config.
                                return(true);
                            }
                        }
                    }
                    else
                    {
                        // log4net
                        return(true);
                    }
                }
                else
                {
                    // TODO: improve performance.
                    var foundChild = DefinitionCache.FirstOrDefault(item => item.Path.StartsWith(path + '/'));
                    if (foundChild != null && !element.HasElements)
                    {
                        return(true);
                    }
                }
            }

            foreach (var item in element.Nodes())
            {
                if (!(item is XElement child))
                {
                    continue;
                }

                var childAdded = ParseSections(child, node, location);
                result = result || childAdded;
            }

            if (!result && !_doNotThrow && name != "location")
            {
                string link = null;
                string oob  = null;
                if (path.StartsWith("system.webServer/aspNetCore/"))
                {
                    oob  = "ASP.NET Core Module (system.webServer/aspNetCore/)";
                    link = "https://docs.microsoft.com/en-us/aspnet/core/publishing/iis?tabs=aspnetcore2x#install-the-net-core-windows-server-hosting-bundle";
                }
                else if (path.StartsWith("system.webServer/rewrite/"))
                {
                    oob  = "URL Rewrite Module (system.webServer/rewrite/)";
                    link = "https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/using-the-url-rewrite-module#where-to-get-the-url-rewrite-module";
                }
                else if (path.StartsWith("system.webServer/webFarms/"))
                {
                    oob  = "Application Request Routing Module (system.webServer/webFarms/)";
                    link = "https://docs.microsoft.com/en-us/iis/extensions/configuring-application-request-routing-arr/define-and-configure-an-application-request-routing-server-farm#prerequisites";
                }
                else if (path.StartsWith("system.webServer/httpPlatform/"))
                {
                    oob  = "HttpPlatformHandler Module (system.webServer/httpPlatform/)";
                    link = "https://docs.microsoft.com/en-us/iis/extensions/httpplatformhandler/httpplatformhandler-configuration-reference";
                }

                var exception = new COMException(
                    $"Line number: {(element as IXmlLineInfo).LineNumber}\r\nError: Unrecognized element '{name}'\r\n");
                if (oob != null)
                {
                    exception.Data.Add("oob", oob);
                    exception.Data.Add("link", link);
                }

                throw exception;
            }

            return(result);
        }
Exemplo n.º 22
0
        public void RunDeploy(String[] args)
        {
            if (args.Length < 3)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: 3 Arguments are required in order to use the -deploy mode, type rdfWebDeploy -help to see usage summary");
                return;
            }
            if (args.Length > 3)
            {
                if (!this.SetOptions(args.Skip(3).ToArray()))
                {
                    Console.Error.WriteLine("rdfWebDeploy: Deployment aborted since one/more options were not valid");
                    return;
                }
            }

            if (this._noLocalIIS)
            {
                Console.WriteLine("rdfWebDeploy: No Local IIS Server available so switching to -xmldeploy mode");
                XmlDeploy xdeploy = new XmlDeploy();
                xdeploy.RunXmlDeploy(args);
                return;
            }

            //Define the Server Manager object
            Admin.ServerManager manager = null;

            try
            {
                //Connect to the Server Manager
                if (!this._noIntegratedRegistration)
                {
                    manager = new Admin.ServerManager();
                }

                //Open the Configuration File
                System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(args[1], this._site);
                Console.Out.WriteLine("rdfWebDeploy: Opened the Web.config file for the specified Web Application");

                //Detect Folders
                String appFolder     = Path.GetDirectoryName(config.FilePath);
                String binFolder     = Path.Combine(appFolder, "bin\\");
                String appDataFolder = Path.Combine(appFolder, "App_Data\\");
                if (!Directory.Exists(binFolder))
                {
                    Directory.CreateDirectory(binFolder);
                    Console.WriteLine("rdfWebDeploy: Created a bin\\ directory for the web application");
                }
                if (!Directory.Exists(appDataFolder))
                {
                    Directory.CreateDirectory(appDataFolder);
                    Console.WriteLine("rdfWebDeploy: Created an App_Data\\ directory for the web application");
                }

                //Deploy dotNetRDF and required DLLs to the bin directory of the application
                String sourceFolder       = RdfWebDeployHelper.ExecutablePath;
                IEnumerable <String> dlls = RdfWebDeployHelper.RequiredDLLs;
                if (this._sql)
                {
                    dlls = dlls.Concat(RdfWebDeployHelper.RequiredSqlDLLs);
                }
                if (this._virtuoso)
                {
                    dlls = dlls.Concat(RdfWebDeployHelper.RequiredVirtuosoDLLs);
                }
                if (this._fulltext)
                {
                    dlls = dlls.Concat(RdfWebDeployHelper.RequiredFullTextDLLs);
                }
                foreach (String dll in dlls)
                {
                    if (File.Exists(Path.Combine(sourceFolder, dll)))
                    {
                        File.Copy(Path.Combine(sourceFolder, dll), Path.Combine(binFolder, dll), true);
                        Console.WriteLine("rdfWebDeploy: Deployed " + dll + " to the web applications bin directory");
                    }
                    else
                    {
                        Console.Error.WriteLine("rdfWebDeploy: Error: Required DLL " + dll + " which needs deploying to the web applications bin directory could not be found");
                        return;
                    }
                }

                //Deploy the configuration file to the App_Data directory
                if (File.Exists(args[2]))
                {
                    File.Copy(args[2], Path.Combine(appDataFolder, args[2]), true);
                    Console.WriteLine("rdfWebDeploy: Deployed the configuration file to the web applications App_Data directory");
                }
                else if (!File.Exists(Path.Combine(appDataFolder, args[2])))
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: Unable to continue deployment as the configuration file " + args[2] + " could not be found either locally for deployment to the App_Data folder or already present in the App_Data folder");
                    return;
                }

                //Set the AppSetting for the configuration file
                config.AppSettings.Settings.Remove("dotNetRDFConfig");
                config.AppSettings.Settings.Add("dotNetRDFConfig", "~/App_Data/" + Path.GetFileName(args[2]));
                Console.WriteLine("rdfWebDeploy: Set the \"dotNetRDFConfig\" appSetting to \"~/App_Data/" + Path.GetFileName(args[2]) + "\"");

                //Now load the Configuration Graph from the App_Data folder
                Graph g = new Graph();
                FileLoader.Load(g, Path.Combine(appDataFolder, args[2]));

                Console.WriteLine("rdfWebDeploy: Successfully deployed required DLLs and appSettings");
                Console.WriteLine();

                //Get the sections of the Configuration File we want to edit
                HttpHandlersSection handlersSection = config.GetSection("system.web/httpHandlers") as HttpHandlersSection;
                if (handlersSection == null)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Handlers section of the web applications Web.Config file");
                    return;
                }

                //Detect Handlers from the Configution Graph and deploy
                IUriNode rdfType     = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
                IUriNode dnrType     = g.CreateUriNode(new Uri(ConfigurationLoader.PropertyType));
                IUriNode httpHandler = g.CreateUriNode(new Uri(ConfigurationLoader.ClassHttpHandler));

                //Deploy for IIS Classic Mode
                if (!this._noClassicRegistration)
                {
                    Console.WriteLine("rdfWebDeploy: Attempting deployment for IIS Classic Mode");
                    foreach (INode n in g.GetTriplesWithPredicateObject(rdfType, httpHandler).Select(t => t.Subject))
                    {
                        if (n.NodeType == NodeType.Uri)
                        {
                            String handlerPath = ((IUriNode)n).Uri.AbsolutePath;
                            INode  type        = g.GetTriplesWithSubjectPredicate(n, dnrType).Select(t => t.Object).FirstOrDefault();
                            if (type == null)
                            {
                                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as there is no dnr:type property specified");
                                continue;
                            }
                            if (type.NodeType == NodeType.Literal)
                            {
                                String handlerType = ((ILiteralNode)type).Value;

                                //First remove any existing registration
                                handlersSection.Handlers.Remove("*", handlerPath);

                                //Then add the new registration
                                handlersSection.Handlers.Add(new HttpHandlerAction(handlerPath, handlerType, "*"));

                                Console.WriteLine("rdfWebDeploy: Deployed the Handler <" + n.ToString() + "> to the web applications Web.Config file");
                            }
                            else
                            {
                                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as the value given for the dnr:type property is not a Literal");
                                continue;
                            }
                        }
                        else
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy a Handler which is not specified as a URI Node");
                        }
                    }

                    //Deploy Negotiate by File Extension if appropriate
                    if (this._negotiate)
                    {
                        HttpModulesSection modulesSection = config.GetSection("system.web/httpModules") as HttpModulesSection;
                        if (modulesSection == null)
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Modules section of the web applications Web.Config file");
                            return;
                        }
                        modulesSection.Modules.Remove("NegotiateByExtension");
                        modulesSection.Modules.Add(new HttpModuleAction("NegotiateByExtension", "VDS.RDF.Web.NegotiateByFileExtension"));
                        Console.WriteLine("rdfWebDeploy: Deployed the Negotiate by File Extension Module");
                    }

                    Console.WriteLine("rdfWebDeploy: Successfully deployed for IIS Classic Mode");
                }

                //Save the completed Configuration File
                config.Save(ConfigurationSaveMode.Minimal);
                Console.WriteLine();

                //Deploy for IIS Integrated Mode
                if (!this._noIntegratedRegistration)
                {
                    Console.WriteLine("rdfWebDeploy: Attempting deployment for IIS Integrated Mode");
                    Admin.Configuration                  adminConfig        = manager.GetWebConfiguration(this._site, args[1]);
                    Admin.ConfigurationSection           newHandlersSection = adminConfig.GetSection("system.webServer/handlers");
                    Admin.ConfigurationElementCollection newHandlers        = newHandlersSection.GetCollection();

                    foreach (INode n in g.GetTriplesWithPredicateObject(rdfType, httpHandler).Select(t => t.Subject))
                    {
                        if (n.NodeType == NodeType.Uri)
                        {
                            String handlerPath = ((IUriNode)n).Uri.AbsolutePath;
                            INode  type        = g.GetTriplesWithSubjectPredicate(n, dnrType).Select(t => t.Object).FirstOrDefault();
                            if (type == null)
                            {
                                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as there is no dnr:type property specified");
                                continue;
                            }
                            if (type.NodeType == NodeType.Literal)
                            {
                                String handlerType = ((ILiteralNode)type).Value;

                                //First remove any existing registration
                                foreach (Admin.ConfigurationElement oldReg in newHandlers.Where(el => el.GetAttributeValue("name").Equals(handlerPath)).ToList())
                                {
                                    newHandlers.Remove(oldReg);
                                }

                                //Then add the new registration
                                Admin.ConfigurationElement reg = newHandlers.CreateElement("add");
                                reg["name"] = handlerPath;
                                reg["path"] = handlerPath;
                                reg["verb"] = "*";
                                reg["type"] = handlerType;
                                newHandlers.AddAt(0, reg);

                                Console.WriteLine("rdfWebDeploy: Deployed the Handler <" + n.ToString() + "> to the web applications Web.Config file");
                            }
                            else
                            {
                                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as the value given for the dnr:type property is not a Literal");
                                continue;
                            }
                        }
                        else
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy a Handler which is not specified as a URI Node");
                        }

                        //Deploy Negotiate by File Extension if appropriate
                        if (this._negotiate)
                        {
                            Admin.ConfigurationSection newModulesSection = adminConfig.GetSection("system.webServer/modules");
                            if (newModulesSection == null)
                            {
                                Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Modules section of the web applications Web.Config file");
                                return;
                            }

                            //First remove the Old Module
                            Admin.ConfigurationElementCollection newModules = newModulesSection.GetCollection();
                            foreach (Admin.ConfigurationElement oldReg in newModules.Where(el => el.GetAttribute("name").Equals("NegotiateByExtension")).ToList())
                            {
                                newModules.Remove(oldReg);
                            }

                            //Then add the new Module
                            Admin.ConfigurationElement reg = newModules.CreateElement("add");
                            reg["name"] = "NegotiateByExtension";
                            reg["type"] = "VDS.RDF.Web.NegotiateByFileExtension";
                            newModules.AddAt(0, reg);

                            Console.WriteLine("rdfWebDeploy: Deployed the Negotiate by File Extension Module");
                        }
                    }

                    manager.CommitChanges();
                    Console.WriteLine("rdfWebDeploy: Successfully deployed for IIS Integrated Mode");
                }
            }
            catch (ConfigurationException configEx)
            {
                Console.Error.WriteLine("rdfWebDeploy: Configuration Error: " + configEx.Message);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: " + ex.Message);
                Console.Error.WriteLine(ex.StackTrace);
            }
            finally
            {
                if (manager != null)
                {
                    manager.Dispose();
                }
            }
        }
Exemplo n.º 23
0
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            string targetDir  = Context.Parameters[Arguments.TargetDir].TrimEnd('\\');
            string configFile = Path.Combine(targetDir, Assembly.GetExecutingAssembly().Location + ".config");

            System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(configFile);
            System.Configuration.Configuration        config  = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);

            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(delegate(object sender, ResolveEventArgs args)
            {
                return(Assembly.LoadFile(Path.Combine(targetDir, args.Name + ".dll")));
            });

            UhuruSection section = (UhuruSection)config.GetSection("uhuru");

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.BaseDir]))
            {
                section.DEA.BaseDir = Context.Parameters[Arguments.BaseDir];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.EnforceUlimit]))
            {
                section.DEA.EnforceUsageLimit = Convert.ToBoolean(Context.Parameters[Arguments.EnforceUlimit], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.FilerPort]))
            {
                int port = Convert.ToInt32(Context.Parameters[Arguments.FilerPort], CultureInfo.InvariantCulture);
                section.DEA.FilerPort = port;
                FirewallTools.OpenPort(port, "DEA FileServer");
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.StatusPort]))
            {
                int port = Convert.ToInt32(Context.Parameters[Arguments.StatusPort], CultureInfo.InvariantCulture);
                section.DEA.StatusPort = port;
                FirewallTools.OpenPort(port, "DEA Status");
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.ForceHttpSharing]))
            {
                section.DEA.ForceHttpSharing = Convert.ToBoolean(Context.Parameters[Arguments.ForceHttpSharing], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.HeartBeatInterval]))
            {
                section.DEA.HeartbeatInterval = Convert.ToInt32(Context.Parameters[Arguments.HeartBeatInterval], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.LocalRoute]))
            {
                section.DEA.LocalRoute = Context.Parameters[Arguments.LocalRoute];
            }
            else
            {
                string ip = string.Empty;
                foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                {
                    if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ip = address.ToString();
                        break;
                    }
                }

                section.DEA.LocalRoute = ip;
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MaxMemory]))
            {
                section.DEA.MaxMemory = Convert.ToInt32(Context.Parameters[Arguments.MaxMemory], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MessageBus]))
            {
                section.DEA.MessageBus = Context.Parameters[Arguments.MessageBus];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MultiTenant]))
            {
                section.DEA.Multitenant = Convert.ToBoolean(Context.Parameters[Arguments.MultiTenant], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.Secure]))
            {
                section.DEA.Secure = Convert.ToBoolean(Context.Parameters[Arguments.Secure], CultureInfo.InvariantCulture);
            }

            section.Service = null;
            config.Save();

            using (ServerManager serverManager = new ServerManager())
            {
                Microsoft.Web.Administration.Configuration authenticationConfig = serverManager.GetApplicationHostConfiguration();

                Microsoft.Web.Administration.ConfigurationSection anonymousAuthenticationSection = authenticationConfig.GetSection("system.webServer/security/authentication/anonymousAuthentication");
                anonymousAuthenticationSection["enabled"]     = true;
                anonymousAuthenticationSection["userName"]    = string.Empty;
                anonymousAuthenticationSection["password"]    = string.Empty;
                anonymousAuthenticationSection["logonMethod"] = @"ClearText";

                serverManager.CommitChanges();
            }
        }
Exemplo n.º 24
0
        private static void RegisterPhpDefaultDocument(ConfigurationSection defaultDocument)
        {
            ConfigurationElement defaultFiles = defaultDocument.GetChildElement("files");
            ConfigurationElementCollection filesCollection = defaultFiles.GetCollection();

            // search index.php in default documents
            bool indexPhpPresent = false;
            foreach (ConfigurationElement configurationElement in filesCollection)
            {
                string value = configurationElement.GetAttributeValue("value") as string;
                if (!string.IsNullOrEmpty(value))
                {
                    if (string.Equals(value, "index.php", StringComparison.OrdinalIgnoreCase))
                    {
                        indexPhpPresent = true;
                        break;
                    }
                }
            }

            if (!indexPhpPresent)
            {
                // add index.php
                ConfigurationElement indexPhp = filesCollection.CreateElement();
                indexPhp.SetAttributeValue("value", "index.php");
                filesCollection.AddAt(0, indexPhp);
            }
        }
        private void context_EndRequest(object sender, EventArgs e)
        {
            HttpResponse response = HttpContext.Current.Response;
            HttpRequest  request  = HttpContext.Current.Request;

            //
            // Check for the X-Send headers
            //
            bool remove = false;
            // we check for temp first, so any software that wants to use it can, as a fallback,
            // also set the regular x-sendfile header in case on that system this version of the
            // dll is not deployed
            string filePath = response.Headers.Get("X-Sendfile-Temporary");

            if (filePath == null)
            {
                filePath = response.Headers.Get("X-Sendfile");
            }
            else
            {
                remove = true;
            }
            if (filePath == null)
            {
                filePath = response.Headers.Get("X-Accel-Redirect");
            }

            if (filePath != null)
            {
                //
                // Determine the file path and ready the response
                //
                if (ConfigurationManager.AppSettings["XSendDir"] != null)
                {
                    filePath = Path.Combine(ConfigurationManager.AppSettings["XSendDir"], filePath);    // if there is a base path set (file will be located above this)
                }
                else if (ConfigurationManager.AppSettings["XAccelLocation"] != null)
                {
                    filePath = filePath.Replace(ConfigurationManager.AppSettings["XAccelLocation"], ConfigurationManager.AppSettings["XAccelRoot"]);
                }

                response.Clear();                               // Clears output buffer
                response.Headers.Remove("X-Sendfile");          // Remove unwanted headers
                response.Headers.Remove("X-Sendfile-Temporary");
                response.Headers.Remove("X-Accel-Redirect");


                //
                // Set the cache policy
                //
                if (ConfigurationManager.AppSettings["XSendCache"] == null)
                {
                    response.Cache.SetCacheability(HttpCacheability.NoCache);
                }
                else if (ConfigurationManager.AppSettings["XSendCache"] == "Public")
                {
                    response.Cache.SetCacheability(HttpCacheability.Public);
                }
                else
                {
                    response.Cache.SetCacheability(HttpCacheability.Private);
                }


                //
                // Get the file information and set headers appropriately
                //
                FileInfo file = new FileInfo(filePath);
                if (!file.Exists)
                {
                    throw new HttpException(404, "File_does_not_exist");
                }

                if (filePath[filePath.Length - 1] == '.')
                {
                    throw new HttpException(404, "File_does_not_exist");
                }


                response.Cache.SetLastModified(file.LastWriteTimeUtc);
                response.Headers.Remove("Content-Length");


                if (!String.IsNullOrEmpty(request.ServerVariables["HTTP_RANGE"]))
                {
                    //request for chunk
                    RangeDownload(file.FullName, HttpContext.Current);
                }
                else
                {
                    response.AddHeader("Content-Length", file.Length.ToString());
                    response.AppendHeader("Accept-Ranges", "bytes");


                    //
                    // Check if we want to detect the mime type of the current content
                    //
                    if (ConfigurationManager.AppSettings["XSendMime"] == null)
                    {
                        Microsoft.Web.Administration.ConfigurationSection           staticContentSection    = WebConfigurationManager.GetSection(HttpContext.Current, "system.webServer/staticContent");
                        Microsoft.Web.Administration.ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection();

                        var mt = staticContentCollection.Where(
                            a => a.Attributes["fileExtension"].Value.ToString().ToLower() == file.Extension.ToLower()
                            ).FirstOrDefault();

                        if (mt != null)
                        {
                            response.ContentType = mt.GetAttributeValue("mimeType").ToString();
                        }
                        else
                        {
                            response.ContentType = "application/octet-stream";
                        }
                    }


                    //
                    // Set a content disposition if it is not already set by the application
                    //
                    if (response.Headers["Content-Disposition"] == null)
                    {
                        response.AppendHeader("Content-Disposition", "inline;filename=" + file.Name);
                    }


                    //
                    //  Send the file without loading it into memory
                    //
                    response.TransmitFile(file.FullName);
                    if (remove)
                    {
                        // note that the little Flush below causes the full file to load into
                        // IIS memory but we need that be able to delete it
                        // Note that on many concurrent requests, that means each request
                        // will load the full output into memory, which wil remain there for
                        // a while because the client needs time to download. Unfortunately
                        // I found no way to dispose of the file once the last byte has been
                        // sent
                        response.Flush();
                        File.Delete(file.FullName);
                    }
                }
            }
        }
Exemplo n.º 26
0
        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)
                    {
                    }
                }
            }
        }
        private void context_EndRequest(object sender, EventArgs e)
        {
            HttpResponse response = HttpContext.Current.Response;
            HttpRequest  request  = HttpContext.Current.Request;

            //
            // Check for the X-Send headers
            //
            string filePath = response.Headers.Get("X-Sendfile");

            if (filePath == null)
            {
                filePath = response.Headers.Get("X-Accel-Redirect");
            }

            if (filePath != null)
            {
                //
                // Determine the file path and ready the response
                //
                if (ConfigurationManager.AppSettings["XSendDir"] != null)
                {
                    filePath = Path.Combine(ConfigurationManager.AppSettings["XSendDir"], filePath);    // if there is a base path set (file will be located above this)
                }
                else if (ConfigurationManager.AppSettings["XAccelLocation"] != null)
                {
                    filePath = filePath.Replace(ConfigurationManager.AppSettings["XAccelLocation"], ConfigurationManager.AppSettings["XAccelRoot"]);
                }

                response.Clear();                               // Clears output buffer
                response.Headers.Remove("X-Sendfile");          // Remove unwanted headers
                response.Headers.Remove("X-Accel-Redirect");


                //
                // Set the cache policy
                //
                if (ConfigurationManager.AppSettings["XSendCache"] == null)
                {
                    response.Cache.SetCacheability(HttpCacheability.NoCache);
                }
                else if (ConfigurationManager.AppSettings["XSendCache"] == "Public")
                {
                    response.Cache.SetCacheability(HttpCacheability.Public);
                }
                else
                {
                    response.Cache.SetCacheability(HttpCacheability.Private);
                }


                //
                // Get the file information and set headers appropriately
                //
                if (!FileUtil.FileExists(filePath))
                {
                    throw new HttpException(404, "File_does_not_exist");
                }
                if (filePath[filePath.Length - 1] == '.')
                {
                    throw new HttpException(404, "File_does_not_exist");
                }
                FileInfo file = new FileInfo(filePath);
                response.Cache.SetLastModified(file.LastWriteTimeUtc);
                response.Headers.Remove("Content-Length");

                DateTime dateTime = new DateTime(file.LastWriteTime.Year, file.LastWriteTime.Month, file.LastWriteTime.Day, file.LastWriteTime.Hour, file.LastWriteTime.Minute, file.LastWriteTime.Second, 0);
                DateTime now      = DateTime.Now;
                string   range    = request.Headers["Range"];

                //
                // Call into .net static file handler to do the heavy lifting for us
                //  Massive hacks. Should work for all version of .net
                //
                // http://dotnetinside.com/framework/v2.0.50727/System.Web/StaticFileHandler
                // http://typedescriptor.net/browse/types/7243-System.Web.StaticFileHandler
                // http://stackoverflow.com/questions/7829478/how-to-execute-a-private-static-method-with-optional-parameters-via-reflection
                //
                //
                var    genEtag = typeof(System.Web.StaticFileHandler).GetMethod("GenerateETag", BindingFlags.Static | BindingFlags.NonPublic);
                string etag    = genEtag.Invoke(obj: null, parameters: new object[] { HttpContext.Current, dateTime, now });

                var rangeRequest = typeof(System.Web.StaticFileHandler).GetMethod("ProcessRangeRequest", BindingFlags.Static | BindingFlags.NonPublic);
                if (StringUtil.StringStartsWithIgnoreCase(range, "bytes") && rangeRequest.Invoke(obj: null, parameters: new object[] { HttpContext.Current, filePath, file.Length, range, etag, dateTime }))
                {
                    return;
                }
                response.AddHeader("Content-Length", file.Length.ToString());
                response.AppendHeader("Accept-Ranges", "bytes");
                response.Cache.SetIgnoreRangeRequests();


                //
                // Check if we want to detect the mime type of the current content
                //
                if (ConfigurationManager.AppSettings["XSendMime"] == null)
                {
                    Microsoft.Web.Administration.ConfigurationSection           staticContentSection    = WebConfigurationManager.GetSection(HttpContext.Current, "system.webServer/staticContent");
                    Microsoft.Web.Administration.ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection();

                    var mt = staticContentCollection.Where(
                        a => a.Attributes["fileExtension"].Value.ToString().ToLower() == file.Extension.ToLower()
                        ).FirstOrDefault();

                    if (mt != null)
                    {
                        response.ContentType = mt.GetAttributeValue("mimeType").ToString();
                    }
                    else
                    {
                        response.ContentType = "application/octet-stream";
                    }
                }


                //
                // Set a content disposition if it is not already set by the application
                //
                if (response.Headers["Content-Disposition"] == null)
                {
                    response.AppendHeader("Content-Disposition", "inline;filename=" + file.Name);
                }


                //
                //  Send the file without loading it into memory
                //
                response.TransmitFile(file.FullName);
            }
        }