Initial project's source code check-in.

This commit is contained in:
ptsurbeleu 2011-07-13 16:07:32 -07:00
commit b03b0b373f
4573 changed files with 981205 additions and 0 deletions

View file

@ -0,0 +1,92 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Authentication
{
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;
using Common;
using Utility;
using System;
using System.Globalization;
internal sealed class AnonymAuthModuleService : ConfigurationModuleService
{
public const string EnabledAttribute = "enabled";
public const string UserNameAttribute = "userName";
public const string PasswordAttribute = "password";
public PropertyBag GetAuthenticationSettings(string siteId)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var section = config.GetSection(Constants.AnonymousAuthenticationSection, siteId);
//
PropertyBag bag = new PropertyBag();
//
bag[AuthenticationGlobals.AnonymousAuthenticationUserName] = Convert.ToString(section.GetAttributeValue(UserNameAttribute));
bag[AuthenticationGlobals.AnonymousAuthenticationPassword] = Convert.ToString(section.GetAttributeValue(PasswordAttribute));
bag[AuthenticationGlobals.Enabled] = Convert.ToBoolean(section.GetAttributeValue(EnabledAttribute));
bag[AuthenticationGlobals.IsLocked] = section.IsLocked;
//
return bag;
}
}
public void SetAuthenticationSettings(string virtualPath, string userName,
string password, bool enabled)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var section = config.GetSection(Constants.AnonymousAuthenticationSection, virtualPath);
//
section.SetAttributeValue(EnabledAttribute, enabled);
section.SetAttributeValue(UserNameAttribute, userName);
section.SetAttributeValue(PasswordAttribute, password);
//
srvman.CommitChanges();
}
}
public void RemoveAuthenticationSettings(string virtualPath)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
config.RemoveLocationPath(virtualPath);
//
srvman.CommitChanges();
}
}
}
}

View file

@ -0,0 +1,81 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Authentication
{
using System;
internal static class AuthenticationGlobals
{
public const string ActiveDirectoryAuthenticationModuleName = "ActiveDirectoryAuthentication";
public const string ActiveDirectoryAuthenticationSectionName = "system.webServer/security/authentication/clientCertificateMappingAuthentication";
public const string AnonymousAuthenticationModuleName = "AnonymousAuthentication";
public const string AnonymousAuthenticationSectionName = "system.webServer/security/authentication/anonymousAuthentication";
public const string AuthenticationModuleName = "Authentication";
public const string AuthenticationSectionName = "system.web/authentication";
public const string BasicAuthenticationModuleName = "BasicAuthentication";
public const string BasicAuthenticationSectionName = "system.webServer/security/authentication/basicAuthentication";
public const string DigestAuthenticationModuleName = "DigestAuthentication";
public const string DigestAuthenticationSectionName = "system.webServer/security/authentication/digestAuthentication";
public const string PasswordProperty = "password";
public const string WindowsAuthenticationModuleName = "WindowsAuthentication";
public const string WindowsAuthenticationSectionName = "system.webServer/security/authentication/windowsAuthentication";
public const int AnonymousAuthenticationUserName = 0;
public const int AnonymousAuthenticationPassword = 1;
public const int BasicAuthenticationDefaultLogonDomain = 2;
public const int BasicAuthenticationRealm = 3;
public const int DigestAuthenticationRealm = 4;
public const int DigestAuthenticationHasDomain = 5;
public const int FormsAuthenticationLoginPageUrl = 6;
public const int FormsAuthenticationExpiration = 7;
public const int FormsAuthenticationCookieMode = 8;
public const int FormsAuthenticationCookieName = 9;
public const int FormsAuthenticationProtectionMode = 10;
public const int FormsAuthenticationRequireSsl = 11;
public const int FormsAuthenticationSlidingExpiration = 12;
public const int ActiveDirectoryAuthenticationHasSslRequirements = 13;
public const int ModuleName = 14;
public const int Enabled = 15;
public const int IsLocked = 16;
}
}

View file

@ -0,0 +1,67 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Authentication
{
using Common;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;
using System;
internal sealed class BasicAuthModuleService : ConfigurationModuleService
{
public const string EnabledAttribute = "enabled";
public void GetAuthenticationSettings(WebVirtualDirectory virtualDir)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var section = config.GetSection(Constants.BasicAuthenticationSection, virtualDir.FullQualifiedPath);
//
virtualDir.EnableBasicAuthentication = Convert.ToBoolean(section.GetAttributeValue(EnabledAttribute));
}
}
public void SetAuthenticationSettings(WebVirtualDirectory virtualDir)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var section = config.GetSection(Constants.BasicAuthenticationSection, virtualDir.FullQualifiedPath);
//
section.SetAttributeValue(EnabledAttribute, virtualDir.EnableBasicAuthentication);
//
srvman.CommitChanges();
}
}
}
}

View file

@ -0,0 +1,71 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Authentication
{
using Common;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;
using System;
internal sealed class WindowsAuthModuleService : ConfigurationModuleService
{
public const string EnabledAttribute = "enabled";
public PropertyBag GetAuthenticationSettings(string siteId)
{
PropertyBag bag = new PropertyBag();
//
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var section = config.GetSection(Constants.WindowsAuthenticationSection, siteId);
//
bag[AuthenticationGlobals.IsLocked] = section.IsLocked;
bag[AuthenticationGlobals.Enabled] = Convert.ToBoolean(section.GetAttributeValue(EnabledAttribute));
}
//
return bag;
}
public void SetEnabled(string siteId, bool enabled)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var section = config.GetSection(Constants.WindowsAuthenticationSection, siteId);
//
section.SetAttributeValue(EnabledAttribute, enabled);
//
srvman.CommitChanges();
}
}
}
}

View file

@ -0,0 +1,76 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.ClassicAsp
{
using System;
internal static class ClassicAspGlobals
{
public const int AppAllowClientDebug = 0;
public const int AppAllowDebugging = 1;
public const int BufferingOn = 2;
public const int CalcLineNumber = 3;
public const int CodePage = 4;
public const int EnableApplicationRestart = 5;
public const int EnableAspHtmlFallback = 6;
public const int EnableChunkedEncoding = 7;
public const int EnableParentPaths = 8;
public const int ErrorsToNTLog = 9;
public const int ExceptionCatchEnable = 10;
public const int Lcid = 11;
public const int LogErrorRequests = 12;
public const int RunOnEndAnonymously = 13;
public const int ScriptErrorMessage = 14;
public const int ScriptErrorSentToBrowser = 15;
public const int ScriptLanguage = 16;
public const int DiskTemplateCacheDirectory = 17;
public const int EnableTypelibCache = 18;
public const int MaxDiskTemplateCacheFiles = 19;
public const int ScriptEngineCacheMax = 20;
public const int ScriptFileCacheSize = 21;
public const int AppServiceFlags = 22;
public const int ExecuteInMta = 23;
public const int PartitionId = 24;
public const int SxsName = 25;
public const int TrackThreadingModel = 26;
public const int BufferingLimit = 27;
public const int MaxRequestEntityAllowed = 28;
public const int ProcessorThreadMax = 29;
public const int QueueConnectionTestTime = 30;
public const int QueueTimeout = 31;
public const int RequestQueueMax = 32;
public const int ScriptTimeout = 33;
public const int AllowSessionState = 34;
public const int KeepSessionIdSecure = 35;
public const int Max = 36;
public const int Timeout = 37;
public const int ReadOnly = 38;
}
}

View file

@ -0,0 +1,74 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using Microsoft.Web.Administration;
namespace WebsitePanel.Providers.Web.Iis.ClassicAsp
{
using Common;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;
using System;
internal sealed class ClassicAspModuleService : ConfigurationModuleService
{
public const string SectionName = "system.webServer/asp";
public const string EnableParentPathsAttribute = "enableParentPaths";
public PropertyBag GetClassicAspSettings(string siteId)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var aspSection = config.GetSection(SectionName, siteId);
//
PropertyBag bag = new PropertyBag();
//
bag[ClassicAspGlobals.EnableParentPaths] = Convert.ToBoolean(aspSection.GetAttributeValue(EnableParentPathsAttribute));
//
return bag;
}
}
public void SetClassicAspSettings(WebVirtualDirectory virtualDir)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var aspSection = config.GetSection(SectionName, virtualDir.FullQualifiedPath);
//
aspSection.SetAttributeValue(EnableParentPathsAttribute, virtualDir.EnableParentPaths);
//
srvman.CommitChanges();
}
}
}
}

View file

@ -0,0 +1,49 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Common
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;
public abstract class ConfigurationModuleService
{
/// <summary>
/// We'll use it in the future to implement management of web farm with shared configuration enabled
/// </summary>
/// <returns></returns>
internal ServerManager GetServerManager()
{
return new ServerManager();
}
}
}

View file

@ -0,0 +1,64 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Common
{
using Microsoft.Web.Administration;
using System;
internal sealed class FastCgiApplication : ConfigurationElement
{
private static readonly string ArgumentsAttribute = "arguments";
private static readonly string FullPathAttribute = "fullPath";
public string Arguments
{
get
{
return (string) base[ArgumentsAttribute];
}
set
{
base[ArgumentsAttribute] = value;
}
}
public string FullPath
{
get
{
return (string) base[FullPathAttribute];
}
set
{
base[FullPathAttribute] = value;
}
}
}
}

View file

@ -0,0 +1,71 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Common
{
using Microsoft.Web.Administration;
using Utility;
using System;
using System.Reflection;
internal sealed class FastCgiApplicationCollection : ConfigurationElementCollectionBase<FastCgiApplication>
{
public FastCgiApplication Add(string fullPath, string arguments)
{
FastCgiApplication element = base.CreateElement();
element.FullPath = fullPath;
if (ConfigurationUtility.ShouldPersist(element.Arguments, arguments))
{
element.Arguments = arguments;
}
return base.Add(element);
}
protected override FastCgiApplication CreateNewElement(string elementTagName)
{
return new FastCgiApplication();
}
public FastCgiApplication this[string fullPath, string arguments]
{
get
{
for (int i = 0; i < base.Count; i++)
{
FastCgiApplication application = base[i];
if (string.Equals(application.FullPath, fullPath, StringComparison.OrdinalIgnoreCase) && string.Equals(application.Arguments, arguments, StringComparison.OrdinalIgnoreCase))
{
return application;
}
}
return null;
}
}
}
}

View file

@ -0,0 +1,50 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Common
{
using Microsoft.Web.Administration;
internal sealed class FastCgiSection : ConfigurationSection
{
private FastCgiApplicationCollection _applications;
public FastCgiApplicationCollection Applications
{
get
{
if (this._applications == null)
{
this._applications = (FastCgiApplicationCollection) base.GetCollection(typeof(FastCgiApplicationCollection));
}
return this._applications;
}
}
}
}

View file

@ -0,0 +1,39 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Common
{
using System;
internal enum HttpErrorResponseMode
{
File,
ExecuteURL,
Redirect
}
}

View file

@ -0,0 +1,72 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Common
{
using Microsoft.Web.Administration;
using System;
using System.Reflection;
internal sealed class IsapiCgiRestrictionCollection : ConfigurationElementCollectionBase<IsapiCgiRestrictionElement>
{
public IsapiCgiRestrictionElement Add(string path, bool allowed)
{
IsapiCgiRestrictionElement element = base.CreateElement();
element.Path = path;
element.Allowed = allowed;
return base.Add(element);
}
protected override IsapiCgiRestrictionElement CreateNewElement(string elementTagName)
{
return new IsapiCgiRestrictionElement();
}
public void Remove(string path)
{
base.Remove(this[path]);
}
public new IsapiCgiRestrictionElement this[string path]
{
get
{
for (int i = 0; i < base.Count; i++)
{
IsapiCgiRestrictionElement element = base[i];
if (string.Equals(Environment.ExpandEnvironmentVariables(element.Path), Environment.ExpandEnvironmentVariables(path), StringComparison.OrdinalIgnoreCase))
{
return element;
}
}
return null;
}
}
}
}

View file

@ -0,0 +1,86 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Common
{
using Microsoft.Web.Administration;
using System;
internal sealed class IsapiCgiRestrictionElement : ConfigurationElement
{
private static readonly string AllowedAttribute = "allowed";
private static readonly string DescriptionAttribute = "description";
private static readonly string GroupIdAttribute = "groupId";
private static readonly string PathAttribute = "path";
public bool Allowed
{
get
{
return (bool) base[AllowedAttribute];
}
set
{
base[AllowedAttribute] = value;
}
}
public string Description
{
get
{
return (string) base[DescriptionAttribute];
}
set
{
base[DescriptionAttribute] = value;
}
}
public string GroupId
{
get
{
return (string) base[GroupIdAttribute];
}
}
public string Path
{
get
{
return (string) base[PathAttribute];
}
set
{
base[PathAttribute] = value;
}
}
}
}

View file

@ -0,0 +1,77 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Common
{
using Microsoft.Web.Administration;
using System;
internal sealed class IsapiCgiRestrictionSection : ConfigurationSection
{
private IsapiCgiRestrictionCollection _collection;
private static readonly string NotListedCgisAllowedAttribute = "notListedCgisAllowed";
private static readonly string NotListedIsapisAllowedAttribute = "notListedIsapisAllowed";
public IsapiCgiRestrictionCollection IsapiCgiRestrictions
{
get
{
if (this._collection == null)
{
this._collection = (IsapiCgiRestrictionCollection) base.GetCollection(typeof(IsapiCgiRestrictionCollection));
}
return this._collection;
}
}
public bool NotListedCgisAllowed
{
get
{
return (bool) base[NotListedCgisAllowedAttribute];
}
set
{
base[NotListedCgisAllowedAttribute] = value;
}
}
public bool NotListedIsapisAllowed
{
get
{
return (bool) base[NotListedIsapisAllowedAttribute];
}
set
{
base[NotListedIsapisAllowedAttribute] = value;
}
}
}
}

View file

@ -0,0 +1,184 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using Microsoft.Web.Administration;
namespace WebsitePanel.Providers.Web.Iis.DefaultDocuments
{
using Common;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using WebsitePanel.Providers.Web.Iis.Utility;
internal sealed class DefaultDocsModuleService : ConfigurationModuleService
{
public const string ValueAttribute = "value";
public string GetDefaultDocumentSettings(string siteId)
{
using (var srvman = GetServerManager())
{
// Load web site configuration
var config = srvman.GetWebConfiguration(siteId);
// Load corresponding section
var section = config.GetSection(Constants.DefaultDocumentsSection);
//
var filesCollection = section.GetCollection("files");
// Build default documents
var defaultDocs = new List<String>();
//
foreach (var item in filesCollection)
{
var item2Get = GetDefaultDocument(item);
//
if (String.IsNullOrEmpty(item2Get))
continue;
//
defaultDocs.Add(item2Get);
}
//
return String.Join(",", defaultDocs.ToArray());
}
}
public void SetDefaultDocumentsEnabled(string siteId, bool enabled)
{
using (var srvman = GetServerManager())
{
// Load web site configuration
var config = srvman.GetWebConfiguration(siteId);
// Load corresponding section
var section = config.GetSection(Constants.DefaultDocumentsSection);
//
section.SetAttributeValue("enabled", enabled);
//
srvman.CommitChanges();
}
}
public void SetDefaultDocumentSettings(string siteId, string defaultDocs)
{
#region Revert to parent settings (inherited)
using (var srvman = GetServerManager())
{
// Load web site configuration
var config = srvman.GetWebConfiguration(siteId);
// Load corresponding section
var section = config.GetSection(Constants.DefaultDocumentsSection);
//
section.RevertToParent();
//
srvman.CommitChanges();
}
#endregion
// Exit if no changes have been made
if (String.IsNullOrEmpty(defaultDocs))
return;
// Update default documents list
var docs2Add = defaultDocs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
#region Put changes in effect
using (var srvman = GetServerManager())
{
// Load web site configuration
var config = srvman.GetWebConfiguration(siteId);
// Load corresponding section
var section = config.GetSection(Constants.DefaultDocumentsSection);
//
var filesCollection = section.GetCollection("files");
// The only solution to override inherited default documents is to use <clear/> element
filesCollection.Clear();
//
foreach (var item in docs2Add)
{
// The default document specified exists
if (FindDefaultDocument(filesCollection, item) > -1)
continue;
//
var item2Add = CreateDefaultDocument(filesCollection, item);
//
if (item2Add == null)
continue;
//
filesCollection.Add(item2Add);
}
//
srvman.CommitChanges();
}
#endregion
}
private string GetDefaultDocument(ConfigurationElement element)
{
if (element == null)
return null;
//
return Convert.ToString(element.GetAttributeValue(ValueAttribute));
}
private ConfigurationElement CreateDefaultDocument(ConfigurationElementCollection collection, string valueStr)
{
if (valueStr == null)
return null;
//
valueStr = valueStr.Trim();
//
if (String.IsNullOrEmpty(valueStr))
return null;
//
ConfigurationElement file2Add = collection.CreateElement("add");
file2Add.SetAttributeValue(ValueAttribute, valueStr);
//
return file2Add;
}
private int FindDefaultDocument(ConfigurationElementCollection collection, string valueStr)
{
for (int i = 0; i < collection.Count; i++)
{
var item = collection[i];
//
var valueObj = item.GetAttributeValue(ValueAttribute);
//
if (String.Equals((String)valueObj, valueStr, StringComparison.OrdinalIgnoreCase))
{
return i;
}
}
//
return -1;
}
}
}

View file

@ -0,0 +1,240 @@
using System;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Providers.Web.Iis.Common;
using Microsoft.Web.Administration;
namespace WebsitePanel.Providers.Web.Delegation
{
internal sealed class DelegationRulesModuleService : ConfigurationModuleService
{
public void RestrictRuleToUser(string providers, string path, string accountName)
{
var rulePredicate = new Predicate<ConfigurationElement>(x => { return x.Attributes["providers"].Value.Equals(providers) && x.Attributes["path"].Value.Equals(path); });
//
var userPredicate = new Predicate<ConfigurationElement>(x => { return x.Attributes["name"].Value.Equals(accountName); });
//
using (var srvman = new ServerManager())
{
var adminConfig = srvman.GetAdministrationConfiguration();
//
var delegationSection = adminConfig.GetSection("system.webServer/management/delegation");
//
var rulesCollection = delegationSection.GetCollection();
// Update rule if exists
foreach (var rule in rulesCollection)
{
if (rulePredicate.Invoke(rule) == true)
{
var permissions = rule.GetCollection("permissions");
//
var user = default(ConfigurationElement);
//
foreach (var item in permissions)
{
if (userPredicate.Invoke(item))
{
user = item;
//
break;
}
}
//
if (user == null)
{
user = permissions.CreateElement("user");
//
user.SetAttributeValue("name", accountName);
user.SetAttributeValue("isRole", false);
//
permissions.Add(user);
}
//
if (user != null)
{
user.SetAttributeValue("accessType", "Deny");
//
srvman.CommitChanges();
}
}
}
}
}
public void AllowRuleToUser(string providers, string path, string accountName)
{
RemoveUserFromRule(providers, path, accountName);
}
public void RemoveUserFromRule(string providers, string path, string accountName)
{
var rulePredicate = new Predicate<ConfigurationElement>(x => { return x.Attributes["providers"].Value.Equals(providers) && x.Attributes["path"].Value.Equals(path); });
//
var userPredicate = new Predicate<ConfigurationElement>(x => { return x.Attributes["name"].Value.Equals(accountName); });
//
using (var srvman = new ServerManager())
{
var adminConfig = srvman.GetAdministrationConfiguration();
//
var delegationSection = adminConfig.GetSection("system.webServer/management/delegation");
//
var rulesCollection = delegationSection.GetCollection();
// Update rule if exists
foreach (var rule in rulesCollection)
{
if (rulePredicate.Invoke(rule) == true)
{
var permissions = rule.GetCollection("permissions");
//
foreach (var user in permissions)
{
if (userPredicate.Invoke(user))
{
permissions.Remove(user);
//
srvman.CommitChanges();
//
break;
}
}
}
}
}
}
public bool DelegationRuleExists(string providers, string path)
{
var exists = false;
//
var predicate = new Predicate<ConfigurationElement>(x =>
{
return x.Attributes["providers"].Value.Equals(providers) && x.Attributes["path"].Value.Equals(path);
});
//
using (var srvman = new ServerManager())
{
var adminConfig = srvman.GetAdministrationConfiguration();
//
var delegationSection = adminConfig.GetSection("system.webServer/management/delegation");
//
var rulesCollection = delegationSection.GetCollection();
// Update rule if exists
foreach (var rule in rulesCollection)
{
if (predicate.Invoke(rule) == true)
{
exists = true;
//
break;
}
}
}
//
return exists;
}
public void AddDelegationRule(string providers, string path, string pathType, string identityType, string userName, string userPassword)
{
var predicate = new Predicate<ConfigurationElement>(x =>
{
return x.Attributes["providers"].Value.Equals(providers) && x.Attributes["path"].Value.Equals(path);
});
//
using (var srvman = GetServerManager())
{
var adminConfig = srvman.GetAdministrationConfiguration();
//
var delegationSection = adminConfig.GetSection("system.webServer/management/delegation");
//
var rulesCollection = delegationSection.GetCollection();
// Update rule if exists
foreach (var rule in rulesCollection)
{
//
if (predicate.Invoke(rule) == true)
{
if (identityType.Equals("SpecificUser"))
{
var runAsElement = rule.ChildElements["runAs"];
//
runAsElement.SetAttributeValue("userName", userName);
runAsElement.SetAttributeValue("password", userPassword);
// Ensure the rules is enabled
if (rule.Attributes["enabled"].Equals(false))
{
rule.SetAttributeValue("enabled", true);
}
//
srvman.CommitChanges();
}
//
return; // Exit
}
}
// Create new rule if none exists
var newRule = rulesCollection.CreateElement("rule");
newRule.SetAttributeValue("providers", providers);
newRule.SetAttributeValue("actions", "*"); // Any
newRule.SetAttributeValue("path", path);
newRule.SetAttributeValue("pathType", pathType);
newRule.SetAttributeValue("enabled", true);
// Run rule as SpecificUser
if (identityType.Equals("SpecificUser"))
{
var runAs = newRule.GetChildElement("runAs");
//
runAs.SetAttributeValue("identityType", "SpecificUser");
runAs.SetAttributeValue("userName", userName);
runAs.SetAttributeValue("password", userPassword);
}
else // Run rule as CurrentUser
{
var runAs = newRule.GetChildElement("runAs");
//
runAs.SetAttributeValue("identityType", "CurrentUser");
}
// Establish permissions
var permissions = newRule.GetCollection("permissions");
var user = permissions.CreateElement("user");
user.SetAttributeValue("name", "*");
user.SetAttributeValue("accessType", "Allow");
user.SetAttributeValue("isRole", false);
permissions.Add(user);
//
rulesCollection.Add(newRule);
//
srvman.CommitChanges();
}
}
public void RemoveDelegationRule(string providers, string path)
{
var predicate = new Predicate<ConfigurationElement>(x =>
{
return x.Attributes["providers"].Value.Equals(providers) && x.Attributes["path"].Value.Equals(path);
});
//
using (var srvman = GetServerManager())
{
var adminConfig = srvman.GetAdministrationConfiguration();
//
var delegationSection = adminConfig.GetSection("system.webServer/management/delegation");
//
var rulesCollection = delegationSection.GetCollection();
// Remove rule if exists
foreach (var rule in rulesCollection)
{
// Match rule against predicate
if (predicate.Invoke(rule) == true)
{
rulesCollection.Remove(rule);
//
srvman.CommitChanges();
//
return; // Exit
}
}
}
}
}
}

View file

@ -0,0 +1,41 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.DirectoryBrowse
{
using System;
internal static class DirectoryBrowseGlobals
{
public const string DirectoryBrowseModuleName = "DirectoryBrowse";
public const int Enabled = 1;
public const int ReadOnly = 3;
public const int ShowFlags = 2;
}
}

View file

@ -0,0 +1,86 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.DirectoryBrowse
{
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;
using Common;
using System;
internal sealed class DirectoryBrowseModuleService : ConfigurationModuleService
{
public PropertyBag GetDirectoryBrowseSettings(string siteId)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(siteId);
//
DirectoryBrowseSection directoryBrowseSection = (DirectoryBrowseSection)config.GetSection(Constants.DirectoryBrowseSection, typeof(DirectoryBrowseSection));
//
PropertyBag bag = new PropertyBag();
bag[DirectoryBrowseGlobals.Enabled] = directoryBrowseSection.Enabled;
bag[DirectoryBrowseGlobals.ShowFlags] = (int)directoryBrowseSection.ShowFlags;
bag[DirectoryBrowseGlobals.ReadOnly] = directoryBrowseSection.IsLocked;
return bag;
}
}
public void SetDirectoryBrowseEnabled(string siteId, bool enabled)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(siteId);
//
var section = config.GetSection("system.webServer/directoryBrowse");
//
section.SetAttributeValue("enabled", enabled);
//
srvman.CommitChanges();
}
}
public void SetDirectoryBrowseSettings(string siteId, PropertyBag updatedBag)
{
if (updatedBag == null)
return;
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(siteId);
//
DirectoryBrowseSection section = (DirectoryBrowseSection)config.GetSection(Constants.DirectoryBrowseSection, typeof(DirectoryBrowseSection));
//
section.Enabled = (bool)updatedBag[DirectoryBrowseGlobals.Enabled];
section.ShowFlags = (DirectoryBrowseShowFlags)updatedBag[DirectoryBrowseGlobals.ShowFlags];
//
srvman.CommitChanges();
}
}
}
}

View file

@ -0,0 +1,64 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.DirectoryBrowse
{
using Microsoft.Web.Administration;
using System;
internal sealed class DirectoryBrowseSection : ConfigurationSection
{
private static readonly string EnabledAttribute = "enabled";
private static readonly string ShowFlagsAttribute = "showFlags";
public bool Enabled
{
get
{
return (bool) base[EnabledAttribute];
}
set
{
base[EnabledAttribute] = value;
}
}
public DirectoryBrowseShowFlags ShowFlags
{
get
{
return (DirectoryBrowseShowFlags) base[ShowFlagsAttribute];
}
set
{
base[ShowFlagsAttribute] = (int) value;
}
}
}
}

View file

@ -0,0 +1,44 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.DirectoryBrowse
{
using System;
[Flags]
internal enum DirectoryBrowseShowFlags
{
None = 0,
Date = 2,
Time = 4,
Size = 8,
Extension = 16,
LongDate = 32
}
}

View file

@ -0,0 +1,98 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Extensions
{
using Providers.Utils;
using Common;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using System.Collections.Specialized;
internal sealed class ExtensionsModuleService : ConfigurationModuleService
{
public const string PathAttribute = "path";
// Mappings collection to properly detect ISAPI modules registered in IIS.
static NameValueCollection ISAPI_MODULES = new NameValueCollection
{
// Misc
{ Constants.AspPathSetting, @"\inetsrv\asp.dll" },
// ASP.NET x86
{ Constants.AspNet11PathSetting, @"\Framework\v1.1.4322\aspnet_isapi.dll" },
{ Constants.AspNet20PathSetting, @"\Framework\v2.0.50727\aspnet_isapi.dll" },
{ Constants.AspNet40PathSetting, @"\Framework\v4.0.30128\aspnet_isapi.dll" },
// ASP.NET x64
{ Constants.AspNet20x64PathSetting, @"\Framework64\v2.0.50727\aspnet_isapi.dll" },
{ Constants.AspNet40x64PathSetting, @"\Framework64\v4.0.30128\aspnet_isapi.dll" }
};
public SettingPair[] GetISAPIExtensionsInstalled()
{
List<SettingPair> settings = new List<SettingPair>();
//
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var section = config.GetSection(Constants.IsapiCgiRestrictionSection);
//
foreach (var item in section.GetCollection())
{
var isapiModulePath = Convert.ToString(item.GetAttributeValue(PathAttribute));
//
for (int i = 0; i < ISAPI_MODULES.Keys.Count; i++)
{
var pathExt = ISAPI_MODULES.Get(i);
//
if (isapiModulePath.EndsWith(pathExt))
{
settings.Add(new SettingPair
{
// Retrieve key name
Name = ISAPI_MODULES.GetKey(i),
// Evaluate ISAPI module path
Value = isapiModulePath
});
//
break;
}
}
}
}
//
return settings.ToArray();
}
}
}

View file

@ -0,0 +1,49 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.Providers.Web.Handlers
{
[Flags]
internal enum HandlerAccessPolicy
{
Execute = 4,
None = 0,
NoRemoteExecute = 0x2000,
NoRemoteRead = 0x1000,
NoRemoteScript = 0x4000,
NoRemoteWrite = 0x400,
Read = 1,
Script = 0x200,
Source = 0x10,
Write = 2
}
}

View file

@ -0,0 +1,162 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Security.AccessControl;
using System.Text;
using Microsoft.Web.Administration;
namespace WebsitePanel.Providers.Web.Handlers
{
internal sealed class HandlerAction : ConfigurationElement
{
// Fields
private static readonly string ModulesAttribute = "modules";
private static readonly string NameAttribute = "name";
private static readonly string PathAttribute = "path";
private static readonly string PreConditionAttribute = "preCondition";
private static readonly string RequireAccessAttribute = "requireAccess";
private static readonly string ResourceTypeAttribute = "resourceType";
private static readonly string ScriptProcessorAttribute = "scriptProcessor";
private static readonly string TypeAttribute = "type";
private static readonly string VerbAttribute = "verb";
// Properties
public string Modules
{
get
{
return (string)base[ModulesAttribute];
}
set
{
base[ModulesAttribute] = value;
}
}
public string Name
{
get
{
return (string)base[NameAttribute];
}
set
{
base[NameAttribute] = value;
}
}
public string Path
{
get
{
return (string)base[PathAttribute];
}
set
{
base[PathAttribute] = value;
}
}
public string PreCondition
{
get
{
return (string)base[PreConditionAttribute];
}
set
{
base[PreConditionAttribute] = value;
}
}
public HandlerRequiredAccess RequireAccess
{
get
{
return (HandlerRequiredAccess)base[RequireAccessAttribute];
}
set
{
base[RequireAccessAttribute] = (int)value;
}
}
public ResourceType ResourceType
{
get
{
return (ResourceType)base[ResourceTypeAttribute];
}
set
{
base[ResourceTypeAttribute] = (int)value;
}
}
public string ScriptProcessor
{
get
{
return (string)base[ScriptProcessorAttribute];
}
set
{
base[ScriptProcessorAttribute] = value;
}
}
public string Type
{
get
{
return (string)base[TypeAttribute];
}
set
{
base[TypeAttribute] = value;
}
}
public string Verb
{
get
{
return (string)base[VerbAttribute];
}
set
{
base[VerbAttribute] = value;
}
}
}
}

View file

@ -0,0 +1,99 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Web.Administration;
namespace WebsitePanel.Providers.Web.Handlers
{
internal sealed class HandlerActionCollection : ConfigurationElementCollectionBase<HandlerAction>
{
// Methods
public HandlerAction AddAt(int index, string name, string path, string verb)
{
HandlerAction element = base.CreateElement();
element.Name = name;
element.Path = path;
element.Verb = verb;
return base.AddAt(index, element);
}
public HandlerAction AddCopy(HandlerAction action)
{
HandlerAction destination = base.CreateElement();
CopyInfo(action, destination);
return base.Add(destination);
}
public HandlerAction AddCopyAt(int index, HandlerAction action)
{
HandlerAction destination = base.CreateElement();
CopyInfo(action, destination);
return base.AddAt(index, destination);
}
private static void CopyInfo(HandlerAction source, HandlerAction destination)
{
destination.Name = source.Name;
destination.Modules = source.Modules;
destination.Path = source.Path;
destination.PreCondition = source.PreCondition;
destination.RequireAccess = source.RequireAccess;
destination.ResourceType = source.ResourceType;
destination.ScriptProcessor = source.ScriptProcessor;
destination.Type = source.Type;
destination.Verb = source.Verb;
}
protected override HandlerAction CreateNewElement(string elementTagName)
{
return new HandlerAction();
}
// Properties
public new HandlerAction this[string name]
{
get
{
for (int i = 0; i < base.Count; i++)
{
HandlerAction action = base[i];
if (string.Equals(action.Name, name, StringComparison.OrdinalIgnoreCase))
{
return action;
}
}
return null;
}
}
}
}

View file

@ -0,0 +1,43 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.Providers.Web.Handlers
{
internal enum HandlerRequiredAccess
{
None,
Read,
Write,
Script,
Execute
}
}

View file

@ -0,0 +1,268 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Handlers
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Web.Administration;
using WebsitePanel.Providers.Web.Iis.Common;
using Microsoft.Web.Management.Server;
using WebsitePanel.Providers.Utils;
using WebsitePanel.Server.Utils;
internal sealed class HandlersModuleService : ConfigurationModuleService
{
public void AddFastCgiApplication(string processorPath, string arguments)
{
//
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
FastCgiSection section = (FastCgiSection)config.GetSection(Constants.FactCgiSection, typeof(FastCgiSection));
FastCgiApplicationCollection applications = section.Applications;
//
if (applications[processorPath, arguments] == null)
{
applications.Add(processorPath, arguments);
}
//
srvman.CommitChanges();
}
}
public void AddIsapiAndCgiRestriction(string processorPath, bool allowed)
{
//
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
IsapiCgiRestrictionSection section = (IsapiCgiRestrictionSection)config.GetSection(
"system.webServer/security/isapiCgiRestriction", typeof(IsapiCgiRestrictionSection));
//
IsapiCgiRestrictionCollection isapiCgiRestrictions = section.IsapiCgiRestrictions;
//
if (isapiCgiRestrictions[processorPath] == null)
{
isapiCgiRestrictions.Add(processorPath, true);
}
else
{
isapiCgiRestrictions[processorPath].Allowed = true;
}
//
srvman.CommitChanges();
}
}
public void SetHandlersAccessPolicy(string fqPath, HandlerAccessPolicy policy)
{
//
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(fqPath);
//
HandlersSection section = (HandlersSection)config.GetSection(Constants.HandlersSection, typeof(HandlersSection));
//
section.AccessPolicy = policy;
//
srvman.CommitChanges();
}
}
public HandlerAccessPolicy GetHandlersAccessPolicy(string fqPath)
{
//
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(fqPath);
//
HandlersSection section = (HandlersSection)config.GetSection(Constants.HandlersSection, typeof(HandlersSection));
//
return section.AccessPolicy;
}
}
internal ConfigurationElementCollection GetHandlers(WebVirtualDirectory virtualDir)
{
//
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
//
var section = config.GetSection(Constants.HandlersSection);
//
return section.GetCollection();
}
}
/// <summary>
/// Adds non existent script maps.
/// </summary>
/// <param name="installedHandlers">Already installed scrip maps.</param>
/// <param name="extensions">Extensions to check.</param>
/// <param name="processor">Extensions processor.</param>
internal void AddScriptMaps(WebVirtualDirectory virtualDir,
IEnumerable<string> extensions, string processor, string scName, string scModule)
{
// Empty processor is out of interest...
if (String.IsNullOrEmpty(processor))
return;
// This section helps to overcome "legacy" issues
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
//
var handlersSection = config.GetSection(Constants.HandlersSection);
// Do a complete section cleanup
handlersSection.RevertToParent();
//
srvman.CommitChanges();
}
//
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var handlersSection = config.GetSection(Constants.HandlersSection, virtualDir.FullQualifiedPath);
var handlersCollection = handlersSection.GetCollection();
// Iterate over extensions in order to setup non-existent handlers
foreach (string extension in extensions)
{
var extParts = extension.Split(',');
var path = extParts[0];
var existentHandler = FindHandlerAction(handlersCollection, path, processor);
// No need to add an existing handler
if (existentHandler != null)
continue;
// Create a new handler
var handler = handlersCollection.CreateElement();
// build script mapping name
var scriptMappingName = String.Format(scName, path);
//
handler["name"] = scriptMappingName;
handler["path"] = "*" + path;
handler["verb"] = "GET,HEAD,POST,DEBUG";
handler["scriptProcessor"] = processor;
handler["resourceType"] = ResourceType.File;
handler["modules"] = scModule;
// add handler
handlersCollection.AddAt(0, handler);
}
//
srvman.CommitChanges();
}
// Allow a script module...
switch (scModule)
{
case Constants.CgiModule: // Allow either ISAPI or CGI module
case Constants.IsapiModule:
AddIsapiAndCgiRestriction(processor, true);
break;
case Constants.FastCgiModule: // Allow FastCGI module
AddFastCgiApplication(processor, String.Empty);
break;
default:
Log.WriteWarning("Unknown Script Module has been requested to allow: {0};", scModule);
break;
}
}
internal void InheritScriptMapsFromParent(string fqPath)
{
if (String.IsNullOrEmpty(fqPath))
return;
//
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var handlersSection = config.GetSection(Constants.HandlersSection, fqPath);
//
handlersSection.RevertToParent();
//
srvman.CommitChanges();
}
}
internal void RemoveScriptMaps(WebVirtualDirectory virtualDir, IEnumerable<string> extensions, string processor)
{
if (String.IsNullOrEmpty(processor))
return;
//
if (virtualDir == null)
return;
//
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var handlersSection = config.GetSection(Constants.HandlersSection, virtualDir.FullQualifiedPath);
var handlersCollection = handlersSection.GetCollection();
//
foreach (string extension in extensions)
{
var extParts = extension.Split(',');
var path = extParts[0];
var existentHandler = FindHandlerAction(handlersCollection, path, processor);
// remove handler if exists
if (existentHandler != null)
handlersCollection.Remove(existentHandler);
}
//
srvman.CommitChanges();
}
}
private ConfigurationElement FindHandlerAction(ConfigurationElementCollection handlers, string path, string processor)
{
foreach (ConfigurationElement action in handlers)
{
// match handler path mapping
bool pathMatches = (String.Compare((string)action["path"], path, true) == 0)
|| (String.Compare((string)action["path"], String.Format("*{0}", path), true) == 0);
// match handler processor
bool processorMatches = (String.Compare(FileUtils.EvaluateSystemVariables((string)action["scriptProcessor"]),
FileUtils.EvaluateSystemVariables(processor), true) == 0);
// return handler action when match is exact
if (pathMatches && processorMatches)
return action;
}
//
return null;
}
}
}

View file

@ -0,0 +1,69 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Web.Administration;
namespace WebsitePanel.Providers.Web.Handlers
{
internal sealed class HandlersSection : ConfigurationSection
{
// Fields
private HandlerActionCollection _handlers;
private static readonly string AccessPolicyAttribute = "accessPolicy";
// Properties
public HandlerAccessPolicy AccessPolicy
{
get
{
return (HandlerAccessPolicy)base[AccessPolicyAttribute];
}
set
{
base[AccessPolicyAttribute] = (int)value;
}
}
public HandlerActionCollection Handlers
{
get
{
if (this._handlers == null)
{
this._handlers = (HandlerActionCollection)base.GetCollection(typeof(HandlerActionCollection));
}
return this._handlers;
}
}
}
}

View file

@ -0,0 +1,42 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.Providers.Web.Handlers
{
internal enum ResourceType
{
File,
Directory,
Either,
Unspecified
}
}

View file

@ -0,0 +1,109 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Providers.Web.Iis.Common;
using Microsoft.Web.Administration;
using System.Collections;
using WebsitePanel.Providers.Web.Iis.Utility;
namespace WebsitePanel.Providers.Web.HttpRedirect
{
internal class HttpRedirectModuleService : ConfigurationModuleService
{
public const string EnabledAttribute = "enabled";
public const string ExactDestinationAttribute = "exactDestination";
public const string ChildOnlyAttribute = "childOnly";
public const string DestinationAttribute = "destination";
public const string HttpResponseStatusAttribute = "httpResponseStatus";
public void LoadHttpRedirectSettings(WebVirtualDirectory virtualDir)
{
using (var srvman = GetServerManager())
{
// Load web site configuration
var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
// Load corresponding section
var section = config.GetSection(Constants.HttpRedirectSection);
//
if (!Convert.ToBoolean(section.GetAttributeValue(EnabledAttribute)))
return;
//
virtualDir.RedirectExactUrl = Convert.ToBoolean(section.GetAttributeValue(ExactDestinationAttribute));
virtualDir.RedirectDirectoryBelow = Convert.ToBoolean(section.GetAttributeValue(ChildOnlyAttribute));
virtualDir.HttpRedirect = Convert.ToString(section.GetAttributeValue(DestinationAttribute));
virtualDir.RedirectPermanent = String.Equals("301", Convert.ToString(section.GetAttributeValue(HttpResponseStatusAttribute)));
}
}
public void SetHttpRedirectSettings(WebVirtualDirectory virtualDir)
{
#region Revert to parent settings (inherited)
using (var srvman = GetServerManager())
{
// Load web site configuration
var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
// Load corresponding section
var section = config.GetSection(Constants.HttpRedirectSection);
//
section.RevertToParent();
//
srvman.CommitChanges();
}
#endregion
// HttpRedirect property is not specified so defaults to the parent
if (String.IsNullOrEmpty(virtualDir.HttpRedirect))
return;
#region Put changes in effect
using (var srvman = GetServerManager())
{
// Load web site configuration
var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
// Load corresponding section
var section = config.GetSection(Constants.HttpRedirectSection);
// Enable http redirect feature
section.SetAttributeValue(EnabledAttribute, true);
section.SetAttributeValue(ExactDestinationAttribute, virtualDir.RedirectExactUrl);
section.SetAttributeValue(DestinationAttribute, virtualDir.HttpRedirect);
section.SetAttributeValue(ChildOnlyAttribute, virtualDir.RedirectDirectoryBelow);
// Configure HTTP Response Status
if (virtualDir.RedirectPermanent)
section.SetAttributeValue(HttpResponseStatusAttribute, "Permanent");
else
section.SetAttributeValue(HttpResponseStatusAttribute, "Found");
//
srvman.CommitChanges();
}
#endregion
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,186 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Providers.Web.Iis.Common;
using Microsoft.Web.Administration;
using WebsitePanel.Providers.Web.Iis.Utility;
namespace WebsitePanel.Providers.Web.MimeTypes
{
internal sealed class MimeTypesModuleService : ConfigurationModuleService
{
public const string FileExtensionAttribute = "fileExtension";
public const string MimeTypeAttribute = "mimeType";
/// <summary>
/// Loads available mime maps into supplied virtual iisDirObject description.
/// </summary>
/// <param name="vdir">Virtual iisDirObject description.</param>
public void GetMimeMaps(WebVirtualDirectory virtualDir)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
//
var section = config.GetSection(Constants.StaticContentSection);
//
var mappings = new List<MimeMap>();
//
foreach (var item in section.GetCollection())
{
var item2Get = GetMimeMap(item);
//
if (item2Get == null)
continue;
//
mappings.Add(item2Get);
}
//
virtualDir.MimeMaps = mappings.ToArray();
}
}
/// <summary>
/// Saves mime types from virtual iisDirObject description into configuration file.
/// </summary>
/// <param name="vdir">Virtual iisDirObject description.</param>
public void SetMimeMaps(WebVirtualDirectory virtualDir)
{
#region Revert to parent settings (inherited)
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
//
var section = config.GetSection(Constants.StaticContentSection);
//
section.RevertToParent();
//
srvman.CommitChanges();
}
#endregion
// Ensure mime maps are set
if (virtualDir.MimeMaps == null || virtualDir.MimeMaps.Length == 0)
return;
#region Put the change in effect
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
//
var section = config.GetSection(Constants.StaticContentSection);
//
var typesCollection = section.GetCollection();
//
foreach (var item in virtualDir.MimeMaps)
{
// Make sure mime-type mapping file extension is formatted exactly as it should be
if (!item.Extension.StartsWith("."))
item.Extension = "." + item.Extension;
//
int indexOf = FindMimeMap(typesCollection, item);
//
if (indexOf > -1)
{
var item2Renew = typesCollection[indexOf];
//
FillConfigurationElementWithData(item2Renew, item);
//
continue;
}
//
typesCollection.Add(CreateMimeMap(typesCollection, item));
}
//
srvman.CommitChanges();
}
#endregion
}
private MimeMap GetMimeMap(ConfigurationElement element)
{
// skip inherited mime mappings
if (element == null || !element.IsLocallyStored)
return null;
//
return new MimeMap
{
Extension = Convert.ToString(element.GetAttributeValue(FileExtensionAttribute)),
MimeType = Convert.ToString(element.GetAttributeValue(MimeTypeAttribute))
};
}
private ConfigurationElement CreateMimeMap(ConfigurationElementCollection collection, MimeMap mapping)
{
if (mapping == null
|| String.IsNullOrEmpty(mapping.MimeType)
|| String.IsNullOrEmpty(mapping.Extension))
{
return null;
}
//
var item2Add = collection.CreateElement("mimeMap");
//
FillConfigurationElementWithData(item2Add, mapping);
//
return item2Add;
}
private void FillConfigurationElementWithData(ConfigurationElement item2Fill, MimeMap mapping)
{
if (mapping == null
|| item2Fill == null
|| String.IsNullOrEmpty(mapping.MimeType)
|| String.IsNullOrEmpty(mapping.Extension))
{
return;
}
//
item2Fill.SetAttributeValue(MimeTypeAttribute, mapping.MimeType);
item2Fill.SetAttributeValue(FileExtensionAttribute, mapping.Extension);
}
private int FindMimeMap(ConfigurationElementCollection collection, MimeMap mapping)
{
for (int i = 0; i < collection.Count; i++)
{
var item = collection[i];
//
if (String.Equals(item.GetAttributeValue(FileExtensionAttribute), mapping.Extension))
{
return i;
}
}
//
return -1;
}
}
}

View file

@ -0,0 +1,31 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WebsitePanel.Providers.Web.IIs70")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("WebsitePanel.Providers.Web.IIs70")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0eb18093-bb95-406a-ab78-a2e45f4cb972")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:

View file

@ -0,0 +1,499 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using Microsoft.Web.Administration;
using WebsitePanel.Providers.Common;
using WebsitePanel.Server.Utils;
using System;
using System.Linq;
using CERTENROLLLib;
using CERTCLIENTLib;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using WebsitePanel.Providers.Web.Iis.Common;
using System.Security;
using WebsitePanel.Providers.Web.Iis.WebObjects;
namespace WebsitePanel.Providers.Web.Iis
{
internal sealed class SSLModuleService : ConfigurationModuleService
{
public void GenerateCsr(SSLCertificate cert)
{
// Create all the objects that will be required
CX509CertificateRequestPkcs10 pkcs10 = new CX509CertificateRequestPkcs10();
CX509PrivateKey privateKey = new CX509PrivateKey();
CCspInformation csp = new CCspInformation();
CCspInformations csPs = new CCspInformations();
CX500DistinguishedName dn = new CX500DistinguishedName();
CX509Enrollment enroll = new CX509Enrollment();
CObjectIds objectIds = new CObjectIds();
CObjectId clientObjectId = new CObjectId();
CObjectId serverObjectId = new CObjectId();
CX509ExtensionKeyUsage extensionKeyUsage = new CX509ExtensionKeyUsage();
CX509ExtensionEnhancedKeyUsage x509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage();
try
{
// Initialize the csp object using the desired Cryptograhic Service Provider (CSP)
csp.InitializeFromName("Microsoft RSA SChannel Cryptographic Provider");
// Add this CSP object to the CSP collection object
csPs.Add(csp);
// Provide key container name, key length and key spec to the private key object
//objPrivateKey.ContainerName = "AlejaCMa";
privateKey.Length = cert.CSRLength;
privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE;
privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG;
privateKey.MachineContext = true;
// Provide the CSP collection object (in this case containing only 1 CSP object)
// to the private key object
privateKey.CspInformations = csPs;
// Create the actual key pair
privateKey.Create();
// Initialize the PKCS#10 certificate request object based on the private key.
// Using the context, indicate that this is a user certificate request and don't
// provide a template name
pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, "");
cert.PrivateKey = privateKey.ToString();
// Key Usage Extension
extensionKeyUsage.InitializeEncode(
CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE |
CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE |
CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE |
CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE
);
pkcs10.X509Extensions.Add((CX509Extension)extensionKeyUsage);
// Enhanced Key Usage Extension
clientObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.2");
objectIds.Add(clientObjectId);
serverObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.1");
objectIds.Add(serverObjectId);
x509ExtensionEnhancedKeyUsage.InitializeEncode(objectIds);
pkcs10.X509Extensions.Add((CX509Extension)x509ExtensionEnhancedKeyUsage);
// Encode the name in using the Distinguished Name object
string request = String.Format(@"CN={0}, O={1}, OU={2}, L={3}, S={4}, C={5}", cert.Hostname, cert.Organisation, cert.OrganisationUnit, cert.City, cert.State, cert.Country);
dn.Encode(request, X500NameFlags.XCN_CERT_NAME_STR_NONE);
// Assing the subject name by using the Distinguished Name object initialized above
pkcs10.Subject = dn;
// Create enrollment request
enroll.InitializeFromRequest(pkcs10);
enroll.CertificateFriendlyName = cert.FriendlyName;
cert.CSR = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER);
}
catch (Exception ex)
{
Log.WriteError("Error creating CSR", ex);
}
}
public SSLCertificate InstallCertificate(SSLCertificate cert, WebSite website)
{
CX509Enrollment response = new CX509Enrollment();
try
{
response.Initialize(X509CertificateEnrollmentContext.ContextMachine);
response.InstallResponse(
InstallResponseRestrictionFlags.AllowUntrustedRoot,
cert.Certificate, EncodingType.XCN_CRYPT_STRING_BASE64HEADER,
null
);
SSLCertificate servercert = (from c in GetServerCertificates()
where c.FriendlyName == cert.FriendlyName
select c).Single();
cert.SerialNumber = servercert.SerialNumber;
cert.ValidFrom = servercert.ValidFrom;
cert.ExpiryDate = servercert.ExpiryDate;
cert.Hash = servercert.Hash;
cert.DistinguishedName = servercert.DistinguishedName;
if (cert.IsRenewal && CheckCertificate(website))
{
DeleteCertificate(GetCurrentSiteCertificate(website), website);
}
AddBinding(cert, website);
}
catch (Exception ex)
{
Log.WriteError("Error adding SSL certificate", ex);
cert.Success = false;
}
return cert;
}
public List<SSLCertificate> GetServerCertificates()
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
//
var certificates = new List<SSLCertificate>();
//
try
{
store.Open(OpenFlags.ReadOnly);
//
certificates = (from X509Certificate2 cert in store.Certificates
let hostname = cert.GetNameInfo(X509NameType.SimpleName, false)
select new SSLCertificate()
{
FriendlyName = cert.FriendlyName,
Hostname = hostname,
Hash = cert.GetCertHash(),
SerialNumber = cert.SerialNumber,
ValidFrom = DateTime.Parse(cert.GetEffectiveDateString()),
ExpiryDate = DateTime.Parse(cert.GetExpirationDateString()),
DistinguishedName = cert.Subject
}).ToList();
}
catch (Exception ex)
{
Log.WriteError(
String.Format("SSLModuleService is unable to get certificates from X509Store('{0}', '{1}') and complete GetServerCertificates call", store.Name, store.Location), ex);
// Re-throw exception
throw;
}
finally
{
store.Close();
}
//
return certificates;
}
public SSLCertificate InstallPfx(byte[] certificate, string password, WebSite website)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
//
SSLCertificate newcert = null, oldcert = null;
// Ensure we perform operations safely and preserve the original state during all manipulations
if (CheckCertificate(website))
oldcert = GetCurrentSiteCertificate(website);
//
X509Certificate2 x509Cert = new X509Certificate2(certificate, password);
#region Step 1: Register X.509 certificate in the store
// Trying to keep X.509 store open as less as possible
try
{
store.Open(OpenFlags.ReadWrite);
//
store.Add(x509Cert);
}
catch (Exception ex)
{
Log.WriteError(String.Format("SSLModuleService could not import PFX into X509Store('{0}', '{1}')", store.Name, store.Location), ex);
// Re-throw error
throw;
}
finally
{
store.Close();
}
#endregion
#region Step 2: Instantiate a copy of new X.509 certificate
try
{
//
store.Open(OpenFlags.ReadWrite);
//
newcert = new SSLCertificate
{
Hostname = x509Cert.GetNameInfo(X509NameType.SimpleName, false),
FriendlyName = x509Cert.FriendlyName,
CSRLength = Convert.ToInt32(x509Cert.PublicKey.Key.KeySize.ToString()),
Installed = true,
DistinguishedName = x509Cert.Subject,
Hash = x509Cert.GetCertHash(),
SerialNumber = x509Cert.SerialNumber,
ExpiryDate = DateTime.Parse(x509Cert.GetExpirationDateString()),
ValidFrom = DateTime.Parse(x509Cert.GetEffectiveDateString()),
};
}
catch (Exception ex)
{
// Rollback X.509 store changes
store.Remove(x509Cert);
// Log error
Log.WriteError("SSLModuleService could not instantiate a copy of new X.509 certificate. All previous changes have been rolled back.", ex);
// Re-throw
throw;
}
finally
{
store.Close();
}
#endregion
#region Step 3: Remove old certificate from the web site if any
try
{
store.Open(OpenFlags.ReadWrite);
// Check if certificate already exists, remove it.
if (oldcert != null)
DeleteCertificate(oldcert, website);
}
catch (Exception ex)
{
// Rollback X.509 store changes
store.Remove(x509Cert);
// Log the error
Log.WriteError(
String.Format("SSLModuleService could not remove existing certificate from '{0}' web site. All changes have been rolled back.", website.Name), ex);
// Re-throw
throw;
}
finally
{
store.Close();
}
#endregion
#region Step 4: Register new certificate with HTTPS binding on the web site
try
{
store.Open(OpenFlags.ReadWrite);
//
AddBinding(newcert, website);
}
catch (Exception ex)
{
// Install old certificate back if any
if (oldcert != null)
InstallCertificate(oldcert, website);
// Rollback X.509 store changes
store.Remove(x509Cert);
// Log the error
Log.WriteError(
String.Format("SSLModuleService could not add new X.509 certificate to '{0}' web site. All changes have been rolled back.", website.Name), ex);
// Re-throw
throw;
}
finally
{
store.Close();
}
#endregion
//
return newcert;
}
public byte[] ExportPfx(string serialNumber, string password)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2 cert = store.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, false)[0];
byte[] exported = cert.Export(X509ContentType.Pfx, password);
return exported;
}
public void AddBinding(SSLCertificate certificate, WebSite website)
{
using (ServerManager sm = GetServerManager())
{
// Not sure why do we need to work with X.509 store here, so commented it out and lets see what happens
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
//
List<ServerBinding> bindings = new List<ServerBinding>();
// Retrieve existing site bindings to figure out what do we have here
WebObjectsModuleService webObjSvc = new WebObjectsModuleService();
bindings.AddRange(webObjSvc.GetSiteBindings(website.SiteId));
// Look for dedicated ip
bool dedicatedIp = bindings.Exists(binding => String.IsNullOrEmpty(binding.Host) && binding.IP != "*");
//
string bindingInformation;
//
bindingInformation = dedicatedIp ? string.Format("{0}:443:", website.SiteIPAddress)
: string.Format("{0}:443:{1}", website.SiteIPAddress, certificate.Hostname);
//
sm.Sites[website.SiteId].Bindings.Add(bindingInformation, certificate.Hash, store.Name);
//
store.Close();
//
sm.CommitChanges();
}
}
public void RemoveBinding(SSLCertificate certificate, WebSite website)
{
using (ServerManager sm = GetServerManager())
{
Site site = sm.Sites[website.SiteId];
Binding sslbind = (from b in site.Bindings
where b.Protocol == "https"
select b).Single();
site.Bindings.Remove(sslbind);
sm.CommitChanges();
}
}
public SSLCertificate FindByFriendlyname(string name)
{
throw new NotImplementedException("Method not implemented");
}
public ResultObject DeleteCertificate(SSLCertificate certificate, WebSite website)
{
ResultObject result = new ResultObject();
try
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.MaxAllowed);
X509Certificate2 cert =
store.Certificates.Find(X509FindType.FindBySerialNumber, certificate.SerialNumber, false)[0];
store.Remove(cert);
store.Close();
RemoveBinding(certificate, website);
result.IsSuccess = true;
}
catch (Exception ex)
{
result.IsSuccess = false;
result.AddError("", ex);
}
return result;
}
public SSLCertificate ImportCertificate(WebSite website)
{
SSLCertificate certificate = new SSLCertificate { Success = false };
try
{
using (ServerManager sm = GetServerManager())
{
Site site = sm.Sites[website.SiteId];
Binding sslbind = (from b in site.Bindings
where b.Protocol == "https"
select b).Single();
certificate.Hash = sslbind.CertificateHash;
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.MaxAllowed);
X509Certificate2 x509Cert = (from X509Certificate2 c in store.Certificates
where Convert.ToBase64String(c.GetCertHash()) == Convert.ToBase64String(certificate.Hash)
select c).Single();
store.Close();
certificate.Hostname = x509Cert.GetNameInfo(X509NameType.SimpleName, false);
certificate.FriendlyName = x509Cert.FriendlyName;
certificate.CSRLength = Convert.ToInt32(x509Cert.PublicKey.Key.KeySize.ToString());
certificate.Installed = true;
certificate.DistinguishedName = x509Cert.Subject;
certificate.Hash = x509Cert.GetCertHash();
certificate.SerialNumber = x509Cert.SerialNumber;
certificate.ExpiryDate = DateTime.Parse(x509Cert.GetExpirationDateString());
certificate.ValidFrom = DateTime.Parse(x509Cert.GetEffectiveDateString());
certificate.Success = true;
}
}
catch (Exception ex)
{
certificate.Success = false;
certificate.Certificate = ex.ToString();
}
return certificate;
}
//Checks to see if the site has a certificate
public bool CheckCertificate(WebSite website)
{
using (var sm = GetServerManager())
{
//
Site site = sm.Sites[website.SiteId];
// Just exit from the loop if https binding found
foreach (Binding bind in site.Bindings.Where(bind => bind.Protocol == "https"))
return true;
//
return false;
}
}
public SSLCertificate GetCurrentSiteCertificate(WebSite website)
{
using (ServerManager sm = GetServerManager())
{
Site site = sm.Sites[website.SiteId];
Binding sslbind = (from b in site.Bindings
where b.Protocol == "https"
select b).Single();
byte[] currentHash = sslbind.CertificateHash;
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2 oldcertificate = (from X509Certificate2 c in store.Certificates
where Convert.ToBase64String(c.GetCertHash()) == Convert.ToBase64String(currentHash)
select c).Single();
store.Close();
SSLCertificate certificate = new SSLCertificate();
certificate.Hash = oldcertificate.GetCertHash();
certificate.SerialNumber = oldcertificate.SerialNumber;
return certificate;
}
}
}
}

View file

@ -0,0 +1,71 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.Utility
{
using System;
using System.Collections.Generic;
using Microsoft.Web.Administration;
using System.Collections;
internal static class ConfigurationUtility
{
public static bool ShouldPersist(string oldValue, string newValue)
{
if (String.IsNullOrEmpty(oldValue))
{
return !String.IsNullOrEmpty(newValue);
}
if (newValue == null)
{
return false;
}
return ((newValue.Length == 0) || !oldValue.Equals(newValue, StringComparison.Ordinal));
}
public static string GetQualifiedVirtualPath(string virtualPath)
{
if (!virtualPath.StartsWith("/"))
return "/" + virtualPath;
//
return virtualPath;
}
public static string GetNonQualifiedVirtualPath(string virtualPath)
{
if (virtualPath == "/")
return virtualPath;
//
if (virtualPath.StartsWith("/"))
return virtualPath.Substring(1);
//
return virtualPath;
}
}
}

View file

@ -0,0 +1,228 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using Microsoft.Web.Administration;
namespace WebsitePanel.Providers.Web.Iis.WebObjects
{
using Common;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using WebsitePanel.Providers.Web.Iis.Utility;
using System.IO;
using WebsitePanel.Providers.Utils;
internal sealed class CustomHttpErrorsModuleService : ConfigurationModuleService
{
public const string StatusCodeAttribute = "statusCode";
public const string SubStatusCodeAttribute = "subStatusCode";
public const string PathAttribute = "path";
public const string ResponseModeAttribute = "responseMode";
public const string PrefixLanguageFilePath = "prefixLanguageFilePath";
public void GetCustomErrors(WebVirtualDirectory virtualDir)
{
//
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
//
var httpErrorsSection = config.GetSection(Constants.HttpErrorsSection);
//
var errorsCollection = httpErrorsSection.GetCollection();
//
var errors = new List<HttpError>();
//
foreach (var item in errorsCollection)
{
var item2Get = GetHttpError(item, virtualDir);
//
if (item2Get == null)
continue;
//
errors.Add(item2Get);
}
//
virtualDir.HttpErrors = errors.ToArray();
}
}
public void SetCustomErrors(WebVirtualDirectory virtualDir)
{
#region Revert to parent settings (inherited)
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
//
var section = config.GetSection(Constants.HttpErrorsSection);
//
section.RevertToParent();
//
srvman.CommitChanges();
}
#endregion
// Http errors list is either empty or not set so defaults to the parent
if (virtualDir.HttpErrors == null || virtualDir.HttpErrors.Length == 0)
return;
#region Put the change in effect
using (var srvman = GetServerManager())
{
var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
//
var section = config.GetSection(Constants.HttpErrorsSection);
//
var errorsCollection = section.GetCollection();
//
foreach (var item in virtualDir.HttpErrors)
{
int indexOf = FindHttpError(errorsCollection, item);
// Just update the element attributes - IIS 7 API will do the rest
if (indexOf > -1)
{
var item2Renew = errorsCollection[indexOf];
//
FillConfigurationElementWithData(item2Renew, item, virtualDir);
//
continue;
}
//
var item2Add = CreateHttpError(errorsCollection, item, virtualDir);
//
if (item2Add == null)
continue;
//
errorsCollection.Add(item2Add);
}
//
srvman.CommitChanges();
}
#endregion
}
private HttpError GetHttpError(ConfigurationElement element, WebVirtualDirectory virtualDir)
{
if (element == null || virtualDir == null)
return null;
// skip inherited http errors
if (!element.IsLocallyStored)
return null;
//
var error = new HttpError
{
ErrorCode = Convert.ToString(element.GetAttributeValue(StatusCodeAttribute)),
ErrorSubcode = Convert.ToString(element.GetAttributeValue(SubStatusCodeAttribute)),
ErrorContent = Convert.ToString(element.GetAttributeValue(PathAttribute)),
HandlerType = Enum.GetName(typeof(HttpErrorResponseMode), element.GetAttributeValue(ResponseModeAttribute))
};
// Make error path relative to the virtual directory's root folder
if (error.HandlerType.Equals("File") // 0 is supposed to be File
&& error.ErrorContent.Length > virtualDir.ContentPath.Length)
{
error.ErrorContent = error.ErrorContent.Substring(virtualDir.ContentPath.Length);
}
//
return error;
}
private ConfigurationElement CreateHttpError(ConfigurationElementCollection collection, HttpError error, WebVirtualDirectory virtualDir)
{
// Skip elements either empty or with empty data
if (error == null || String.IsNullOrEmpty(error.ErrorContent))
return null;
// Create new custom error
ConfigurationElement error2Add = collection.CreateElement("error");
if (!FillConfigurationElementWithData(error2Add, error, virtualDir))
return null;
//
return error2Add;
}
private bool FillConfigurationElementWithData(ConfigurationElement item2Fill, HttpError error, WebVirtualDirectory virtualDir)
{
// code
Int64 statusCode = 0;
if (!Int64.TryParse(error.ErrorCode, out statusCode)
|| statusCode < 400 || statusCode > 999)
return false;
// sub-code
Int32 subStatusCode = -1;
if (!Int32.TryParse(error.ErrorSubcode, out subStatusCode))
return false;
//
if (subStatusCode == 0)
subStatusCode = -1;
// correct error content
string errorContent = error.ErrorContent;
if (error.HandlerType.Equals("File"))
{
if(error.ErrorContent.Length > virtualDir.ContentPath.Length)
errorContent = errorContent.Substring(virtualDir.ContentPath.Length);
errorContent = FileUtils.CorrectRelativePath(errorContent);
}
item2Fill.SetAttributeValue(StatusCodeAttribute, statusCode);
item2Fill.SetAttributeValue(SubStatusCodeAttribute, subStatusCode);
item2Fill.SetAttributeValue(PathAttribute, errorContent);
// Cleanup prefix language file path attribute.
item2Fill.SetAttributeValue(PrefixLanguageFilePath, String.Empty);
//
item2Fill.SetAttributeValue(ResponseModeAttribute, error.HandlerType);
// We are succeeded
return true;
}
private int FindHttpError(ConfigurationElementCollection collection, HttpError error)
{
for (int i = 0; i < collection.Count; i++)
{
var item = collection[i];
//
if ((Int64)item.GetAttributeValue(StatusCodeAttribute) == Int64.Parse(error.ErrorCode)
&& (Int32)item.GetAttributeValue(SubStatusCodeAttribute) == Int32.Parse(error.ErrorSubcode))
{
return i;
}
}
//
return -1;
}
}
}

View file

@ -0,0 +1,178 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Providers.Web.Iis.Common;
using WebsitePanel.Providers.Web.Iis.Utility;
using Microsoft.Web.Administration;
namespace WebsitePanel.Providers.Web.WebObjects
{
public class CustomHttpHeadersModuleService : ConfigurationModuleService
{
public const string NameAttribute = "name";
public const string ValueAttribute = "value";
public void GetCustomHttpHeaders(WebVirtualDirectory virtualDir)
{
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var httpProtocolSection = config.GetSection(Constants.HttpProtocolSection, virtualDir.FullQualifiedPath);
//
if (httpProtocolSection == null)
return;
//
var headersCollection = httpProtocolSection.GetCollection("customHeaders");
//
var headers = new List<HttpHeader>();
//
foreach (var item in headersCollection)
{
var item2Get = GetCustomHttpHeader(item);
//
if (item2Get == null)
continue;
//
headers.Add(item2Get);
}
//
virtualDir.HttpHeaders = headers.ToArray();
}
}
public void SetCustomHttpHeaders(WebVirtualDirectory virtualDir)
{
#region Revert to parent settings (inherited)
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var section = config.GetSection(Constants.HttpProtocolSection, virtualDir.FullQualifiedPath);
//
section.RevertToParent();
//
srvman.CommitChanges();
}
#endregion
// Ensure virtual directory has Custom HTTP Headers set
if (virtualDir.HttpHeaders == null || virtualDir.HttpHeaders.Length == 0)
return;
#region Put the change in effect
using (var srvman = GetServerManager())
{
var config = srvman.GetApplicationHostConfiguration();
//
var section = config.GetSection(Constants.HttpProtocolSection, virtualDir.FullQualifiedPath);
//
var headersCollection = section.GetCollection("customHeaders");
// Clean the collection to avoid duplicates collision on the root and nested levels
headersCollection.Clear();
// Iterate over custom http headers are being set
foreach (var item in virtualDir.HttpHeaders)
{
// Trying to find out whether the header is being updated
int indexOf = FindCustomHttpHeader(headersCollection, item);
//
if (indexOf > -1)
{
// Obtain the custom http header to update
var item2Renew = headersCollection[indexOf];
// Apply changes to the element
FillConfigurationElementWithData(item2Renew, item);
// Loop the next item
continue;
}
// Creating a new custom http header
var item2Add = CreateCustomHttpHeader(headersCollection, item);
// Checking results of the create operation
if (item2Add == null)
continue;
// Adding the newly created custom http header
headersCollection.Add(item2Add);
}
// Commit changes
srvman.CommitChanges();
}
#endregion
}
private HttpHeader GetCustomHttpHeader(ConfigurationElement element)
{
if (element == null)
return null;
//
return new HttpHeader
{
Key = Convert.ToString(element.GetAttributeValue(NameAttribute)),
Value = Convert.ToString(element.GetAttributeValue(ValueAttribute))
};
}
private ConfigurationElement CreateCustomHttpHeader(ConfigurationElementCollection collection, HttpHeader header)
{
// Skip elements either empty or with empty data
if (header == null || String.IsNullOrEmpty(header.Key))
return null;
//
ConfigurationElement header2Add = collection.CreateElement("add");
//
FillConfigurationElementWithData(header2Add, header);
//
return header2Add;
}
private void FillConfigurationElementWithData(ConfigurationElement item2Fill, HttpHeader header)
{
//
item2Fill.SetAttributeValue(NameAttribute, header.Key);
item2Fill.SetAttributeValue(ValueAttribute, header.Value);
}
private int FindCustomHttpHeader(ConfigurationElementCollection collection, HttpHeader header)
{
for (int i = 0; i < collection.Count; i++)
{
var item = collection[i];
//
if (String.Equals(item.GetAttributeValue(NameAttribute), header.Key))
{
return i;
}
}
//
return -1;
}
}
}

View file

@ -0,0 +1,671 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.Web.Iis.WebObjects
{
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Common;
using Utility;
using WebsitePanel.Providers.Utils;
using Microsoft.Web.Management;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Server;
using WebsitePanel.Providers.Web.Iis.Authentication;
internal sealed class WebObjectsModuleService : ConfigurationModuleService
{
public void ForceEnableAppPoolWow6432Mode(string poolName)
{
using (var srvman = GetServerManager())
{
var appPool = srvman.ApplicationPools[poolName];
//
if (Constants.X64Environment && appPool.Enable32BitAppOnWin64 == false)
{
appPool.Enable32BitAppOnWin64 = true;
srvman.CommitChanges();
}
}
}
public void SetWebServerDefaultLoggingSettings(LogExtFileFlags svrLoggingFlags)
{
using (var srvman = GetServerManager())
{
// Update logging settings
srvman.SiteDefaults.LogFile.LogExtFileFlags |= svrLoggingFlags;
//
srvman.CommitChanges();
}
}
public void SetWebSiteLoggingSettings(WebSite webSite)
{
using (var srvman = GetServerManager())
{
var iisObject = srvman.Sites[webSite.SiteId];
// Website logging is enabled by default
iisObject.LogFile.Enabled = true;
// Set website logs folder
if (!String.IsNullOrEmpty(webSite.LogsPath))
iisObject.LogFile.Directory = webSite.LogsPath;
//
srvman.CommitChanges();
}
}
public string[] GrantConfigurationSectionAccess(string[] sections)
{
List<string> messages = new List<string>();
//
if (sections != null && sections.Length > 0)
{
foreach (string sectionName in sections)
{
try
{
string cmd = FileUtils.EvaluateSystemVariables(@"%windir%\system32\inetsrv\appcmd.exe");
//
FileUtils.ExecuteSystemCommand(cmd,
String.Format("unlock config -section:{0}", sectionName));
}
catch (Exception ex)
{
messages.Add(String.Format("Could not unlock section '{0}'. Reason: {1}",
sectionName, ex.StackTrace));
}
}
}
//
return messages.ToArray();
}
public void ConfigureConnectAsFeature(WebVirtualDirectory virtualDir)
{
// read website
using (var srvman = GetServerManager())
{
var webSite = String.IsNullOrEmpty(virtualDir.ParentSiteName) ? srvman.Sites[virtualDir.Name] : srvman.Sites[virtualDir.ParentSiteName];
//
if (webSite != null)
{
// get root iisAppObject
var webApp = webSite.Applications[virtualDir.VirtualPath];
//
if (webApp != null)
{
var vdir = webApp.VirtualDirectories["/"];
//
if (vdir != null)
{
vdir.LogonMethod = AuthenticationLogonMethod.ClearText;
//
if (virtualDir.DedicatedApplicationPool)
{
var appPool = GetApplicationPool(virtualDir);
vdir.UserName = appPool.ProcessModel.UserName;
vdir.Password = appPool.ProcessModel.Password;
}
else
{
vdir.UserName = virtualDir.AnonymousUsername;
vdir.Password = virtualDir.AnonymousUserPassword;
}
//
srvman.CommitChanges();
}
}
}
}
}
public ApplicationPool GetApplicationPool(WebVirtualDirectory virtualDir)
{
if (virtualDir == null)
throw new ArgumentNullException("vdir");
// read app pool
using (var srvman = GetServerManager())
{
var appPool = srvman.ApplicationPools[virtualDir.ApplicationPool];
//
if (appPool == null)
throw new ApplicationException("ApplicationPoolNotFound");
//
return appPool;
}
}
public void CreateApplicationPool(string appPoolName, string appPoolUsername,
string appPoolPassword, string runtimeVersion, bool enable32BitOnWin64,
ManagedPipelineMode pipelineMode)
{
// ensure app pool name specified
if (String.IsNullOrEmpty(appPoolName))
throw new ArgumentNullException("appPoolName");
// Create iisAppObject pool
using (var srvman = GetServerManager())
{
// ensure app pool unique
if (srvman.ApplicationPools[appPoolName] != null)
throw new Exception("ApplicationPoolAlreadyExists");
var element = srvman.ApplicationPools.Add(appPoolName);
//
element.ManagedPipelineMode = pipelineMode;
// ASP.NET 2.0 by default
if (!String.IsNullOrEmpty(runtimeVersion))
element.ManagedRuntimeVersion = runtimeVersion;
//
element.Enable32BitAppOnWin64 = enable32BitOnWin64;
// set iisAppObject pool identity
if (!String.IsNullOrEmpty(appPoolUsername))
{
element.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
element.ProcessModel.UserName = appPoolUsername;
element.ProcessModel.Password = appPoolPassword;
}
else
{
element.ProcessModel.IdentityType = ProcessModelIdentityType.NetworkService;
}
//
element.AutoStart = true;
//
srvman.CommitChanges();
}
}
public string CreateSite(WebSite site)
{
// ensure site bindings
if (site.Bindings == null || site.Bindings.Length == 0)
throw new ApplicationException("SiteServerBindingsEmpty");
// ensure site name
if (String.IsNullOrEmpty(site.Name))
throw new ApplicationException("SiteNameEmpty");
// ensure physical site content path
if (String.IsNullOrEmpty(site.ContentPath))
throw new ApplicationException("SiteContentPathEmpty");
using (var srvman = GetServerManager())
{
//
var iisObject = srvman.Sites.Add(site.Name, site.ContentPath, 80);
//
iisObject.Applications[0].ApplicationPoolName = site.ApplicationPool;
//
site.SiteId = iisObject.Name;
//
iisObject.ServerAutoStart = true;
//
srvman.CommitChanges();
//
return iisObject.Name;
}
}
public void UpdateSite(WebSite site)
{
// ensure physical site content path
if (String.IsNullOrEmpty(site.ContentPath))
throw new Exception("SiteContentPathEmpty");
//
using (var srvman = GetServerManager())
{
//
var iisObject = srvman.Sites[site.Name];
//
iisObject.Applications[0].ApplicationPoolName = site.ApplicationPool;
//
iisObject.Applications[0].VirtualDirectories[0].PhysicalPath = site.ContentPath;
//
iisObject.ServerAutoStart = true;
//
srvman.CommitChanges();
}
}
public void UpdateVirtualDirectory(WebVirtualDirectory virtualDir)
{
// ensure physical site content path
if (String.IsNullOrEmpty(virtualDir.ContentPath))
throw new Exception("VirtualDirContentPathEmpty");
//
using (var srvman = GetServerManager())
{
// Obtain parent web site
var webSite = srvman.Sites[virtualDir.ParentSiteName];
// Ensure web site has been found
if (webSite == null)
throw new ApplicationException("WebSiteNotFound");
//
var v_dir = webSite.Applications[virtualDir.VirtualPath];
v_dir.ApplicationPoolName = virtualDir.ApplicationPool;
v_dir.VirtualDirectories[0].PhysicalPath = virtualDir.ContentPath;
//
srvman.CommitChanges();
}
}
public void DeleteApplicationPools(params string[] appPoolNames)
{
using (var srvman = GetServerManager())
{
//
foreach (var poolName in appPoolNames)
{
// Lookup for an app pool
int indexOf = srvman.ApplicationPools.IndexOf(srvman.ApplicationPools[poolName]);
// Remove app pool if it is found
if (indexOf > -1)
srvman.ApplicationPools.RemoveAt(indexOf);
}
//
srvman.CommitChanges();
}
}
public void ChangeSiteState(string siteId, ServerState state)
{
using (var srvman = GetServerManager())
{
var webSite = srvman.Sites[siteId];
//
if (webSite == null)
return;
//
switch (state)
{
case ServerState.Continuing:
case ServerState.Started:
webSite.Start();
webSite.ServerAutoStart = true;
break;
case ServerState.Stopped:
case ServerState.Paused:
webSite.Stop();
webSite.ServerAutoStart = false;
break;
}
//
srvman.CommitChanges();
}
}
public ServerState GetSiteState(string siteId)
{
using (var srvman = GetServerManager())
{
// ensure website exists
if (srvman.Sites[siteId] == null)
return ServerState.Unknown;
//
var siteState = ServerState.Unknown;
//
switch (srvman.Sites[siteId].State)
{
case ObjectState.Started:
siteState = ServerState.Started;
break;
case ObjectState.Starting:
siteState = ServerState.Starting;
break;
case ObjectState.Stopped:
siteState = ServerState.Stopped;
break;
case ObjectState.Stopping:
siteState = ServerState.Stopping;
break;
}
//
return siteState;
}
}
public bool SiteExists(string siteId)
{
using (var srvman = GetServerManager())
{
return (srvman.Sites[siteId] != null);
}
}
public string[] GetSites()
{
using (var srvman = GetServerManager())
{
var iisObjects = new List<string>();
//
foreach (var item in srvman.Sites)
iisObjects.Add(item.Name);
//
return iisObjects.ToArray();
}
}
public string GetWebSiteNameFromIIS(string siteName)
{
using (var srvman = GetServerManager())
{
if (srvman.Sites[siteName] != null)
return srvman.Sites[siteName].Name;
//
return null;
}
}
public string GetWebSiteIdFromIIS(string siteId, string format)
{
using (var srvman = GetServerManager())
{
var iisObject = srvman.Sites[siteId];
// Format string is empty
if (String.IsNullOrEmpty(format))
return Convert.ToString(iisObject.Id);
//
return String.Format(format, iisObject.Id);
}
}
public WebSite GetWebSiteFromIIS(string siteId)
{
using (var srvman = GetServerManager())
{
var webSite = new WebSite();
//
var iisObject = srvman.Sites[siteId];
//
webSite.SiteId = webSite.Name = iisObject.Name;
//
if (iisObject.LogFile.Enabled)
{
webSite.LogsPath = iisObject.LogFile.Directory;
webSite[WebSite.IIS7_LOG_EXT_FILE_FIELDS] = iisObject.LogFile.LogExtFileFlags.ToString();
}
// Read instant website id
webSite[WebSite.IIS7_SITE_ID] = GetWebSiteIdFromIIS(siteId, "W3SVC{0}");
// Read web site iisAppObject pool name
webSite.ApplicationPool = iisObject.Applications["/"].ApplicationPoolName;
//
return webSite;
}
}
public ServerBinding[] GetSiteBindings(string siteId)
{
using (var srvman = GetServerManager())
{
var iisObject = srvman.Sites[siteId];
// get server bingings
var bindings = new List<ServerBinding>();
//
foreach (var bindingObj in iisObject.Bindings)
{
// return only "http" bindings
if (String.Equals(bindingObj.Protocol, Uri.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase))
{
string[] parts = bindingObj.BindingInformation.Split(':');
// append binding
bindings.Add(new ServerBinding(bindingObj.Protocol, parts[0], parts[1], parts[2]));
}
}
//
return bindings.ToArray();
}
}
private void SyncWebSiteBindingsChanges(string siteId, ServerBinding[] bindings)
{
// ensure site bindings
if (bindings == null || bindings.Length == 0)
throw new Exception("SiteServerBindingsEmpty");
using (var srvman = GetServerManager())
{
var iisObject = srvman.Sites[siteId];
//
lock (((ICollection)iisObject.ChildElements).SyncRoot)
{
// remove all "http" bindings
int i = 0;
while (i < iisObject.Bindings.Count)
{
if (String.Equals(iisObject.Bindings[i].Protocol, Uri.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase))
{
iisObject.Bindings.RemoveAt(i);
continue;
}
else
{
i++;
}
}
// Create HTTP bindings received
foreach (var serverBinding in bindings)
{
var bindingInformation = String.Format("{0}:{1}:{2}", serverBinding.IP, serverBinding.Port, serverBinding.Host);
iisObject.Bindings.Add(bindingInformation, Uri.UriSchemeHttp);
}
}
//
srvman.CommitChanges();
}
}
public void UpdateSiteBindings(string siteId, ServerBinding[] bindings)
{
// Ensure web site exists
if (!SiteExists(siteId))
return;
//
SyncWebSiteBindingsChanges(siteId, bindings);
}
public string GetPhysicalPath(WebVirtualDirectory virtualDir)
{
using (var srvman = GetServerManager())
{
string siteId = (virtualDir.ParentSiteName == null)
? virtualDir.Name : virtualDir.ParentSiteName;
//
var iisObject = srvman.Sites[siteId];
if (iisObject == null)
return null;
//
var iisAppObject = iisObject.Applications[virtualDir.VirtualPath];
if (iisAppObject == null)
return null;
//
var iisDirObject = iisAppObject.VirtualDirectories["/"];
if (iisDirObject == null)
return null;
//
return iisDirObject.PhysicalPath;
}
}
public void DeleteApplicationPool(params string[] appPoolNames)
{
using (var srvman = GetServerManager())
{
foreach (var item in appPoolNames)
{
var indexOf = srvman.ApplicationPools.IndexOf(srvman.ApplicationPools[item]);
//
if (indexOf > -1)
srvman.ApplicationPools.RemoveAt(indexOf);
}
//
srvman.CommitChanges();
}
}
public bool IsApplicationPoolExist(string poolName)
{
if (String.IsNullOrEmpty(poolName))
throw new ArgumentNullException("poolName");
//
using (var srvman = GetServerManager())
{
return (srvman.ApplicationPools[poolName] != null);
}
}
public void DeleteSite(string siteId)
{
if (!SiteExists(siteId))
return;
//
using (var srvman = GetServerManager())
{
//
var indexOf = srvman.Sites.IndexOf(srvman.Sites[siteId]);
srvman.Sites.RemoveAt(indexOf);
//
srvman.CommitChanges();
}
}
public WebVirtualDirectory[] GetVirtualDirectories(string siteId)
{
if (!SiteExists(siteId))
return new WebVirtualDirectory[] { };
using (var srvman = GetServerManager())
{
var vdirs = new List<WebVirtualDirectory>();
var iisObject = srvman.Sites[siteId];
//
foreach (var item in iisObject.Applications)
{
// Skip root application which is web site itself
if (item.Path == "/")
continue;
//
vdirs.Add(new WebVirtualDirectory
{
Name = ConfigurationUtility.GetNonQualifiedVirtualPath(item.Path),
ContentPath = item.VirtualDirectories[0].PhysicalPath
});
}
//
return vdirs.ToArray();
}
}
public WebVirtualDirectory GetVirtualDirectory(string siteId, string directoryName)
{
//
if (String.IsNullOrEmpty(siteId))
throw new ArgumentNullException("siteId");
//
if (String.IsNullOrEmpty(directoryName))
throw new ArgumentNullException("directoryName");
//
if (!SiteExists(siteId))
return null;
//
using (var srvman = GetServerManager())
{
var site = srvman.Sites[siteId];
//
var vdir = new WebVirtualDirectory
{
Name = directoryName,
ParentSiteName = siteId
};
// We assume that we create only applications.
vdir.ApplicationPool = site.Applications[vdir.VirtualPath].ApplicationPoolName;
//
return vdir;
}
}
public void CreateVirtualDirectory(string siteId, string directoryName, string physicalPath)
{
if (!SiteExists(siteId))
throw new ApplicationException();
//
using (var srvman = GetServerManager())
{
var iisSiteObject = srvman.Sites[siteId];
var iisAppObject = iisSiteObject.Applications.Add(directoryName, physicalPath);
//
srvman.CommitChanges();
}
}
public bool VirtualDirectoryExists(string siteId, string directoryName)
{
if (!SiteExists(siteId))
return false;
using (var srvman = GetServerManager())
{
var vdir = new WebVirtualDirectory
{
Name = directoryName,
ParentSiteName = siteId
};
//
return (srvman.Sites[siteId].Applications[vdir.VirtualPath] != null);
}
}
public void DeleteVirtualDirectory(WebVirtualDirectory virtualDir)
{
if (!SiteExists(virtualDir.ParentSiteName))
return;
//
using (var srvman = GetServerManager())
{
var iisSiteObject = srvman.Sites[virtualDir.ParentSiteName];
var iisAppObject = iisSiteObject.Applications[virtualDir.VirtualPath];
//
if (iisAppObject != null)
iisSiteObject.Applications.Remove(iisAppObject);
//
srvman.CommitChanges();
}
}
}
}

View file

@ -0,0 +1,181 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{1B9DCE85-C664-49FC-B6E1-86C63CAB88D1}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WebsitePanel.Providers.Web</RootNamespace>
<AssemblyName>WebsitePanel.Providers.Web.IIs70</AssemblyName>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\WebsitePanel.Server\bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<WarningsAsErrors>618</WarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\WebsitePanel.Server\bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<WarningsAsErrors>618</WarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<Reference Include="Ionic.Zip.Reduced, Version=1.8.4.28, Culture=neutral, PublicKeyToken=edbe51ad942a3f5c, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\Ionic.Zip.Reduced.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Web.Administration, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\References\Microsoft\Microsoft.Web.Administration.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Web.Management, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Lib\References\Microsoft\Microsoft.Web.Management.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.DirectoryServices" />
<Reference Include="System.Management" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\VersionInfo.cs">
<Link>VersionInfo.cs</Link>
</Compile>
<Compile Include="Authentication\AnonymAuthModuleService.cs" />
<Compile Include="Authentication\AuthenticationGlobals.cs" />
<Compile Include="Authentication\BasicAuthModuleService.cs" />
<Compile Include="Authentication\WindowsAuthenticationModuleService.cs" />
<Compile Include="ClassicAsp\ClassicAspGlobals.cs" />
<Compile Include="ClassicAsp\ClassicAspModuleService.cs" />
<Compile Include="Common\ConfigurationModuleService.cs" />
<Compile Include="Common\FastCgiApplication.cs" />
<Compile Include="Common\FastCgiApplicationCollection.cs" />
<Compile Include="Common\FastCgiSection.cs" />
<Compile Include="Common\HttpErrorResponseMode.cs" />
<Compile Include="DefaultDocuments\DefaultDocumentModuleService.cs" />
<Compile Include="Delegation\DelegationRulesModuleService.cs" />
<Compile Include="DirectoryBrowse\DirectoryBrowseGlobals.cs" />
<Compile Include="DirectoryBrowse\DirectoryBrowseModuleService.cs" />
<Compile Include="DirectoryBrowse\DirectoryBrowseSection.cs" />
<Compile Include="DirectoryBrowse\DirectoryBrowseShowFlags.cs" />
<Compile Include="Extensions\ExtensionsModuleService.cs" />
<Compile Include="Common\IsapiCgiRestrictionCollection.cs" />
<Compile Include="Common\IsapiCgiRestrictionElement.cs" />
<Compile Include="Common\IsapiCgiRestrictionSection.cs" />
<Compile Include="Handlers\HandlerAccessPolicy.cs" />
<Compile Include="Handlers\HandlerAction.cs" />
<Compile Include="Handlers\HandlerActionCollection.cs" />
<Compile Include="Handlers\HandlerRequiredAccess.cs" />
<Compile Include="Handlers\HandlersModuleService.cs" />
<Compile Include="Handlers\HandlersSection.cs" />
<Compile Include="Handlers\ResourceType.cs" />
<Compile Include="HttpRedirect\HttpRedirectModuleService.cs" />
<Compile Include="IIs70.cs" />
<Compile Include="MimeTypes\MimeTypesModuleService.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SSL\SSLModuleService.cs" />
<Compile Include="Utility\ConfigurationUtility.cs" />
<Compile Include="WebObjects\CustomHttpErrorsModuleService.cs" />
<Compile Include="WebObjects\CustomHttpHeadersModuleService.cs" />
<Compile Include="WebObjects\WebObjectsModuleService.cs">
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WebsitePanel.Providers.Base\WebsitePanel.Providers.Base.csproj">
<Project>{684C932A-6C75-46AC-A327-F3689D89EB42}</Project>
<Name>WebsitePanel.Providers.Base</Name>
</ProjectReference>
<ProjectReference Include="..\WebsitePanel.Providers.Web.IIs60\WebsitePanel.Providers.Web.IIs60.csproj">
<Project>{9BE0317D-E42E-4FF6-9A87-8C801F046EA1}</Project>
<Name>WebsitePanel.Providers.Web.IIs60</Name>
</ProjectReference>
<ProjectReference Include="..\WebsitePanel.Server.Utils\WebsitePanel.Server.Utils.csproj">
<Project>{E91E52F3-9555-4D00-B577-2B1DBDD87CA7}</Project>
<Name>WebsitePanel.Server.Utils</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<COMReference Include="CERTCLIENTLib">
<Guid>{372FCE32-4324-11D0-8810-00A0C903B83C}</Guid>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>tlbimp</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>True</EmbedInteropTypes>
<Private>False</Private>
</COMReference>
<COMReference Include="CERTENROLLLib">
<Guid>{728AB348-217D-11DA-B2A4-000E7BBB2B09}</Guid>
<VersionMajor>1</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>tlbimp</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>True</EmbedInteropTypes>
<Private>False</Private>
</COMReference>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>