Imported Upstream version 4.8.0.309

Former-commit-id: 5f9c6ae75f295e057a7d2971f3a6df4656fa8850
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2016-11-10 13:04:39 +00:00
parent ee1447783b
commit 94b2861243
4912 changed files with 390737 additions and 49310 deletions

View File

@ -27,6 +27,11 @@ namespace System
LocalAppContextSwitches.SetDefaultsLessOrEqual_452();
}
if (version <= 40601)
{
LocalAppContextSwitches.SetDefaultsLessOrEqual_461();
}
break;
}
}

View File

@ -839,17 +839,11 @@ namespace System.ServiceModel.Channels
{
AspNetEnvironment env = AspNetEnvironment.Current;
// When IIS hosted, WebSockets can be used if the pipeline mode is integrated and the WebSocketModule is loaded.
// Otherwise, the client requests will not be upgraded to web sockets (see the code in HostedHttpTransportManager.HttpContextReceived(..)).
// We do the checks below (and fail the service activation), to avoid starting a WebSockets listener that won't get called.
// When IIS hosted, WebSockets can be used if the pipeline mode is integrated
if (!env.UsingIntegratedPipeline)
{
throw FxTrace.Exception.AsError(new NotSupportedException(SR.GetString(SR.WebSocketsNotSupportedInClassicPipeline)));
}
else if (!env.IsWebSocketModuleLoaded)
{
throw FxTrace.Exception.AsError(new NotSupportedException(SR.GetString(SR.WebSocketModuleNotLoaded)));
}
}
else if (!WebSocketHelper.OSSupportsWebSockets())
{

View File

@ -1 +1 @@
f50e3667174e51a9ed111f895086c89240f0296c
ee3fbc127a7fcb92e6aa44345193357a75edc7ee

View File

@ -202,8 +202,8 @@ namespace System.ServiceModel.Channels
internal const bool RequireClientCertificate = false;
internal const int MaxFaultSize = MaxBufferSize;
internal const int MaxSecurityFaultSize = 16384;
internal const SslProtocols SslProtocols = System.Security.Authentication.SslProtocols.Ssl3 |
System.Security.Authentication.SslProtocols.Tls |
internal const SslProtocols SslProtocols = System.Security.Authentication.SslProtocols.Tls |
System.Security.Authentication.SslProtocols.Tls11 |
System.Security.Authentication.SslProtocols.Tls12;

View File

@ -1101,31 +1101,82 @@ namespace System.ServiceModel.Channels
#if !FEATURE_CORECLR
// On CoreCLR this is not the way to determine if a process is a tailored application (which means APPX).
// On CoreCLR AppX is determined by a flag past to the host which is exposed by AppDomain.IsAppXProcess in mscorlib.
// The reason for this if-def is to ensure nobody takes a dependency on this on CoreCLR.
private static IntPtr GetCurrentProcessToken() { return new IntPtr(-4); }
enum AppPolicyClrCompat
{
AppPolicyClrCompat_Others = 0,
AppPolicyClrCompat_ClassicDesktop = 1,
AppPolicyClrCompat_Universal = 2,
AppPolicyClrCompat_PackagedDesktop = 3
};
[DllImport(KERNEL32, CharSet = CharSet.None, EntryPoint = "AppPolicyGetClrCompat")]
[System.Security.SecuritySafeCritical]
[return: MarshalAs(UnmanagedType.I4)]
private static extern Int32 _AppPolicyGetClrCompat(IntPtr processToken, out AppPolicyClrCompat appPolicyClrCompat);
// AppModel.h functions (Win8+)
[DllImport(KERNEL32, CharSet = CharSet.None, EntryPoint = "GetCurrentPackageId")]
[SecurityCritical]
[System.Security.SecuritySafeCritical]
[return: MarshalAs(UnmanagedType.I4)]
private static extern Int32 GetCurrentPackageId(ref Int32 pBufferLength, Byte[] pBuffer);
private static extern Int32 _GetCurrentPackageId(ref Int32 pBufferLength, Byte[] pBuffer);
[Fx.Tag.SecurityNote(
Critical = "Critical because it calls the native function GetCurrentPackageId.",
Safe = "Safe because it takes no user input and it doesn't leak security sensitive information.")]
[SecuritySafeCritical]
[DllImport(KERNEL32, CharSet=System.Runtime.InteropServices.CharSet.Auto, BestFitMapping=false)]
[ResourceExposure(ResourceScope.Machine)]
private static extern IntPtr GetModuleHandle(string modName);
// Copied from Win32Native.cs
// Note - do NOT use this to call methods. Use P/Invoke, which will
// do much better things w.r.t. marshaling, pinning memory, security
// stuff, better interactions with thread aborts, etc. This is used
// solely by DoesWin32MethodExist for avoiding try/catch EntryPointNotFoundException
// in scenarios where an OS Version check is insufficient
[DllImport(KERNEL32, CharSet=CharSet.Ansi, BestFitMapping=false, SetLastError=true, ExactSpelling=true)]
[ResourceExposure(ResourceScope.None)]
private static extern IntPtr GetProcAddress(IntPtr hModule, String methodName);
[System.Security.SecurityCritical] // auto-generated
private static bool DoesWin32MethodExist(String moduleName, String methodName)
{
// GetModuleHandle does not increment the module's ref count, so we don't need to call FreeLibrary.
IntPtr hModule = GetModuleHandle(moduleName);
if (hModule == IntPtr.Zero) {
System.Diagnostics.Debug.Assert(hModule != IntPtr.Zero, "GetModuleHandle failed. Dll isn't loaded?");
return false;
}
IntPtr functionPointer = GetProcAddress(hModule, methodName);
return (functionPointer != IntPtr.Zero);
}
// On CoreCLR this is not the way to determine if a process is a tailored application (which means APPX).
// On CoreCLR AppX is determined by a flag past to the host which is exposed by AppDomain.IsAppXProcess in mscorlib.
// The reason for this if-def is to ensure nobody takes a dependency on this on CoreCLR.
[System.Security.SecuritySafeCritical]
private static bool _IsTailoredApplication()
{
if (OSEnvironmentHelper.IsAtLeast(OSVersion.Win8))
Version windows8Version = new Version(6, 2, 0, 0);
OperatingSystem os = Environment.OSVersion;
bool osSupportsPackagedProcesses = os.Platform == PlatformID.Win32NT && os.Version >= windows8Version;
if (osSupportsPackagedProcesses && DoesWin32MethodExist(KERNEL32, "AppPolicyGetClrCompat"))
{
int bufLen = 0;
// Will return ERROR_INSUFFICIENT_BUFFER when running within a tailored application,
// Use AppPolicyGetClrCompat if it is available. Return true if and only if this is a UWA which means if
// this is packaged desktop app this method will return false. This may cause some confusion however
// this is necessary to make the behavior of packaged desktop apps identical to desktop apps.
AppPolicyClrCompat appPolicyClrCompat;
return _AppPolicyGetClrCompat(GetCurrentProcessToken(), out appPolicyClrCompat) == ERROR_SUCCESS &&
appPolicyClrCompat == AppPolicyClrCompat.AppPolicyClrCompat_Universal;
}
else if(osSupportsPackagedProcesses && DoesWin32MethodExist(KERNEL32, "GetCurrentPackageId"))
{
Int32 bufLen = 0;
// Will return ERROR_INSUFFICIENT_BUFFER when running within a packaged application,
// and will return ERROR_NO_PACKAGE_IDENTITY otherwise.
return GetCurrentPackageId(ref bufLen, null) == ERROR_INSUFFICIENT_BUFFER;
return _GetCurrentPackageId(ref bufLen, null) == ERROR_INSUFFICIENT_BUFFER;
}
else
{
{ // We must be running on a downlevel OS.
return false;
}
}

View File

@ -6,6 +6,7 @@ namespace System.ServiceModel.Channels
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net;
@ -44,6 +45,7 @@ namespace System.ServiceModel.Channels
static readonly HashSet<char> InvalidSeparatorSet = new HashSet<char>(new char[] { '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}', ' ' });
static string currentWebSocketVersion;
[SuppressMessage("Microsoft.Security.Cryptography", "CA5354:DoNotUseSHA1", Justification = "Cannot change. Usage of SHA1 is part of WebSocket spec. Justification in RFC6455 section 10.8")]
internal static string ComputeAcceptHeader(string webSocketKey)
{
Fx.Assert(webSocketKey != null, "webSocketKey should not be null.");

View File

@ -1 +1 @@
35c78297859f7342bb6f1137a045ea1bf79b932c
a457268b0cec838769a3f3a1db5bc2d6a67d31c1

View File

@ -1347,31 +1347,38 @@ namespace System.ServiceModel.Description
internal static XmlSchema CreateWsdl()
{
return XmlSchema.Read(new StringReader(wsdl), null);
StringReader reader = new StringReader(wsdl);
return XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null);
}
internal static XmlSchema CreateSoap()
{
return XmlSchema.Read(new StringReader(soap), null);
StringReader reader = new StringReader(soap);
return XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null);
}
internal static XmlSchema CreateSoapEncoding()
{
return XmlSchema.Read(new StringReader(soapEncoding), null);
StringReader reader = new StringReader(soapEncoding);
return XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null);
}
internal static XmlSchema CreateFakeSoapEncoding()
{
return XmlSchema.Read(new StringReader(fakeSoapEncoding), null);
StringReader reader = new StringReader(fakeSoapEncoding);
return XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null);
}
internal static XmlSchema CreateFakeXsdSchema()
{
return XmlSchema.Read(new StringReader(fakeXsd), null);
StringReader reader = new StringReader(fakeXsd);
return XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null);
}
internal static XmlSchema CreateFakeXmlSchema()
{
return XmlSchema.Read(new StringReader(fakeXmlSchema), null);
StringReader reader = new StringReader(fakeXmlSchema);
return XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null);
}
internal static bool IsKnownSchema(string ns)

View File

@ -5,6 +5,7 @@
namespace System.ServiceModel.Description
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
@ -313,6 +314,8 @@ namespace System.ServiceModel.Description
return newWsdl;
}
[SuppressMessage("Microsoft.Security.Xml", "CA3054:DoNotAllowDtdOnXmlTextReader")]
[SuppressMessage("Microsoft.Security.Xml", "CA3069:ReviewDtdProcessingAssignment", Justification = "This is trusted server code from the application only. We should allow the customer add dtd.")]
private static XmlSchema CloneXsd(XmlSchema originalXsd)
{
Fx.Assert(originalXsd != null, "originalXsd must not be null");
@ -321,7 +324,7 @@ namespace System.ServiceModel.Description
{
originalXsd.Write(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
newXsd = XmlSchema.Read(memoryStream, null);
newXsd = XmlSchema.Read(new XmlTextReader(memoryStream) { DtdProcessing = DtdProcessing.Parse }, null);
}
return newXsd;

View File

@ -7,6 +7,7 @@ namespace System.ServiceModel.Dispatcher
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
@ -262,6 +263,7 @@ namespace System.ServiceModel.Dispatcher
}
}
[SuppressMessage("Microsoft.Security.Xml", "CA3057:DoNotUseLoadXml")]
static QueryMatcher()
{
QueryMatcher.defaultFunctionLibs = new IFunctionLibrary[] { new XPathFunctionLibrary() };

View File

@ -8,12 +8,11 @@ namespace System.ServiceModel.Dispatcher
using System.Diagnostics;
using System.Reflection;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Security;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.Threading.Tasks;
using Threading;
/// <summary>
/// An invoker used when some operation contract has a return value of Task or its generic counterpart (Task of T)
@ -21,14 +20,12 @@ namespace System.ServiceModel.Dispatcher
internal class TaskMethodInvoker : IOperationInvoker
{
private const string ResultMethodName = "Result";
private MethodInfo taskMethod;
private bool isGenericTask;
private readonly MethodInfo taskMethod;
private InvokeDelegate invokeDelegate;
private int inputParameterCount;
private int outputParameterCount;
private object[] outputs;
private MethodInfo toAsyncMethodInfo;
private MethodInfo taskTResultGetMethod;
private bool isGenericTask;
public TaskMethodInvoker(MethodInfo taskMethod, Type taskType)
{
@ -41,7 +38,6 @@ namespace System.ServiceModel.Dispatcher
if (taskType != ServiceReflector.VoidType)
{
this.toAsyncMethodInfo = TaskExtensions.MakeGenericMethod(taskType);
this.taskTResultGetMethod = ((PropertyInfo)taskMethod.ReturnType.GetMember(ResultMethodName)[0]).GetGetMethod();
this.isGenericTask = true;
}
@ -57,36 +53,11 @@ namespace System.ServiceModel.Dispatcher
get { return this.taskMethod; }
}
private InvokeDelegate InvokeDelegate
{
get
{
this.EnsureIsInitialized();
return this.invokeDelegate;
}
}
private int InputParameterCount
{
get
{
this.EnsureIsInitialized();
return this.inputParameterCount;
}
}
private int OutputParameterCount
{
get
{
this.EnsureIsInitialized();
return this.outputParameterCount;
}
}
public object[] AllocateInputs()
{
return EmptyArray.Allocate(this.InputParameterCount);
EnsureIsInitialized();
return EmptyArray<object>.Allocate(this.inputParameterCount);
}
public object Invoke(object instance, object[] inputs, out object[] outputs)
@ -96,6 +67,114 @@ namespace System.ServiceModel.Dispatcher
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
{
return ToApm(InvokeAsync(instance, inputs), callback, state);
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
if (instance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
}
object returnVal = null;
bool callFailed = true;
bool callFaulted = false;
ServiceModelActivity activity = null;
Activity boundOperation = null;
try
{
AsyncMethodInvoker.GetActivityInfo(ref activity, ref boundOperation);
Task<Tuple<object, object[]>> invokeTask = result as Task<Tuple<object, object[]>>;
if (invokeTask == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.SFxInvalidCallbackIAsyncResult));
}
AggregateException ae = null;
Tuple<object, object[]> tuple = null;
Task task = null;
if (invokeTask.IsFaulted)
{
Fx.Assert(invokeTask.Exception != null, "Task.IsFaulted guarantees non-null exception.");
ae = invokeTask.Exception;
}
else
{
Fx.Assert(invokeTask.IsCompleted, "Task.Result is expected to be completed");
tuple = invokeTask.Result;
task = tuple.Item1 as Task;
if (task == null)
{
outputs = tuple.Item2;
return null;
}
if (task.IsFaulted)
{
Fx.Assert(task.Exception != null, "Task.IsFaulted guarantees non-null exception.");
ae = task.Exception;
}
}
if (ae != null && ae.InnerException != null)
{
if (ae.InnerException is FaultException)
{
// If invokeTask.IsFaulted we produce the 'callFaulted' behavior below.
// Any other exception will retain 'callFailed' behavior.
callFaulted = true;
callFailed = false;
}
if (ae.InnerException is SecurityException)
{
DiagnosticUtility.TraceHandledException(ae.InnerException, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
}
invokeTask.GetAwaiter().GetResult();
}
// Task cancellation without an exception indicates failure but we have no
// additional information to provide. Accessing Task.Result will throw a
// TaskCanceledException. For consistency between void Tasks and Task<T>,
// we detect and throw here.
if (task.IsCanceled)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TaskCanceledException(task));
}
outputs = tuple.Item2;
returnVal = this.isGenericTask ? this.taskTResultGetMethod.Invoke(task, Type.EmptyTypes) : null;
callFailed = false;
return returnVal;
}
finally
{
if (boundOperation != null)
{
((IDisposable)boundOperation).Dispose();
}
ServiceModelActivity.Stop(activity);
AsyncMethodInvoker.StopOperationInvokeTrace(callFailed, callFaulted, this.TaskMethod.Name);
AsyncMethodInvoker.StopOperationInvokePerformanceCounters(callFailed, callFaulted, this.TaskMethod.Name);
}
}
private async Task<Tuple<object, object[]>> InvokeAsync(object instance, object[] inputs)
{
EnsureIsInitialized();
if (instance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
@ -103,59 +182,55 @@ namespace System.ServiceModel.Dispatcher
if (inputs == null)
{
if (this.InputParameterCount > 0)
if (this.inputParameterCount > 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceNull, this.InputParameterCount)));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceNull, this.inputParameterCount)));
}
}
else if (inputs.Length != this.InputParameterCount)
else if (inputs.Length != this.inputParameterCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceInvalid, this.InputParameterCount, inputs.Length)));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceInvalid, this.inputParameterCount, inputs.Length)));
}
this.outputs = EmptyArray.Allocate(this.OutputParameterCount);
object[] outputs = EmptyArray.Allocate(this.outputParameterCount);
AsyncMethodInvoker.StartOperationInvokePerformanceCounters(this.taskMethod.Name);
IAsyncResult returnValue;
bool callFailed = true;
bool callFaulted = false;
object returnValue;
ServiceModelActivity activity = null;
Activity boundActivity = null;
try
{
Activity boundActivity = null;
AsyncMethodInvoker.CreateActivityInfo(ref activity, ref boundActivity);
AsyncMethodInvoker.StartOperationInvokeTrace(this.taskMethod.Name);
using (boundActivity)
if (DiagnosticUtility.ShouldUseActivity)
{
if (DiagnosticUtility.ShouldUseActivity)
{
string activityName = SR.GetString(SR.ActivityExecuteMethod, this.taskMethod.DeclaringType.FullName, this.taskMethod.Name);
ServiceModelActivity.Start(activity, activityName, ActivityType.ExecuteUserCode);
}
object taskReturnValue = this.InvokeDelegate(instance, inputs, this.outputs);
if (taskReturnValue == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("task");
}
else if (this.isGenericTask)
{
returnValue = (IAsyncResult)this.toAsyncMethodInfo.Invoke(null, new object[] { taskReturnValue, callback, state });
}
else
{
returnValue = ((Task)taskReturnValue).AsAsyncResult(callback, state);
}
callFailed = false;
string activityName = SR.GetString(SR.ActivityExecuteMethod, this.taskMethod.DeclaringType.FullName, this.taskMethod.Name);
ServiceModelActivity.Start(activity, activityName, ActivityType.ExecuteUserCode);
}
OperationContext.EnableAsyncFlow();
returnValue = this.invokeDelegate(instance, inputs, outputs);
if (returnValue == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("task");
}
var returnValueTask = returnValue as Task;
if (returnValueTask != null)
{
// Only return once the task has completed
await returnValueTask;
}
return Tuple.Create(returnValue, outputs);
}
catch (System.Security.SecurityException e)
catch (SecurityException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
@ -163,101 +238,77 @@ namespace System.ServiceModel.Dispatcher
catch (Exception e)
{
TraceUtility.TraceUserCodeException(e, this.taskMethod);
if (e is FaultException)
{
callFaulted = true;
callFailed = false;
}
throw;
}
finally
{
ServiceModelActivity.Stop(activity);
OperationContext.DisableAsyncFlow();
// Any exception above means InvokeEnd will not be called, so complete it here.
if (callFailed || callFaulted)
if (boundActivity != null)
{
AsyncMethodInvoker.StopOperationInvokeTrace(callFailed, callFaulted, this.TaskMethod.Name);
AsyncMethodInvoker.StopOperationInvokePerformanceCounters(callFailed, callFaulted, this.TaskMethod.Name);
((IDisposable)boundActivity).Dispose();
}
}
return returnValue;
ServiceModelActivity.Stop(activity);
}
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
// Helper method when implementing an APM wrapper around a Task based async method which returns a result.
// In the BeginMethod method, you would call use ToApm to wrap a call to MethodAsync:
// return MethodAsync(params).ToApm(callback, state);
// In the EndMethod, you would use ToApmEnd<TResult> to ensure the correct exception handling
// This will handle throwing exceptions in the correct place and ensure the IAsyncResult contains the provided
// state object
private static Task<TResult> ToApm<TResult>(Task<TResult> task, AsyncCallback callback, object state)
{
object returnVal;
bool callFailed = true;
bool callFaulted = false;
ServiceModelActivity activity = null;
if (instance == null)
// When using APM, the returned IAsyncResult must have the passed in state object stored in AsyncState. This
// is so the callback can regain state. If the incoming task already holds the state object, there's no need
// to create a TaskCompletionSource to ensure the returned (IAsyncResult)Task has the right state object.
// This is a performance optimization for this special case.
if (task.AsyncState == state)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
}
try
{
Activity boundOperation = null;
AsyncMethodInvoker.GetActivityInfo(ref activity, ref boundOperation);
using (boundOperation)
if (callback != null)
{
Task task = result as Task;
Fx.Assert(task != null, "InvokeEnd needs to be called with the result returned from InvokeBegin.");
if (task.IsFaulted)
task.ContinueWith((antecedent, obj) =>
{
Fx.Assert(task.Exception != null, "Task.IsFaulted guarantees non-null exception.");
// If FaultException is thrown, we will get 'callFaulted' behavior below.
// Any other exception will retain 'callFailed' behavior.
throw FxTrace.Exception.AsError<FaultException>(task.Exception);
}
// Task cancellation without an exception indicates failure but we have no
// additional information to provide. Accessing Task.Result will throw a
// TaskCanceledException. For consistency between void Tasks and Task<T>,
// we detect and throw here.
if (task.IsCanceled)
{
throw FxTrace.Exception.AsError(new TaskCanceledException(task));
}
outputs = this.outputs;
if (this.isGenericTask)
{
returnVal = this.taskTResultGetMethod.Invoke(result, Type.EmptyTypes);
}
else
{
returnVal = null;
}
callFailed = false;
AsyncCallback callbackObj = (AsyncCallback)obj;
callbackObj(antecedent);
}, callback, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default);
}
}
catch (SecurityException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
}
catch (FaultException)
{
callFaulted = true;
callFailed = false;
throw;
}
finally
{
ServiceModelActivity.Stop(activity);
AsyncMethodInvoker.StopOperationInvokeTrace(callFailed, callFaulted, this.TaskMethod.Name);
AsyncMethodInvoker.StopOperationInvokePerformanceCounters(callFailed, callFaulted, this.TaskMethod.Name);
return task;
}
return returnVal;
// Need to create a TaskCompletionSource so that the returned Task object has the correct AsyncState value.
var tcs = new TaskCompletionSource<TResult>(state);
var continuationState = Tuple.Create(tcs, callback);
task.ContinueWith((antecedent, obj) =>
{
Tuple<TaskCompletionSource<TResult>, AsyncCallback> tuple = (Tuple<TaskCompletionSource<TResult>, AsyncCallback>)obj;
TaskCompletionSource<TResult> tcsObj = tuple.Item1;
AsyncCallback callbackObj = tuple.Item2;
if (antecedent.IsFaulted)
{
tcsObj.TrySetException(antecedent.Exception.InnerException);
}
else if (antecedent.IsCanceled)
{
tcsObj.TrySetCanceled();
}
else
{
tcsObj.TrySetResult(antecedent.Result);
}
if (callbackObj != null)
{
callbackObj(tcsObj.Task);
}
}, continuationState, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default);
return tcs.Task;
}
private void EnsureIsInitialized()

View File

@ -92,7 +92,7 @@ namespace System.ServiceModel.Dispatcher
bufferWriter.Flush();
XmlDocument doc = new XmlDocument();
memoryStream.Position = 0;
doc.Load(memoryStream);
doc.Load(new XmlTextReader(memoryStream) { DtdProcessing = DtdProcessing.Prohibit });
//doc.Save(Console.Out);
foreach (XmlElement element in doc.DocumentElement.ChildNodes)
{

View File

@ -67,7 +67,7 @@ namespace System.ServiceModel
static XmlSchema GetEprSchema()
{
using (XmlTextReader reader = new XmlTextReader(new StringReader(Schema)))
using (XmlTextReader reader = new XmlTextReader(new StringReader(Schema)) { DtdProcessing = DtdProcessing.Prohibit })
{
return XmlSchema.Read(reader, null);
}

View File

@ -67,7 +67,7 @@ namespace System.ServiceModel
static XmlSchema GetEprSchema()
{
using (XmlTextReader reader = new XmlTextReader(new StringReader(Schema)))
using (XmlTextReader reader = new XmlTextReader(new StringReader(Schema)) { DtdProcessing = DtdProcessing.Prohibit })
{
return XmlSchema.Read(reader, null);
}

View File

@ -14,9 +14,11 @@ namespace System.ServiceModel
{
private const string DisableExplicitConnectionCloseHeaderString = "Switch.System.ServiceModel.DisableExplicitConnectionCloseHeader";
private const string AllowUnsignedToHeaderString = "Switch.System.ServiceModel.AllowUnsignedToHeader";
private const string DisableCngCertificatesString = "Switch.System.ServiceModel.DisableCngCertificates";
private static int disableExplicitConnectionCloseHeader;
private static int allowUnsignedToHeader;
private static int disableCngCertificates;
public static bool DisableExplicitConnectionCloseHeader
{
@ -36,10 +38,29 @@ namespace System.ServiceModel
}
}
public static bool DisableCngCertificates
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return LocalAppContext.GetCachedSwitchValue(DisableCngCertificatesString, ref disableCngCertificates);
}
}
public static void SetDefaultsLessOrEqual_452()
{
#pragma warning disable BCL0012
// Define the switches that should be true for 4.5.2 or less, false for 4.6+.
LocalAppContext.DefineSwitchDefault(DisableExplicitConnectionCloseHeaderString, true);
#pragma warning restore BCL0012
}
public static void SetDefaultsLessOrEqual_461()
{
#pragma warning disable BCL0012
// Define the switches that should be true for 4.6.1 or less, false for 4.6.2+.
LocalAppContext.DefineSwitchDefault(DisableCngCertificatesString, true);
#pragma warning restore BCL0012
}
}
}

View File

@ -5,19 +5,21 @@
namespace System.ServiceModel
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime;
using System.Security.Claims;
using System.Security.Principal;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security;
using System.Threading;
public sealed class OperationContext : IExtensibleObject<OperationContext>
{
[ThreadStatic]
static Holder currentContext;
static AsyncLocal<OperationContext> currentAsyncLocalContext = new AsyncLocal<OperationContext>();
ServiceChannel channel;
Message clientReply;
bool closeClientReply;
@ -33,6 +35,7 @@ namespace System.ServiceModel
MessageHeaders outgoingMessageHeaders;
MessageVersion outgoingMessageVersion;
EndpointDispatcher endpointDispatcher;
bool isAsyncFlowEnabled;
public event EventHandler OperationCompleted;
@ -92,12 +95,19 @@ namespace System.ServiceModel
{
get
{
return CurrentHolder.Context;
return ShouldUseAsyncLocalContext ? OperationContext.currentAsyncLocalContext.Value : CurrentHolder.Context;
}
set
{
CurrentHolder.Context = value;
if (ShouldUseAsyncLocalContext)
{
OperationContext.currentAsyncLocalContext.Value = value;
}
else
{
CurrentHolder.Context = value;
}
}
}
@ -115,6 +125,14 @@ namespace System.ServiceModel
}
}
private static bool ShouldUseAsyncLocalContext
{
get
{
return CurrentHolder.Context == null && OperationContext.currentAsyncLocalContext.Value != null && OperationContext.currentAsyncLocalContext.Value.isAsyncFlowEnabled;
}
}
public EndpointDispatcher EndpointDispatcher
{
get
@ -339,6 +357,21 @@ namespace System.ServiceModel
this.clientReply = null;
}
internal static void EnableAsyncFlow()
{
CurrentHolder.Context.isAsyncFlowEnabled = true;
currentAsyncLocalContext.Value = CurrentHolder.Context;
}
internal static void DisableAsyncFlow()
{
if (OperationContext.Current != null && OperationContext.Current.isAsyncFlowEnabled)
{
OperationContext.Current.isAsyncFlowEnabled = false;
currentAsyncLocalContext.Value = null;
}
}
internal void FireOperationCompleted()
{
try

View File

@ -10,14 +10,12 @@ namespace System.ServiceModel
public sealed class OperationContextScope : IDisposable
{
[ThreadStatic]
static OperationContextScope currentScope;
static AsyncLocal<OperationContextScope> currentScope = new AsyncLocal<OperationContextScope>();
OperationContext currentContext;
bool disposed;
readonly OperationContext originalContext = OperationContext.Current;
readonly OperationContextScope originalScope = OperationContextScope.currentScope;
readonly Thread thread = Thread.CurrentThread;
readonly OperationContextScope originalScope = OperationContextScope.currentScope.Value;
public OperationContextScope(IContextChannel channel)
{
@ -41,22 +39,19 @@ namespace System.ServiceModel
void PushContext(OperationContext context)
{
this.currentContext = context;
OperationContextScope.currentScope = this;
OperationContextScope.currentScope.Value = this;
OperationContext.Current = this.currentContext;
}
void PopContext()
{
if (this.thread != Thread.CurrentThread)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInvalidContextScopeThread0)));
if (OperationContextScope.currentScope != this)
if (OperationContextScope.currentScope.Value != this)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInterleavedContextScopes0)));
if (OperationContext.Current != this.currentContext)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxContextModifiedInsideScope0)));
OperationContextScope.currentScope = this.originalScope;
OperationContextScope.currentScope.Value = this.originalScope;
OperationContext.Current = this.originalContext;
if (this.currentContext != null)

View File

@ -17,6 +17,7 @@ namespace System.ServiceModel.Security
using System.Text;
using System.Xml;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;
using Psha1DerivedKeyGenerator = System.IdentityModel.Psha1DerivedKeyGenerator;
@ -57,6 +58,7 @@ namespace System.ServiceModel.Security
return CryptoHelper.CreateHashAlgorithm(SecurityAlgorithms.Sha256Digest);
}
[SuppressMessage("Microsoft.Security.Cryptography", "CA5354:DoNotUseSHA1", Justification = "Cannot change. Required as SOAP spec requires supporting SHA1.")]
internal static HashAlgorithm CreateHashAlgorithm(string digestMethod)
{
object algorithmObject = CryptoAlgorithms.GetAlgorithmFromConfig(digestMethod);
@ -86,6 +88,7 @@ namespace System.ServiceModel.Security
}
}
[SuppressMessage("Microsoft.Security.Cryptography", "CA5354:DoNotUseSHA1", Justification = "Cannot change. Required as SOAP spec requires supporting SHA1.")]
internal static HashAlgorithm CreateHashForAsymmetricSignature(string signatureMethod)
{
object algorithmObject = CryptoAlgorithms.GetAlgorithmFromConfig(signatureMethod);

View File

@ -0,0 +1 @@
b62aceefcff29d0061ab33c65db191ab5faee7c8

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