Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@@ -0,0 +1,59 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System.Collections.Generic;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Collections.ObjectModel;
using System.ServiceModel.Dispatcher;
// This attribute specifies what the service implementation requires for AspNet Integration mode.
[AttributeUsage(ServiceModelAttributeTargets.ServiceBehavior)]
public sealed class AspNetCompatibilityRequirementsAttribute : Attribute, IServiceBehavior
{
// AppCompat: The default has been changed in 4.5 to Allowed so that fewer people need to change it.
// For deployment compat purposes, apps targeting 4.0 should behave the same as if 4.5 was not installed.
AspNetCompatibilityRequirementsMode requirementsMode = OSEnvironmentHelper.IsApplicationTargeting45 ?
AspNetCompatibilityRequirementsMode.Allowed : AspNetCompatibilityRequirementsMode.NotAllowed;
// NotAllowed: Validates that the service is not running in the AspNetCompatibility mode.
//
// Required: Validates that service runs in the AspNetCompatibility mode only.
//
// Allowed: Allows both AspNetCompatibility mode and the default Indigo mode.
//
public AspNetCompatibilityRequirementsMode RequirementsMode
{
get
{
return this.requirementsMode;
}
set
{
AspNetCompatibilityRequirementsModeHelper.Validate(value);
this.requirementsMode = value;
}
}
void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
{
}
void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
if (description == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
}
AspNetEnvironment.Current.ValidateCompatibilityRequirements(RequirementsMode);
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
}
}
}

View File

@@ -0,0 +1,35 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System.ComponentModel;
public enum AspNetCompatibilityRequirementsMode
{
NotAllowed,
Allowed,
Required,
}
static class AspNetCompatibilityRequirementsModeHelper
{
static public bool IsDefined(AspNetCompatibilityRequirementsMode x)
{
return
x == AspNetCompatibilityRequirementsMode.NotAllowed ||
x == AspNetCompatibilityRequirementsMode.Allowed ||
x == AspNetCompatibilityRequirementsMode.Required ||
false;
}
public static void Validate(AspNetCompatibilityRequirementsMode value)
{
if (!IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value,
typeof(AspNetCompatibilityRequirementsMode)));
}
}
}
}

View File

@@ -0,0 +1,370 @@
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Runtime;
using System.Security;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Permissions;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
class AspNetEnvironment
{
static readonly object thisLock = new object();
// Double-checked locking pattern requires volatile for read/write synchronization
static volatile AspNetEnvironment current;
static bool isEnabled;
static bool? isApplicationDomainHosted;
protected AspNetEnvironment()
{
}
public static AspNetEnvironment Current
{
get
{
if (current == null)
{
lock (thisLock)
{
if (current == null)
{
current = new AspNetEnvironment();
}
}
}
return current;
}
// AspNetEnvironment.Current is set by System.ServiceModel.Activation when it is brought into memory through
// the ASP.Net hosting environment. It is the only "real" implementer of this class.
protected set
{
Fx.Assert(!isEnabled, "should only be explicitly set once");
Fx.Assert(value != null, "should only be set to a valid environment");
current = value;
isEnabled = true;
}
}
public static bool Enabled
{
get
{
return isEnabled;
}
}
public bool RequiresImpersonation
{
get
{
return AspNetCompatibilityEnabled;
}
}
public virtual bool AspNetCompatibilityEnabled
{
get
{
// subclass will check AspNetCompatibility mode
return false;
}
}
public virtual string ConfigurationPath
{
get
{
return AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
}
}
// these ideally would be replaced with public APIs
public virtual bool IsConfigurationBased
{
get
{
// subclass will check ServiceActivationElement presence
return false;
}
}
public virtual string CurrentVirtualPath
{
get
{
// subclass will use calculation from HostingManager.CreateService
return null;
}
}
public virtual string XamlFileBaseLocation
{
get
{
// subclass will use calculation from HostingManager.CreateService
return null;
}
}
public virtual bool UsingIntegratedPipeline
{
get
{
return false;
}
}
public virtual string WebSocketVersion
{
get
{
return null;
}
}
// Indicates if the WebSocket module is loaded. When IIS hosted, it throws an exception when called before we determined if the module is loaded or not.
public bool IsWebSocketModuleLoaded
{
get
{
return this.WebSocketVersion != null;
}
}
public virtual void AddHostingBehavior(ServiceHostBase serviceHost, ServiceDescription description)
{
// subclass will add HostedBindingBehavior
}
public virtual bool IsWindowsAuthenticationConfigured()
{
// subclass will check Asp.Net authentication mode
return false;
}
public virtual List<Uri> GetBaseAddresses(Uri addressTemplate)
{
// subclass will provide multiple base address support
return null;
}
// check if ((System.Web.Configuration.WebContext)configHostingContext).ApplicationLevel == WebApplicationLevel.AboveApplication
public virtual bool IsWebConfigAboveApplication(object configHostingContext)
{
// there are currently only two known implementations of HostingContext, so we are
// pretty much guaranteed to be hosted in ASP.Net here. However, it may not be
// through our BuildProvider, so we still need to do some work in the base class.
// The HostedAspNetEnvironment subclass can perform more efficiently using reflection
return SystemWebHelper.IsWebConfigAboveApplication(configHostingContext);
}
public virtual void EnsureCompatibilityRequirements(ServiceDescription description)
{
// subclass will ensure AspNetCompatibilityRequirementsAttribute is in the behaviors collection
}
public virtual bool TryGetFullVirtualPath(out string virtualPath)
{
// subclass will use the virtual path from the compiled string
virtualPath = null;
return false;
}
public virtual string GetAnnotationFromHost(ServiceHostBase host)
{
// subclass will return "Website name\Application Virtual Path|\relative service virtual path|serviceName"
return string.Empty;
}
public virtual void EnsureAllReferencedAssemblyLoaded()
{
}
public virtual BaseUriWithWildcard GetBaseUri(string transportScheme, Uri listenUri)
{
return null;
}
public virtual void ValidateHttpSettings(string virtualPath, bool isMetadataListener, bool usingDefaultSpnList, ref AuthenticationSchemes supportedSchemes, ref ExtendedProtectionPolicy extendedProtectionPolicy, ref string realm)
{
}
// returns whether or not the caller should use the hosted client certificate mapping
public virtual bool ValidateHttpsSettings(string virtualPath, ref bool requireClientCertificate)
{
return false;
}
public virtual void ProcessNotMatchedEndpointAddress(Uri uri, string endpointName)
{
// subclass will throw as appropriate for compat mode
}
public virtual void ValidateCompatibilityRequirements(AspNetCompatibilityRequirementsMode compatibilityMode)
{
// validate that hosting settings are compatible with the requested requirements
if (compatibilityMode == AspNetCompatibilityRequirementsMode.Required)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.Hosting_CompatibilityServiceNotHosted)));
}
}
public virtual IAspNetMessageProperty GetHostingProperty(Message message)
{
// subclass will gen up a HostingMessageProperty
return null;
}
public virtual IAspNetMessageProperty GetHostingProperty(Message message, bool removeFromMessage)
{
// subclass will return the hosting property from the message
// and remove it from the message's properties.
return null;
}
public virtual void PrepareMessageForDispatch(Message message)
{
// subclass will wrap ReceiveContext for Busy Count
}
public virtual void ApplyHostedContext(TransportChannelListener listener, BindingContext context)
{
// subclass will push hosted information to the transport listeners
}
internal virtual void AddMetadataBindingParameters(Uri listenUri, KeyedByTypeCollection<IServiceBehavior> serviceBehaviors, BindingParameterCollection bindingParameters)
{
bindingParameters.Add(new ServiceMetadataExtension.MetadataBindingParameter());
}
internal virtual bool IsMetadataListener(BindingParameterCollection bindingParameters)
{
return bindingParameters.Find<ServiceMetadataExtension.MetadataBindingParameter>() != null;
}
public virtual void IncrementBusyCount()
{
// subclass will increment HostingEnvironment.BusyCount
}
public virtual void DecrementBusyCount()
{
// subclass will decrement HostingEnvironment.BusyCount
}
public virtual bool TraceIncrementBusyCountIsEnabled()
{
// subclass will return true if tracing for IncrementBusyCount is enabled.
//kept as a separate check from TraceIncrementBusyCount to avoid creating source string if Tracing is not enabled.
return false;
}
public virtual bool TraceDecrementBusyCountIsEnabled()
{
// subclass will return true if tracing for DecrementBusyCount is enabled.
//kept as a separate check from TraceDecrementBusyCount to avoid creating source string if Tracing is not enabled.
return false;
}
public virtual void TraceIncrementBusyCount(string data)
{
//callers are expected to check if TraceIncrementBusyCountIsEnabled() is true
//before calling this method
// subclass will emit trace for IncrementBusyCount
// data is emitted in the Trace as the source of the call to Increment.
}
public virtual void TraceDecrementBusyCount(string data)
{
//callers are expected to check if TraceDecrementBusyCountIsEnabled() is true
//before calling this method
// subclass will emit trace for DecrementBusyCount
// data is emitted in the Trace as the source of the call to Decrement.
}
public virtual object GetConfigurationSection(string sectionPath)
{
// subclass will interact with web.config system
return ConfigurationManager.GetSection(sectionPath);
}
// Be sure to update UnsafeGetSection if you modify this method
[Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical method UnsafeGetSectionFromConfigurationManager which elevates.")]
[SecurityCritical]
public virtual object UnsafeGetConfigurationSection(string sectionPath)
{
// subclass will interact with web.config system
return UnsafeGetSectionFromConfigurationManager(sectionPath);
}
public virtual AuthenticationSchemes GetAuthenticationSchemes(Uri baseAddress)
{
// subclass will grab settings from the metabase
return AuthenticationSchemes.None;
}
public virtual bool IsSimpleApplicationHost
{
get
{
// subclass will grab settings from the ServiceHostingEnvironment
return false;
}
}
[Fx.Tag.SecurityNote(Critical = "Asserts ConfigurationPermission in order to fetch config from ConfigurationManager,"
+ "caller must guard return value.")]
[SecurityCritical]
[ConfigurationPermission(SecurityAction.Assert, Unrestricted = true)]
static object UnsafeGetSectionFromConfigurationManager(string sectionPath)
{
return ConfigurationManager.GetSection(sectionPath);
}
public virtual bool IsWithinApp(string absoluteVirtualPath)
{
return true;
}
internal static bool IsApplicationDomainHosted()
{
if (!AspNetEnvironment.isApplicationDomainHosted.HasValue)
{
lock (AspNetEnvironment.thisLock)
{
if (!AspNetEnvironment.isApplicationDomainHosted.HasValue)
{
bool isApplicationDomainHosted = false;
if (AspNetEnvironment.Enabled)
{
isApplicationDomainHosted = AspNetEnvironment.IsSystemWebAssemblyLoaded();
}
AspNetEnvironment.isApplicationDomainHosted = isApplicationDomainHosted;
}
}
}
return AspNetEnvironment.isApplicationDomainHosted.Value;
}
private static bool IsSystemWebAssemblyLoaded()
{
const string systemWebName = "System.Web,";
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (assembly.FullName.StartsWith(systemWebName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
}

View File

@@ -0,0 +1,56 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Activation.Configuration
{
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
internal static class ConfigurationStrings
{
static string GetSectionPath(string sectionName)
{
return string.Format(CultureInfo.InvariantCulture, @"{0}/{1}", ConfigurationStrings.SectionGroupName, sectionName);
}
static internal string DiagnosticSectionPath
{
get { return ConfigurationStrings.GetSectionPath(ConfigurationStrings.DiagnosticSectionName); }
}
static internal string NetTcpSectionPath
{
get { return ConfigurationStrings.GetSectionPath(ConfigurationStrings.NetTcpSectionName); }
}
static internal string NetPipeSectionPath
{
get { return ConfigurationStrings.GetSectionPath(ConfigurationStrings.NetPipeSectionName); }
}
internal const string SectionGroupName = "system.serviceModel.activation";
// Sid for the built-in group IIS_IUSRS for IIS7
internal const string IIS_IUSRSSid = "S-1-5-32-568";
internal const string DiagnosticSectionName = "diagnostics";
internal const string NetTcpSectionName = "net.tcp";
internal const string NetPipeSectionName = "net.pipe";
internal const string AllowAccounts = "allowAccounts";
internal const string Enabled = "enabled";
internal const string ListenBacklog = "listenBacklog";
internal const string MaxPendingAccepts = "maxPendingAccepts";
internal const string MaxPendingConnections = "maxPendingConnections";
internal const string PerformanceCountersEnabled = "performanceCountersEnabled";
internal const string ReceiveTimeout = "receiveTimeout";
internal const string SecurityIdentifier = "securityIdentifier";
internal const string TeredoEnabled = "teredoEnabled";
internal const string TimeSpanOneTick = "00:00:00.0000001";
internal const string TimeSpanZero = "00:00:00";
}
}

View File

@@ -0,0 +1,37 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Activation.Configuration
{
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
public sealed partial class DiagnosticSection : ConfigurationSection
{
public DiagnosticSection()
: base()
{
}
static internal DiagnosticSection GetSection()
{
DiagnosticSection retval = (DiagnosticSection)ConfigurationManager.GetSection(ConfigurationStrings.DiagnosticSectionPath);
if (retval == null)
{
retval = new DiagnosticSection();
}
return retval;
}
[ConfigurationProperty(ConfigurationStrings.PerformanceCountersEnabled, DefaultValue = ListenerConstants.DefaultPerformanceCountersEnabled)]
public bool PerformanceCountersEnabled
{
get { return (bool)base[ConfigurationStrings.PerformanceCountersEnabled]; }
set { base[ConfigurationStrings.PerformanceCountersEnabled] = value; }
}
}
}

View File

@@ -0,0 +1,82 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Activation.Configuration
{
using System;
using System.Configuration;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
public sealed partial class NetPipeSection : ConfigurationSection
{
PropertyInformationCollection propertyInfo;
public NetPipeSection()
: base()
{
propertyInfo = this.ElementInformation.Properties;
}
[ConfigurationProperty(ConfigurationStrings.AllowAccounts)]
public SecurityIdentifierElementCollection AllowAccounts
{
get { return (SecurityIdentifierElementCollection)base[ConfigurationStrings.AllowAccounts]; }
}
static internal NetPipeSection GetSection()
{
NetPipeSection retval = (NetPipeSection)ConfigurationManager.GetSection(ConfigurationStrings.NetPipeSectionPath);
if (retval == null)
{
retval = new NetPipeSection();
}
return retval;
}
protected override void InitializeDefault()
{
this.AllowAccounts.SetDefaultIdentifiers();
}
[ConfigurationProperty(ConfigurationStrings.MaxPendingConnections, DefaultValue = ListenerConstants.DefaultMaxPendingConnections)]
[IntegerValidator(MinValue = 0)]
public int MaxPendingConnections
{
get { return (int)base[ConfigurationStrings.MaxPendingConnections]; }
set { base[ConfigurationStrings.MaxPendingConnections] = value; }
}
[ConfigurationProperty(ConfigurationStrings.MaxPendingAccepts, DefaultValue = ListenerConstants.DefaultMaxPendingAccepts)]
[IntegerValidator(MinValue = 0)]
public int MaxPendingAccepts
{
get
{
int maxPendingAccepts = (int)base[ConfigurationStrings.MaxPendingAccepts];
if (maxPendingAccepts != ListenerConstants.DefaultMaxPendingAccepts)
{
// if the user changed the default, return user's value
return maxPendingAccepts;
}
else
{
// otherwise return 2 * transport default, since SMSvcHost defaults are global
return 2 * ConnectionOrientedTransportDefaults.GetMaxPendingAccepts();
}
}
set { base[ConfigurationStrings.MaxPendingAccepts] = value; }
}
[ConfigurationProperty(ConfigurationStrings.ReceiveTimeout, DefaultValue = ListenerConstants.DefaultReceiveTimeoutString)]
[System.ComponentModel.TypeConverter(typeof(TimeSpanOrInfiniteConverter))]
[System.ServiceModel.Configuration.ServiceModelTimeSpanValidator(MinValueString = ConfigurationStrings.TimeSpanZero)]
public TimeSpan ReceiveTimeout
{
get { return (TimeSpan)base[ConfigurationStrings.ReceiveTimeout]; }
set { base[ConfigurationStrings.ReceiveTimeout] = value; }
}
}
}

View File

@@ -0,0 +1,111 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Activation.Configuration
{
using System;
using System.Configuration;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
public sealed partial class NetTcpSection : ConfigurationSection
{
PropertyInformationCollection propertyInfo;
public NetTcpSection()
: base()
{
propertyInfo = this.ElementInformation.Properties;
}
[ConfigurationProperty(ConfigurationStrings.AllowAccounts)]
public SecurityIdentifierElementCollection AllowAccounts
{
get { return (SecurityIdentifierElementCollection)base[ConfigurationStrings.AllowAccounts]; }
}
static internal NetTcpSection GetSection()
{
NetTcpSection retval = (NetTcpSection)ConfigurationManager.GetSection(ConfigurationStrings.NetTcpSectionPath);
if (retval == null)
{
retval = new NetTcpSection();
}
return retval;
}
protected override void InitializeDefault()
{
this.AllowAccounts.SetDefaultIdentifiers();
}
[ConfigurationProperty(ConfigurationStrings.ListenBacklog, DefaultValue = ListenerConstants.DefaultListenBacklog)]
[IntegerValidator(MinValue = 0)]
public int ListenBacklog
{
get
{
int listenBacklog = (int)base[ConfigurationStrings.ListenBacklog];
if (listenBacklog != ListenerConstants.DefaultListenBacklog)
{
// if the user changed the default, return user's value
return listenBacklog;
}
else
{
// otherwise return the transport default
return TcpTransportDefaults.GetListenBacklog();
}
}
set { base[ConfigurationStrings.ListenBacklog] = value; }
}
[ConfigurationProperty(ConfigurationStrings.MaxPendingConnections, DefaultValue = ListenerConstants.DefaultMaxPendingConnections)]
[IntegerValidator(MinValue = 0)]
public int MaxPendingConnections
{
get { return (int)base[ConfigurationStrings.MaxPendingConnections]; }
set { base[ConfigurationStrings.MaxPendingConnections] = value; }
}
[ConfigurationProperty(ConfigurationStrings.MaxPendingAccepts, DefaultValue = ListenerConstants.DefaultMaxPendingAccepts)]
[IntegerValidator(MinValue = 0)]
public int MaxPendingAccepts
{
get
{
int maxPendingAccepts = (int)base[ConfigurationStrings.MaxPendingAccepts];
if (maxPendingAccepts != ListenerConstants.DefaultMaxPendingAccepts)
{
// if the user changed the default, return user's value
return maxPendingAccepts;
}
else
{
// otherwise return 2 * transport default, since SMSvcHost defaults are global
return 2 * ConnectionOrientedTransportDefaults.GetMaxPendingAccepts();
}
}
set { base[ConfigurationStrings.MaxPendingAccepts] = value; }
}
[ConfigurationProperty(ConfigurationStrings.ReceiveTimeout, DefaultValue = ListenerConstants.DefaultReceiveTimeoutString)]
[System.ComponentModel.TypeConverter(typeof(TimeSpanOrInfiniteConverter))]
[System.ServiceModel.Configuration.ServiceModelTimeSpanValidator(MinValueString = ConfigurationStrings.TimeSpanZero)]
public TimeSpan ReceiveTimeout
{
get { return (TimeSpan)base[ConfigurationStrings.ReceiveTimeout]; }
set { base[ConfigurationStrings.ReceiveTimeout] = value; }
}
[ConfigurationProperty(ConfigurationStrings.TeredoEnabled, DefaultValue = ListenerConstants.DefaultTeredoEnabled)]
public bool TeredoEnabled
{
get { return (bool)base[ConfigurationStrings.TeredoEnabled]; }
set { base[ConfigurationStrings.TeredoEnabled] = value; }
}
}
}

View File

@@ -0,0 +1,58 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Activation.Configuration
{
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Runtime;
using System.Security.Principal;
class SecurityIdentifierConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (typeof(string) == sourceType)
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (typeof(InstanceDescriptor) == destinationType)
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
Fx.Assert(this.CanConvertFrom(context, value.GetType()), "");
if (value is string)
{
return new SecurityIdentifier((string)value);
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
Fx.Assert(this.CanConvertTo(context, destinationType), "");
if (destinationType == typeof(string) && value is SecurityIdentifier)
{
SecurityIdentifier sid = (SecurityIdentifier)value;
return sid.Value;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}

View File

@@ -0,0 +1,33 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Activation.Configuration
{
using System;
using System.ComponentModel;
using System.Configuration;
using System.Security.Principal;
public sealed partial class SecurityIdentifierElement : ConfigurationElement
{
public SecurityIdentifierElement()
: base()
{
}
public SecurityIdentifierElement(SecurityIdentifier sid)
: this()
{
this.SecurityIdentifier = sid;
}
[ConfigurationProperty(ConfigurationStrings.SecurityIdentifier, DefaultValue = null, Options = ConfigurationPropertyOptions.IsKey)]
[TypeConverter(typeof(SecurityIdentifierConverter))]
public SecurityIdentifier SecurityIdentifier
{
get { return (SecurityIdentifier)base[ConfigurationStrings.SecurityIdentifier]; }
set { base[ConfigurationStrings.SecurityIdentifier] = value; }
}
}
}

View File

@@ -0,0 +1,48 @@
//------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
namespace System.ServiceModel.Activation.Configuration
{
using System;
using System.Collections;
using System.Configuration;
using System.Globalization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Configuration;
using System.ServiceModel.Channels;
using System.Security.Principal;
[ConfigurationCollection(typeof(SecurityIdentifierElement))]
public sealed class SecurityIdentifierElementCollection : ServiceModelConfigurationElementCollection<SecurityIdentifierElement>
{
public SecurityIdentifierElementCollection() : base() { }
protected override Object GetElementKey(ConfigurationElement element)
{
if (element == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
}
SecurityIdentifierElement configElementKey = (SecurityIdentifierElement)element;
return configElementKey.SecurityIdentifier.Value;
}
internal void SetDefaultIdentifiers()
{
if (Iis7Helper.IisVersion >= 7)
{
this.Add(new SecurityIdentifierElement(new SecurityIdentifier(ConfigurationStrings.IIS_IUSRSSid)));
}
this.Add(new SecurityIdentifierElement(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null)));
this.Add(new SecurityIdentifierElement(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null)));
this.Add(new SecurityIdentifierElement(new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null)));
this.Add(new SecurityIdentifierElement(new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null)));
}
}
}

View File

@@ -0,0 +1,39 @@
//------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
namespace System.ServiceModel.Activation.Configuration
{
using System;
using System.Configuration;
public sealed class ServiceModelActivationSectionGroup : ConfigurationSectionGroup
{
public DiagnosticSection Diagnostics
{
get { return (DiagnosticSection)this.Sections[ConfigurationStrings.DiagnosticSectionName]; }
}
static public ServiceModelActivationSectionGroup GetSectionGroup(Configuration config)
{
if (config == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("config");
}
#pragma warning suppress 56506 // [....], Configuration.SectionGroups cannot be null
return (ServiceModelActivationSectionGroup)config.SectionGroups[ConfigurationStrings.SectionGroupName];
}
public NetPipeSection NetPipe
{
get { return (NetPipeSection)this.Sections[ConfigurationStrings.NetPipeSectionName]; }
}
public NetTcpSection NetTcp
{
get { return (NetTcpSection)this.Sections[ConfigurationStrings.NetTcpSectionName]; }
}
}
}

View File

@@ -0,0 +1,45 @@
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Net.Sockets;
[DataContract]
[KnownType(typeof(TcpDuplicateContext))]
[KnownType(typeof(NamedPipeDuplicateContext))]
class DuplicateContext
{
[DataMember]
Uri via;
[DataMember]
byte[] readData;
protected DuplicateContext(Uri via, byte[] readData)
{
this.via = via;
this.readData = readData;
}
public Uri Via
{
get
{
return this.via;
}
}
public byte[] ReadData
{
get
{
return this.readData;
}
}
}
}

View File

@@ -0,0 +1,14 @@
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
interface IAspNetMessageProperty
{
Uri OriginalRequestUri { get; }
IDisposable ApplyIntegrationContext();
IDisposable Impersonate();
void Close();
}
}

View File

@@ -0,0 +1,22 @@
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System;
using System.Net.Sockets;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Runtime.Serialization;
interface IConnectionDuplicator
{
[OperationContract(IsOneWay = false, AsyncPattern = true)]
IAsyncResult BeginDuplicate(
DuplicateContext duplicateContext,
AsyncCallback callback, object state);
void EndDuplicate(IAsyncResult result);
}
}

View File

@@ -0,0 +1,33 @@
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IConnectionDuplicator))]
interface IConnectionRegister
{
[OperationContract(IsOneWay = false, IsInitiating = true)]
ListenerExceptionStatus Register(Version version, int pid, BaseUriWithWildcard path, int queueId, Guid token, string eventName);
[OperationContract]
bool ValidateUriRoute(Uri uri, IPAddress address, int port);
[OperationContract]
void Unregister();
}
//Used on the client side (e.g. inside WebHost) to add async support to validate the Uri without blocking IO threads to improve scalability.
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IConnectionDuplicator))]
interface IConnectionRegisterAsync : IConnectionRegister
{
[OperationContract(AsyncPattern = true, Action = "http://tempuri.org/IConnectionRegister/ValidateUriRoute", ReplyAction = "http://tempuri.org/IConnectionRegister/ValidateUriRouteResponse")]
IAsyncResult BeginValidateUriRoute(System.Uri uri, IPAddress address, int port, AsyncCallback callback, object asyncState);
bool EndValidateUriRoute(System.IAsyncResult result);
}
}

View File

@@ -0,0 +1,62 @@
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System.Runtime;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32;
static class Iis7Helper
{
static int iisVersion;
static bool isIis7;
static Iis7Helper()
{
isIis7 = GetIsIis7();
}
internal static int IisVersion
{
get { return iisVersion; }
}
internal static bool IsIis7
{
get { return isIis7; }
}
[Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical method to get version info from registry.",
Safe = "Processes registry info into a safe bool for return.")]
[SecuritySafeCritical]
static bool GetIsIis7()
{
iisVersion = -1;
object majorVersion = UnsafeGetMajorVersionFromRegistry();
if (majorVersion != null && majorVersion.GetType().Equals(typeof(int)))
{
iisVersion = (int)majorVersion;
}
return iisVersion >= 7;
}
const string subKey = @"Software\Microsoft\InetSTP";
[Fx.Tag.SecurityNote(Critical = "Asserts registry access to get a single value from the registry, caller should not leak value.")]
[SecurityCritical]
[RegistryPermission(SecurityAction.Assert, Read = @"HKEY_LOCAL_MACHINE\" + subKey)]
static object UnsafeGetMajorVersionFromRegistry()
{
using (RegistryKey localMachine = Registry.LocalMachine)
{
using (RegistryKey versionKey = localMachine.OpenSubKey(subKey))
{
return versionKey != null ? versionKey.GetValue("MajorVersion") : null;
}
}
}
}
}

View File

@@ -0,0 +1,55 @@
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Net.Sockets;
using System.ServiceModel.Dispatcher;
[DataContract]
class ListenerChannelContext
{
[DataMember]
string appKey;
[DataMember]
int listenerChannelId;
[DataMember]
Guid token;
internal ListenerChannelContext(string appKey, int listenerChannelId, Guid token)
{
this.appKey = appKey;
this.listenerChannelId = listenerChannelId;
this.token = token;
}
internal string AppKey { get { return appKey; } }
internal int ListenerChannelId { get { return listenerChannelId; } }
internal Guid Token { get { return token; } }
public static ListenerChannelContext Hydrate(byte[] blob)
{
using (MemoryStream memoryStream = new MemoryStream(blob))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(ListenerChannelContext));
return (ListenerChannelContext)serializer.ReadObject(memoryStream);
}
}
public byte[] Dehydrate()
{
using (MemoryStream memoryStream = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(typeof(ListenerChannelContext));
serializer.WriteObject(memoryStream, this);
return memoryStream.ToArray();
}
}
}
}

View File

@@ -0,0 +1,50 @@
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System;
using System.ServiceModel.Channels;
static class ListenerConstants
{
// Default constants for configurable settings
public const int DefaultListenBacklog = TcpTransportDefaults.ListenBacklogConst;
public const int DefaultMaxPendingAccepts = 0;
public const int DefaultMaxPendingConnections = 100;
public const string DefaultReceiveTimeoutString = "00:00:30";
public const bool DefaultTeredoEnabled = false;
public const bool DefaultPerformanceCountersEnabled = true;
// Registration service binding settings
public const int RegistrationMaxConcurrentSessions = int.MaxValue;
// based on empirical observations, I've never seen it go over 9018 (seems to be ~8k plus soap goo)
// we can be safer here, since we don't actually increase the memeory usage
public const int RegistrationMaxReceivedMessageSize = 10000;
public static readonly TimeSpan RegistrationCloseTimeout = TimeSpan.FromSeconds(2);
// Shared connection settings
// we shouldn't be needing to read more than 2115 bytes to dipatch a session
public const int SharedConnectionBufferSize = 2500;
public const int SharedMaxDrainSize = TransportDefaults.MaxDrainSize;
public static readonly TimeSpan SharedSendTimeout = ServiceDefaults.SendTimeout;
public const int SharedMaxContentTypeSize = ConnectionOrientedTransportDefaults.MaxContentTypeSize;
// Internal listener global settings
public const int MaxRetries = 5;
public const int MaxUriSize = ConnectionOrientedTransportDefaults.MaxViaSize;
public static readonly TimeSpan ServiceStartTimeout = TimeSpan.FromSeconds(10);
public const int ServiceStopTimeout = 30000;
public static readonly TimeSpan WasConnectTimeout = TimeSpan.FromSeconds(120);
// Constant strings
public const string GlobalPrefix = "Global\\";
public const string MsmqActivationServiceName = "NetMsmqActivator";
public const string NamedPipeActivationServiceName = "NetPipeActivator";
public const string NamedPipeSharedMemoryName = NamedPipeActivationServiceName + "/endpoint";
public const string TcpActivationServiceName = "NetTcpActivator";
public const string TcpPortSharingServiceName = "NetTcpPortSharing";
public const string TcpSharedMemoryName = TcpPortSharingServiceName + "/endpoint";
}
}

View File

@@ -0,0 +1,18 @@
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
enum ListenerExceptionStatus
{
Success,
PathTooLong,
RegistrationQuotaExceeded,
ProtocolUnsupported,
ConflictingRegistration,
FailedToListen,
VersionUnsupported,
InvalidArgument,
}
}

View File

@@ -0,0 +1,286 @@
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.ServiceModel.Channels;
using System.ServiceModel.ComIntegration;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.ServiceModel.Security;
using System.Text;
[SuppressUnmanagedCodeSecurityAttribute()]
static class ListenerUnsafeNativeMethods
{
const string ADVAPI32 = "advapi32.dll";
const string KERNEL32 = "kernel32.dll";
internal const int OWNER_SECURITY_INFORMATION = 0x00000001;
internal const int DACL_SECURITY_INFORMATION = 0x00000004;
internal const int ERROR_FILE_NOT_FOUND = 2;
internal const int ERROR_INSUFFICIENT_BUFFER = 122;
internal const int ERROR_SERVICE_ALREADY_RUNNING = 1056;
internal const int PROCESS_QUERY_INFORMATION = 0x0400;
internal const int PROCESS_DUP_HANDLE = 0x0040;
internal const int READ_CONTROL = 0x00020000;
internal const int TOKEN_QUERY = 0x0008;
internal const int WRITE_DAC = 0x00040000;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x0020;
// for some of these check out: %SDXROOT%\public\sdk\inc\winsvc.h
internal const int SC_MANAGER_CONNECT = 0x0001;
internal const int SC_STATUS_PROCESS_INFO = 0;
internal const int SERVICE_QUERY_CONFIG = 0x0001;
internal const int SERVICE_QUERY_STATUS = 0x0004;
internal const int SERVICE_RUNNING = 0x00000004;
internal const int SERVICE_START = 0x0010;
internal const int SERVICE_START_PENDING = 0x00000002;
[DllImport(KERNEL32, ExactSpelling = true, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool IsDebuggerPresent();
[DllImport(KERNEL32, ExactSpelling = true)]
[ResourceExposure(ResourceScope.Process)]
internal static extern void DebugBreak();
[DllImport(ADVAPI32, ExactSpelling = true, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static unsafe extern bool AdjustTokenPrivileges(SafeCloseHandle tokenHandle, bool disableAllPrivileges, TOKEN_PRIVILEGES* newState, int bufferLength, IntPtr previousState, IntPtr returnLength);
[DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool LookupAccountName(string systemName, string accountName, byte[] sid,
ref uint cbSid, StringBuilder referencedDomainName, ref uint cchReferencedDomainName, out short peUse);
[DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static unsafe extern bool LookupPrivilegeValue(IntPtr lpSystemName, string lpName, LUID* lpLuid);
[DllImport(ADVAPI32, ExactSpelling = true, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool CloseServiceHandle(IntPtr handle);
[DllImport(ADVAPI32, ExactSpelling = true, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool GetKernelObjectSecurity(SafeCloseHandle handle, int securityInformation, [Out] byte[] pSecurityDescriptor, int nLength, out int lpnLengthNeeded);
[DllImport(ADVAPI32, ExactSpelling = true, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool GetTokenInformation(SafeCloseHandle tokenHandle, TOKEN_INFORMATION_CLASS tokenInformationClass, [Out] byte[] pTokenInformation, int tokenInformationLength, out int returnLength);
[DllImport(KERNEL32, ExactSpelling = true, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern SafeCloseHandle OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport(KERNEL32, ExactSpelling = true, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern IntPtr GetCurrentProcess();
[DllImport(ADVAPI32, ExactSpelling = true, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool OpenProcessToken(SafeCloseHandle processHandle, int desiredAccess, out SafeCloseHandle tokenHandle);
[DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern SafeServiceHandle OpenSCManager(string lpMachineName, string lpDatabaseName, int dwDesiredAccess);
[DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern SafeServiceHandle OpenService(SafeServiceHandle hSCManager, string lpServiceName, int dwDesiredAccess);
[DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool QueryServiceConfig(SafeServiceHandle hService, [Out] byte[] pServiceConfig, int cbBufSize, out int pcbBytesNeeded);
[DllImport(ADVAPI32, ExactSpelling = true, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool QueryServiceStatus(SafeServiceHandle hService, out SERVICE_STATUS_PROCESS status);
[DllImport(ADVAPI32, ExactSpelling = true, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool QueryServiceStatusEx(SafeServiceHandle hService, int InfoLevel, [Out] byte[] pBuffer, int cbBufSize, out int pcbBytesNeeded);
[DllImport(ADVAPI32, ExactSpelling = true, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool SetKernelObjectSecurity(SafeCloseHandle handle, int securityInformation, [In] byte[] pSecurityDescriptor);
[DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool StartService(SafeServiceHandle hSCManager, int dwNumServiceArgs, string[] lpServiceArgVectors);
[Flags]
internal enum SidAttribute : uint
{
SE_GROUP_MANDATORY = 0x1, // The SID cannot have the SE_GROUP_ENABLED attribute cleared by a call to the AdjustTokenGroups function. However, you can use the CreateRestrictedToken function to convert a mandatory SID to a deny-only SID.
SE_GROUP_ENABLED_BY_DEFAULT = 0x2, // The SID is enabled by default.
SE_GROUP_ENABLED = 0x4, // The SID is enabled for access checks. When the system performs an access check, it checks for access-allowed and access-denied access control entries (ACEs) that apply to the SID. A SID without this attribute is ignored during an access check unless the SE_GROUP_USE_FOR_DENY_ONLY attribute is set.
SE_GROUP_OWNER = 0x8, // The SID identifies a group account for which the user of the token is the owner of the group, or the SID can be assigned as the owner of the token or objects.
SE_GROUP_USE_FOR_DENY_ONLY = 0x10, //
SE_GROUP_RESOURCE = 0x20000000, // The SID identifies a domain-local group.Windows NT: This value is not supported.
SE_GROUP_LOGON_ID = 0xC0000000, // The SID is a logon SID that identifies the logon session associated with an access token.
}
internal enum TOKEN_INFORMATION_CLASS : int
{
TokenUser = 1, // TOKEN_USER structure that contains the user account of the token. = 1,
TokenGroups, // a TOKEN_GROUPS structure that contains the group accounts associated with the token.,
TokenPrivileges, // a TOKEN_PRIVILEGES structure that contains the privileges of the token.,
TokenOwner, // a TOKEN_OWNER structure that contains the default owner security identifier (SID) for newly created objects.,
TokenPrimaryGroup, // a TOKEN_PRIMARY_GROUP structure that contains the default primary group SID for newly created objects.,
TokenDefaultDacl, // a TOKEN_DEFAULT_DACL structure that contains the default DACL for newly created objects.,
TokenSource, // a TOKEN_SOURCE structure that contains the source of the token. TOKEN_QUERY_SOURCE access is needed to retrieve this information.,
TokenType, // a TOKEN_TYPE value that indicates whether the token is a primary or impersonation token.,
TokenImpersonationLevel, // a SECURITY_IMPERSONATION_LEVEL value that indicates the impersonation level of the token. If the access token is not an impersonation token, the function fails.,
TokenStatistics, // a TOKEN_STATISTICS structure that contains various token statistics.,
TokenRestrictedSids, // a TOKEN_GROUPS structure that contains the list of restricting SIDs in a restricted token.,
TokenSessionId, // a DWORD value that indicates the Terminal Services session identifier that is associated with the token. If the token is associated with the Terminal Server console session, the session identifier is zero. If the token is associated with the Terminal Server client session, the session identifier is nonzero. In a non-Terminal Services environment, the session identifier is zero. If TokenSessionId is set with SetTokenInformation, the application must have the Act As Part Of the Operating System privilege, and the application must be enabled to set the session ID in a token.
TokenGroupsAndPrivileges, // a TOKEN_GROUPS_AND_PRIVILEGES structure that contains the user SID, the group accounts, the restricted SIDs, and the authentication ID associated with the token.,
TokenSessionReference, // Reserved,
TokenSandBoxInert, // a DWORD value that is nonzero if the token includes the SANDBOX_INERT flag.,
TokenAuditPolicy,
TokenOrigin, // a TOKEN_ORIGIN value. If the token resulted from a logon that used explicit credentials, such as passing a name, domain, and password to the LogonUser function, then the TOKEN_ORIGIN structure will contain the ID of the logon session that created it. If the token resulted from network authentication, such as a call to AcceptSecurityContext or a call to LogonUser with dwLogonType set to LOGON32_LOGON_NETWORK or LOGON32_LOGON_NETWORK_CLEARTEXT, then this value will be zero.
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
TokenIsAppContainer,
TokenCapabilities,
TokenAppContainerSid,
TokenAppContainerNumber,
TokenUserClaimAttributes,
TokenDeviceClaimAttributes,
TokenRestrictedUserClaimAttributes,
TokenRestrictedDeviceClaimAttributes,
TokenDeviceGroups,
TokenRestrictedDeviceGroups,
MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct QUERY_SERVICE_CONFIG
{
internal int dwServiceType;
internal int dwStartType;
internal int dwErrorControl;
internal string lpBinaryPathName;
internal string lpLoadOrderGroup;
internal int dwTagId;
internal string lpDependencies;
internal string lpServiceStartName;
internal string lpDisplayName;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SERVICE_STATUS_PROCESS
{
internal int dwServiceType;
internal int dwCurrentState;
internal int dwControlsAccepted;
internal int dwWin32ExitCode;
internal int dwServiceSpecificExitCode;
internal int dwCheckPoint;
internal int dwWaitHint;
internal int dwProcessId;
internal int dwServiceFlags;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal struct SID_AND_ATTRIBUTES
{
internal IntPtr Sid;
internal SidAttribute Attributes;
}
[StructLayout(LayoutKind.Sequential)]
internal struct TOKEN_GROUPS
{
internal int GroupCount;
internal IntPtr Groups; // array of SID_AND_ATTRIBUTES
}
[StructLayout(LayoutKind.Sequential)]
internal struct TOKEN_USER
{
internal IntPtr User; // a SID_AND_ATTRIBUTES
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct TOKEN_PRIVILEGES
{
internal int PrivilegeCount;
internal LUID_AND_ATTRIBUTES Privileges; // array of LUID_AND_ATTRIBUTES
}
[ComImport, Guid("CB2F6722-AB3A-11D2-9C40-00C04FA30A3E"), ComConversionLoss, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface ICorRuntimeHost
{
void Void0();
void Void1();
void Void2();
void Void3();
void Void4();
void Void5();
void Void6();
void Void7();
void Void8();
void Void9();
void GetDefaultDomain([MarshalAs(UnmanagedType.IUnknown)] out object pAppDomain);
}
}
sealed class SafeCloseHandle : SafeHandleZeroOrMinusOneIsInvalid
{
const string KERNEL32 = "kernel32.dll";
SafeCloseHandle() : base(true) { }
internal SafeCloseHandle(IntPtr handle, bool ownsHandle)
: base(ownsHandle)
{
DiagnosticUtility.DebugAssert(handle == IntPtr.Zero || !ownsHandle, "Unsafe to create a SafeHandle that owns a pre-existing handle before the SafeHandle was created.");
SetHandle(handle);
}
protected override bool ReleaseHandle()
{
// PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call.
#pragma warning suppress 56523 // We are not interested to throw an exception here. We can ignore the Last Error code.
return CloseHandle(handle);
}
[DllImport(KERNEL32, ExactSpelling = true, SetLastError = true)]
[SuppressUnmanagedCodeSecurity]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
extern static bool CloseHandle(IntPtr handle);
}
[SuppressUnmanagedCodeSecurityAttribute()]
sealed class SafeServiceHandle : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeServiceHandle()
: base(true)
{
}
override protected bool ReleaseHandle()
{
#pragma warning suppress 56523 // [....], should only fail if there is a bug (invalid handle); MDA will be raised
return ListenerUnsafeNativeMethods.CloseServiceHandle(handle);
}
}
}

Some files were not shown because too many files have changed in this diff Show More