2
0

DispatchOperationRuntime.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel.Dispatcher
  5. {
  6. using System;
  7. using System.Diagnostics;
  8. using System.Globalization;
  9. using System.IdentityModel.Configuration;
  10. using System.IdentityModel.Tokens;
  11. using System.Reflection;
  12. using System.Runtime;
  13. using System.Security;
  14. using System.Security.Claims;
  15. using System.Security.Principal;
  16. using System.ServiceModel;
  17. using System.ServiceModel.Channels;
  18. using System.ServiceModel.Diagnostics;
  19. using System.ServiceModel.Diagnostics.Application;
  20. using System.ServiceModel.Security;
  21. class DispatchOperationRuntime
  22. {
  23. static AsyncCallback invokeCallback = Fx.ThunkCallback(new AsyncCallback(DispatchOperationRuntime.InvokeCallback));
  24. readonly string action;
  25. readonly ICallContextInitializer[] callContextInitializers;
  26. readonly IDispatchFaultFormatter faultFormatter;
  27. readonly IDispatchMessageFormatter formatter;
  28. readonly ImpersonationOption impersonation;
  29. readonly IParameterInspector[] inspectors;
  30. readonly IOperationInvoker invoker;
  31. readonly bool isTerminating;
  32. readonly bool isSessionOpenNotificationEnabled;
  33. readonly bool isSynchronous;
  34. readonly string name;
  35. readonly ImmutableDispatchRuntime parent;
  36. readonly bool releaseInstanceAfterCall;
  37. readonly bool releaseInstanceBeforeCall;
  38. readonly string replyAction;
  39. readonly bool transactionAutoComplete;
  40. readonly bool transactionRequired;
  41. readonly bool deserializeRequest;
  42. readonly bool serializeReply;
  43. readonly bool isOneWay;
  44. readonly bool disposeParameters;
  45. readonly ReceiveContextAcknowledgementMode receiveContextAcknowledgementMode;
  46. readonly bool bufferedReceiveEnabled;
  47. readonly bool isInsideTransactedReceiveScope;
  48. internal DispatchOperationRuntime(DispatchOperation operation, ImmutableDispatchRuntime parent)
  49. {
  50. if (operation == null)
  51. {
  52. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operation");
  53. }
  54. if (parent == null)
  55. {
  56. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
  57. }
  58. if (operation.Invoker == null)
  59. {
  60. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.RuntimeRequiresInvoker0)));
  61. }
  62. this.disposeParameters = ((operation.AutoDisposeParameters) && (!operation.HasNoDisposableParameters));
  63. this.parent = parent;
  64. this.callContextInitializers = EmptyArray<ICallContextInitializer>.ToArray(operation.CallContextInitializers);
  65. this.inspectors = EmptyArray<IParameterInspector>.ToArray(operation.ParameterInspectors);
  66. this.faultFormatter = operation.FaultFormatter;
  67. this.impersonation = operation.Impersonation;
  68. this.deserializeRequest = operation.DeserializeRequest;
  69. this.serializeReply = operation.SerializeReply;
  70. this.formatter = operation.Formatter;
  71. this.invoker = operation.Invoker;
  72. try
  73. {
  74. this.isSynchronous = operation.Invoker.IsSynchronous;
  75. }
  76. catch (Exception e)
  77. {
  78. if (Fx.IsFatal(e))
  79. {
  80. throw;
  81. }
  82. throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
  83. }
  84. this.isTerminating = operation.IsTerminating;
  85. this.isSessionOpenNotificationEnabled = operation.IsSessionOpenNotificationEnabled;
  86. this.action = operation.Action;
  87. this.name = operation.Name;
  88. this.releaseInstanceAfterCall = operation.ReleaseInstanceAfterCall;
  89. this.releaseInstanceBeforeCall = operation.ReleaseInstanceBeforeCall;
  90. this.replyAction = operation.ReplyAction;
  91. this.isOneWay = operation.IsOneWay;
  92. this.transactionAutoComplete = operation.TransactionAutoComplete;
  93. this.transactionRequired = operation.TransactionRequired;
  94. this.receiveContextAcknowledgementMode = operation.ReceiveContextAcknowledgementMode;
  95. this.bufferedReceiveEnabled = operation.BufferedReceiveEnabled;
  96. this.isInsideTransactedReceiveScope = operation.IsInsideTransactedReceiveScope;
  97. if (this.formatter == null && (deserializeRequest || serializeReply))
  98. {
  99. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.DispatchRuntimeRequiresFormatter0, this.name)));
  100. }
  101. if ((operation.Parent.InstanceProvider == null) && (operation.Parent.Type != null))
  102. {
  103. SyncMethodInvoker sync = this.invoker as SyncMethodInvoker;
  104. if (sync != null)
  105. {
  106. this.ValidateInstanceType(operation.Parent.Type, sync.Method);
  107. }
  108. AsyncMethodInvoker async = this.invoker as AsyncMethodInvoker;
  109. if (async != null)
  110. {
  111. this.ValidateInstanceType(operation.Parent.Type, async.BeginMethod);
  112. this.ValidateInstanceType(operation.Parent.Type, async.EndMethod);
  113. }
  114. TaskMethodInvoker task = this.invoker as TaskMethodInvoker;
  115. if (task != null)
  116. {
  117. this.ValidateInstanceType(operation.Parent.Type, task.TaskMethod);
  118. }
  119. }
  120. }
  121. internal string Action
  122. {
  123. get { return this.action; }
  124. }
  125. internal ICallContextInitializer[] CallContextInitializers
  126. {
  127. get { return this.callContextInitializers; }
  128. }
  129. internal bool DisposeParameters
  130. {
  131. get { return this.disposeParameters; }
  132. }
  133. internal bool HasDefaultUnhandledActionInvoker
  134. {
  135. get { return (this.invoker is DispatchRuntime.UnhandledActionInvoker); }
  136. }
  137. internal bool SerializeReply
  138. {
  139. get { return this.serializeReply; }
  140. }
  141. internal IDispatchFaultFormatter FaultFormatter
  142. {
  143. get { return this.faultFormatter; }
  144. }
  145. internal IDispatchMessageFormatter Formatter
  146. {
  147. get { return this.formatter; }
  148. }
  149. internal ImpersonationOption Impersonation
  150. {
  151. get { return this.impersonation; }
  152. }
  153. internal IOperationInvoker Invoker
  154. {
  155. get { return this.invoker; }
  156. }
  157. internal bool IsSynchronous
  158. {
  159. get { return this.isSynchronous; }
  160. }
  161. internal bool IsOneWay
  162. {
  163. get { return this.isOneWay; }
  164. }
  165. internal bool IsTerminating
  166. {
  167. get { return this.isTerminating; }
  168. }
  169. internal string Name
  170. {
  171. get { return this.name; }
  172. }
  173. internal IParameterInspector[] ParameterInspectors
  174. {
  175. get { return this.inspectors; }
  176. }
  177. internal ImmutableDispatchRuntime Parent
  178. {
  179. get { return this.parent; }
  180. }
  181. internal ReceiveContextAcknowledgementMode ReceiveContextAcknowledgementMode
  182. {
  183. get { return this.receiveContextAcknowledgementMode; }
  184. }
  185. internal bool ReleaseInstanceAfterCall
  186. {
  187. get { return this.releaseInstanceAfterCall; }
  188. }
  189. internal bool ReleaseInstanceBeforeCall
  190. {
  191. get { return this.releaseInstanceBeforeCall; }
  192. }
  193. internal string ReplyAction
  194. {
  195. get { return this.replyAction; }
  196. }
  197. internal bool TransactionAutoComplete
  198. {
  199. get { return this.transactionAutoComplete; }
  200. }
  201. internal bool TransactionRequired
  202. {
  203. get { return this.transactionRequired; }
  204. }
  205. internal bool IsInsideTransactedReceiveScope
  206. {
  207. get { return this.isInsideTransactedReceiveScope; }
  208. }
  209. void DeserializeInputs(ref MessageRpc rpc)
  210. {
  211. bool success = false;
  212. try
  213. {
  214. try
  215. {
  216. rpc.InputParameters = this.Invoker.AllocateInputs();
  217. }
  218. catch (Exception e)
  219. {
  220. if (Fx.IsFatal(e))
  221. {
  222. throw;
  223. }
  224. if (ErrorBehavior.ShouldRethrowExceptionAsIs(e))
  225. {
  226. throw;
  227. }
  228. throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
  229. }
  230. try
  231. {
  232. // If the field is true, then this operation is to be invoked at the time the service
  233. // channel is opened. The incoming message is created at ChannelHandler level with no
  234. // content, so we don't need to deserialize the message.
  235. if (!this.isSessionOpenNotificationEnabled)
  236. {
  237. if (this.deserializeRequest)
  238. {
  239. if (TD.DispatchFormatterDeserializeRequestStartIsEnabled())
  240. {
  241. TD.DispatchFormatterDeserializeRequestStart(rpc.EventTraceActivity);
  242. }
  243. this.Formatter.DeserializeRequest(rpc.Request, rpc.InputParameters);
  244. if (TD.DispatchFormatterDeserializeRequestStopIsEnabled())
  245. {
  246. TD.DispatchFormatterDeserializeRequestStop(rpc.EventTraceActivity);
  247. }
  248. }
  249. else
  250. {
  251. rpc.InputParameters[0] = rpc.Request;
  252. }
  253. }
  254. success = true;
  255. }
  256. catch (Exception e)
  257. {
  258. if (Fx.IsFatal(e))
  259. {
  260. throw;
  261. }
  262. if (ErrorBehavior.ShouldRethrowExceptionAsIs(e))
  263. {
  264. throw;
  265. }
  266. throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
  267. }
  268. }
  269. finally
  270. {
  271. rpc.DidDeserializeRequestBody = (rpc.Request.State != MessageState.Created);
  272. if (!success && MessageLogger.LoggingEnabled)
  273. {
  274. MessageLogger.LogMessage(ref rpc.Request, MessageLoggingSource.Malformed);
  275. }
  276. }
  277. }
  278. void InitializeCallContext(ref MessageRpc rpc)
  279. {
  280. if (this.CallContextInitializers.Length > 0)
  281. {
  282. InitializeCallContextCore(ref rpc);
  283. }
  284. }
  285. void InitializeCallContextCore(ref MessageRpc rpc)
  286. {
  287. IClientChannel channel = rpc.Channel.Proxy as IClientChannel;
  288. int offset = this.Parent.CallContextCorrelationOffset;
  289. try
  290. {
  291. for (int i = 0; i < rpc.Operation.CallContextInitializers.Length; i++)
  292. {
  293. ICallContextInitializer initializer = this.CallContextInitializers[i];
  294. rpc.Correlation[offset + i] = initializer.BeforeInvoke(rpc.InstanceContext, channel, rpc.Request);
  295. }
  296. }
  297. catch (Exception e)
  298. {
  299. if (Fx.IsFatal(e))
  300. {
  301. throw;
  302. }
  303. if (ErrorBehavior.ShouldRethrowExceptionAsIs(e))
  304. {
  305. throw;
  306. }
  307. throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
  308. }
  309. }
  310. void UninitializeCallContext(ref MessageRpc rpc)
  311. {
  312. if (this.CallContextInitializers.Length > 0)
  313. {
  314. UninitializeCallContextCore(ref rpc);
  315. }
  316. }
  317. void UninitializeCallContextCore(ref MessageRpc rpc)
  318. {
  319. IClientChannel channel = rpc.Channel.Proxy as IClientChannel;
  320. int offset = this.Parent.CallContextCorrelationOffset;
  321. try
  322. {
  323. for (int i = this.CallContextInitializers.Length - 1; i >= 0; i--)
  324. {
  325. ICallContextInitializer initializer = this.CallContextInitializers[i];
  326. initializer.AfterInvoke(rpc.Correlation[offset + i]);
  327. }
  328. }
  329. catch (Exception e)
  330. {
  331. // thread-local storage may be corrupt
  332. DiagnosticUtility.FailFast(string.Format(CultureInfo.InvariantCulture, "ICallContextInitializer.BeforeInvoke threw an exception of type {0}: {1}", e.GetType(), e.Message));
  333. }
  334. }
  335. void InspectInputs(ref MessageRpc rpc)
  336. {
  337. if (this.ParameterInspectors.Length > 0)
  338. {
  339. InspectInputsCore(ref rpc);
  340. }
  341. }
  342. void InspectInputsCore(ref MessageRpc rpc)
  343. {
  344. int offset = this.Parent.ParameterInspectorCorrelationOffset;
  345. for (int i = 0; i < this.ParameterInspectors.Length; i++)
  346. {
  347. IParameterInspector inspector = this.ParameterInspectors[i];
  348. rpc.Correlation[offset + i] = inspector.BeforeCall(this.Name, rpc.InputParameters);
  349. if (TD.ParameterInspectorBeforeCallInvokedIsEnabled())
  350. {
  351. TD.ParameterInspectorBeforeCallInvoked(rpc.EventTraceActivity, this.ParameterInspectors[i].GetType().FullName);
  352. }
  353. }
  354. }
  355. void InspectOutputs(ref MessageRpc rpc)
  356. {
  357. if (this.ParameterInspectors.Length > 0)
  358. {
  359. InspectOutputsCore(ref rpc);
  360. }
  361. }
  362. void InspectOutputsCore(ref MessageRpc rpc)
  363. {
  364. int offset = this.Parent.ParameterInspectorCorrelationOffset;
  365. for (int i = this.ParameterInspectors.Length - 1; i >= 0; i--)
  366. {
  367. IParameterInspector inspector = this.ParameterInspectors[i];
  368. inspector.AfterCall(this.Name, rpc.OutputParameters, rpc.ReturnParameter, rpc.Correlation[offset + i]);
  369. if (TD.ParameterInspectorAfterCallInvokedIsEnabled())
  370. {
  371. TD.ParameterInspectorAfterCallInvoked(rpc.EventTraceActivity, this.ParameterInspectors[i].GetType().FullName);
  372. }
  373. }
  374. }
  375. [Fx.Tag.SecurityNote(Critical = "Calls SecurityCritical method StartImpersonation.",
  376. Safe = "Manages the result of impersonation and properly Disposes it.")]
  377. [DebuggerStepperBoundary]
  378. [SecuritySafeCritical]
  379. internal void InvokeBegin(ref MessageRpc rpc)
  380. {
  381. if (rpc.Error == null)
  382. {
  383. try
  384. {
  385. this.InitializeCallContext(ref rpc);
  386. object target = rpc.Instance;
  387. this.DeserializeInputs(ref rpc);
  388. this.InspectInputs(ref rpc);
  389. ValidateMustUnderstand(ref rpc);
  390. IAsyncResult result = null;
  391. IDisposable impersonationContext = null;
  392. IPrincipal originalPrincipal = null;
  393. bool isThreadPrincipalSet = false;
  394. bool isConcurrent = this.Parent.IsConcurrent(ref rpc);
  395. try
  396. {
  397. if (this.parent.RequireClaimsPrincipalOnOperationContext)
  398. {
  399. SetClaimsPrincipalToOperationContext(rpc);
  400. }
  401. if (this.parent.SecurityImpersonation != null)
  402. {
  403. this.parent.SecurityImpersonation.StartImpersonation(ref rpc, out impersonationContext, out originalPrincipal, out isThreadPrincipalSet);
  404. }
  405. IManualConcurrencyOperationInvoker manualInvoker = this.Invoker as IManualConcurrencyOperationInvoker;
  406. if (this.isSynchronous)
  407. {
  408. if (manualInvoker != null && isConcurrent)
  409. {
  410. if (this.bufferedReceiveEnabled)
  411. {
  412. rpc.OperationContext.IncomingMessageProperties.Add(
  413. BufferedReceiveMessageProperty.Name, new BufferedReceiveMessageProperty(ref rpc));
  414. }
  415. rpc.ReturnParameter = manualInvoker.Invoke(target, rpc.InputParameters, rpc.InvokeNotification, out rpc.OutputParameters);
  416. }
  417. else
  418. {
  419. rpc.ReturnParameter = this.Invoker.Invoke(target, rpc.InputParameters, out rpc.OutputParameters);
  420. }
  421. }
  422. else
  423. {
  424. bool isBeginSuccessful = false;
  425. if (manualInvoker != null && isConcurrent && this.bufferedReceiveEnabled)
  426. {
  427. // This will modify the rpc, it has to be done before rpc.Pause
  428. // since IResumeMessageRpc implementation keeps reference of rpc.
  429. // This is to ensure consistent rpc whether or not InvokeBegin completed
  430. // synchronously or asynchronously.
  431. rpc.OperationContext.IncomingMessageProperties.Add(
  432. BufferedReceiveMessageProperty.Name, new BufferedReceiveMessageProperty(ref rpc));
  433. }
  434. IResumeMessageRpc resumeRpc = rpc.Pause();
  435. try
  436. {
  437. if (manualInvoker != null && isConcurrent)
  438. {
  439. result = manualInvoker.InvokeBegin(target, rpc.InputParameters, rpc.InvokeNotification, invokeCallback, resumeRpc);
  440. }
  441. else
  442. {
  443. result = this.Invoker.InvokeBegin(target, rpc.InputParameters, invokeCallback, resumeRpc);
  444. }
  445. isBeginSuccessful = true;
  446. // if the call above actually went async, then responsibility to call
  447. // ProcessMessage{6,7,Cleanup} has been transferred to InvokeCallback
  448. }
  449. finally
  450. {
  451. if (!isBeginSuccessful)
  452. {
  453. rpc.UnPause();
  454. }
  455. }
  456. }
  457. }
  458. finally
  459. {
  460. try
  461. {
  462. if (this.parent.SecurityImpersonation != null)
  463. {
  464. this.parent.SecurityImpersonation.StopImpersonation(ref rpc, impersonationContext, originalPrincipal, isThreadPrincipalSet);
  465. }
  466. }
  467. #pragma warning suppress 56500 // covered by FxCOP
  468. catch
  469. {
  470. string message = null;
  471. try
  472. {
  473. message = SR.GetString(SR.SFxRevertImpersonationFailed0);
  474. }
  475. finally
  476. {
  477. DiagnosticUtility.FailFast(message);
  478. }
  479. }
  480. }
  481. if (this.isSynchronous)
  482. {
  483. this.InspectOutputs(ref rpc);
  484. this.SerializeOutputs(ref rpc);
  485. }
  486. else
  487. {
  488. if (result == null)
  489. {
  490. throw TraceUtility.ThrowHelperError(new ArgumentNullException("IOperationInvoker.BeginDispatch"), rpc.Request);
  491. }
  492. if (result.CompletedSynchronously)
  493. {
  494. // if the async call completed synchronously, then the responsibility to call
  495. // ProcessMessage{6,7,Cleanup} still remains on this thread
  496. rpc.UnPause();
  497. rpc.AsyncResult = result;
  498. }
  499. }
  500. }
  501. #pragma warning suppress 56500 // covered by FxCOP
  502. catch { throw; } // Make sure user Exception filters are not impersonated.
  503. finally
  504. {
  505. this.UninitializeCallContext(ref rpc);
  506. }
  507. }
  508. }
  509. void SetClaimsPrincipalToOperationContext(MessageRpc rpc)
  510. {
  511. ServiceSecurityContext securityContext = rpc.SecurityContext;
  512. if (!rpc.HasSecurityContext)
  513. {
  514. SecurityMessageProperty securityContextProperty = rpc.Request.Properties.Security;
  515. if (securityContextProperty != null)
  516. {
  517. securityContext = securityContextProperty.ServiceSecurityContext;
  518. }
  519. }
  520. if (securityContext != null)
  521. {
  522. object principal;
  523. if (securityContext.AuthorizationContext.Properties.TryGetValue(AuthorizationPolicy.ClaimsPrincipalKey, out principal))
  524. {
  525. ClaimsPrincipal claimsPrincipal = principal as ClaimsPrincipal;
  526. if (claimsPrincipal != null)
  527. {
  528. //
  529. // Always set ClaimsPrincipal to OperationContext.Current if identityModel pipeline is used.
  530. //
  531. OperationContext.Current.ClaimsPrincipal = claimsPrincipal;
  532. }
  533. else
  534. {
  535. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NoPrincipalSpecifiedInAuthorizationContext)));
  536. }
  537. }
  538. }
  539. }
  540. static void InvokeCallback(IAsyncResult result)
  541. {
  542. if (result.CompletedSynchronously)
  543. {
  544. return;
  545. }
  546. IResumeMessageRpc resume = result.AsyncState as IResumeMessageRpc;
  547. if (resume == null)
  548. {
  549. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxInvalidAsyncResultState0));
  550. }
  551. resume.SignalConditionalResume(result);
  552. }
  553. [Fx.Tag.SecurityNote(Critical = "Calls SecurityCritical method StartImpersonation.",
  554. Safe = "Manages the result of impersonation and properly Disposes it.")]
  555. [DebuggerStepperBoundary]
  556. [SecuritySafeCritical]
  557. internal void InvokeEnd(ref MessageRpc rpc)
  558. {
  559. if ((rpc.Error == null) && !this.isSynchronous)
  560. {
  561. try
  562. {
  563. this.InitializeCallContext(ref rpc);
  564. if (this.parent.RequireClaimsPrincipalOnOperationContext)
  565. {
  566. SetClaimsPrincipalToOperationContext(rpc);
  567. }
  568. IDisposable impersonationContext = null;
  569. IPrincipal originalPrincipal = null;
  570. bool isThreadPrincipalSet = false;
  571. try
  572. {
  573. if (this.parent.SecurityImpersonation != null)
  574. {
  575. this.parent.SecurityImpersonation.StartImpersonation(ref rpc, out impersonationContext, out originalPrincipal, out isThreadPrincipalSet);
  576. }
  577. rpc.ReturnParameter = this.Invoker.InvokeEnd(rpc.Instance, out rpc.OutputParameters, rpc.AsyncResult);
  578. }
  579. finally
  580. {
  581. try
  582. {
  583. if (this.parent.SecurityImpersonation != null)
  584. {
  585. this.parent.SecurityImpersonation.StopImpersonation(ref rpc, impersonationContext, originalPrincipal, isThreadPrincipalSet);
  586. }
  587. }
  588. #pragma warning suppress 56500 // covered by FxCOP
  589. catch
  590. {
  591. string message = null;
  592. try
  593. {
  594. message = SR.GetString(SR.SFxRevertImpersonationFailed0);
  595. }
  596. finally
  597. {
  598. DiagnosticUtility.FailFast(message);
  599. }
  600. }
  601. }
  602. this.InspectOutputs(ref rpc);
  603. this.SerializeOutputs(ref rpc);
  604. }
  605. #pragma warning suppress 56500 // covered by FxCOP
  606. catch { throw; } // Make sure user Exception filters are not impersonated.
  607. finally
  608. {
  609. this.UninitializeCallContext(ref rpc);
  610. }
  611. }
  612. }
  613. void SerializeOutputs(ref MessageRpc rpc)
  614. {
  615. if (!this.IsOneWay && this.parent.EnableFaults)
  616. {
  617. Message reply;
  618. if (this.serializeReply)
  619. {
  620. try
  621. {
  622. if (TD.DispatchFormatterSerializeReplyStartIsEnabled())
  623. {
  624. TD.DispatchFormatterSerializeReplyStart(rpc.EventTraceActivity);
  625. }
  626. reply = this.Formatter.SerializeReply(rpc.RequestVersion, rpc.OutputParameters, rpc.ReturnParameter);
  627. if (TD.DispatchFormatterSerializeReplyStopIsEnabled())
  628. {
  629. TD.DispatchFormatterSerializeReplyStop(rpc.EventTraceActivity);
  630. }
  631. }
  632. catch (Exception e)
  633. {
  634. if (Fx.IsFatal(e))
  635. {
  636. throw;
  637. }
  638. if (ErrorBehavior.ShouldRethrowExceptionAsIs(e))
  639. {
  640. throw;
  641. }
  642. throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
  643. }
  644. if (reply == null)
  645. {
  646. string message = SR.GetString(SR.SFxNullReplyFromFormatter2, this.Formatter.GetType().ToString(), (this.name ?? ""));
  647. ErrorBehavior.ThrowAndCatch(new InvalidOperationException(message));
  648. }
  649. }
  650. else
  651. {
  652. if ((rpc.ReturnParameter == null) && (rpc.OperationContext.RequestContext != null))
  653. {
  654. string message = SR.GetString(SR.SFxDispatchRuntimeMessageCannotBeNull, this.name);
  655. ErrorBehavior.ThrowAndCatch(new InvalidOperationException(message));
  656. }
  657. reply = (Message)rpc.ReturnParameter;
  658. if ((reply != null) && (!ProxyOperationRuntime.IsValidAction(reply, this.ReplyAction)))
  659. {
  660. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInvalidReplyAction, this.Name, reply.Headers.Action ?? "{NULL}", this.ReplyAction)));
  661. }
  662. }
  663. if (DiagnosticUtility.ShouldUseActivity && rpc.Activity != null && reply != null)
  664. {
  665. TraceUtility.SetActivity(reply, rpc.Activity);
  666. if (TraceUtility.ShouldPropagateActivity)
  667. {
  668. TraceUtility.AddActivityHeader(reply);
  669. }
  670. }
  671. else if (TraceUtility.ShouldPropagateActivity && reply != null && rpc.ResponseActivityId != Guid.Empty)
  672. {
  673. ActivityIdHeader header = new ActivityIdHeader(rpc.ResponseActivityId);
  674. header.AddTo(reply);
  675. }
  676. //rely on the property set during the message receive to correlate the trace
  677. if (TraceUtility.MessageFlowTracingOnly)
  678. {
  679. //Guard against MEX scenarios where the message is closed by now
  680. if (null != rpc.OperationContext.IncomingMessage && MessageState.Closed != rpc.OperationContext.IncomingMessage.State)
  681. {
  682. FxTrace.Trace.SetAndTraceTransfer(TraceUtility.GetReceivedActivityId(rpc.OperationContext), true);
  683. }
  684. else
  685. {
  686. if (rpc.ResponseActivityId != Guid.Empty)
  687. {
  688. FxTrace.Trace.SetAndTraceTransfer(rpc.ResponseActivityId, true);
  689. }
  690. }
  691. }
  692. // Add the ImpersonateOnSerializingReplyMessageProperty on the reply message iff
  693. // a. reply message is not null.
  694. // b. Impersonation is enabled on serializing Reply
  695. if (reply != null && this.parent.IsImpersonationEnabledOnSerializingReply)
  696. {
  697. bool shouldImpersonate = this.parent.SecurityImpersonation != null && this.parent.SecurityImpersonation.IsImpersonationEnabledOnCurrentOperation(ref rpc);
  698. if (shouldImpersonate)
  699. {
  700. reply.Properties.Add(ImpersonateOnSerializingReplyMessageProperty.Name, new ImpersonateOnSerializingReplyMessageProperty(ref rpc));
  701. reply = new ImpersonatingMessage(reply);
  702. }
  703. }
  704. if (MessageLogger.LoggingEnabled && null != reply)
  705. {
  706. MessageLogger.LogMessage(ref reply, MessageLoggingSource.ServiceLevelSendReply | MessageLoggingSource.LastChance);
  707. }
  708. rpc.Reply = reply;
  709. }
  710. }
  711. void ValidateInstanceType(Type type, MethodInfo method)
  712. {
  713. if (!method.DeclaringType.IsAssignableFrom(type))
  714. {
  715. string message = SR.GetString(SR.SFxMethodNotSupportedByType2,
  716. type.FullName,
  717. method.DeclaringType.FullName);
  718. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(message));
  719. }
  720. }
  721. void ValidateMustUnderstand(ref MessageRpc rpc)
  722. {
  723. if (parent.ValidateMustUnderstand)
  724. {
  725. rpc.NotUnderstoodHeaders = rpc.Request.Headers.GetHeadersNotUnderstood();
  726. if (rpc.NotUnderstoodHeaders != null)
  727. {
  728. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  729. new MustUnderstandSoapException(rpc.NotUnderstoodHeaders, rpc.Request.Version.Envelope));
  730. }
  731. }
  732. }
  733. }
  734. }