ChannelHandler.cs 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel.Dispatcher
  5. {
  6. using System;
  7. using System.Globalization;
  8. using System.Runtime;
  9. using System.Runtime.CompilerServices;
  10. using System.Runtime.Diagnostics;
  11. using System.ServiceModel;
  12. using System.ServiceModel.Activation;
  13. using System.ServiceModel.Channels;
  14. using System.ServiceModel.Description;
  15. using System.ServiceModel.Diagnostics;
  16. using System.ServiceModel.Diagnostics.Application;
  17. using System.Threading;
  18. using System.Transactions;
  19. using System.Xml;
  20. using SessionIdleManager = System.ServiceModel.Channels.ServiceChannel.SessionIdleManager;
  21. class ChannelHandler
  22. {
  23. public static readonly TimeSpan CloseAfterFaultTimeout = TimeSpan.FromSeconds(10);
  24. public const string MessageBufferPropertyName = "_RequestMessageBuffer_";
  25. readonly IChannelBinder binder;
  26. readonly DuplexChannelBinder duplexBinder;
  27. readonly ServiceHostBase host;
  28. readonly bool incrementedActivityCountInConstructor;
  29. readonly bool isCallback;
  30. readonly ListenerHandler listener;
  31. readonly ServiceThrottle throttle;
  32. readonly bool wasChannelThrottled;
  33. readonly SessionIdleManager idleManager;
  34. readonly bool sendAsynchronously;
  35. static AsyncCallback onAsyncReplyComplete = Fx.ThunkCallback(new AsyncCallback(ChannelHandler.OnAsyncReplyComplete));
  36. static AsyncCallback onAsyncReceiveComplete = Fx.ThunkCallback(new AsyncCallback(ChannelHandler.OnAsyncReceiveComplete));
  37. static Action<object> onContinueAsyncReceive = new Action<object>(ChannelHandler.OnContinueAsyncReceive);
  38. static Action<object> onStartSyncMessagePump = new Action<object>(ChannelHandler.OnStartSyncMessagePump);
  39. static Action<object> onStartAsyncMessagePump = new Action<object>(ChannelHandler.OnStartAsyncMessagePump);
  40. static Action<object> onStartSingleTransactedBatch = new Action<object>(ChannelHandler.OnStartSingleTransactedBatch);
  41. static Action<object> openAndEnsurePump = new Action<object>(ChannelHandler.OpenAndEnsurePump);
  42. RequestInfo requestInfo;
  43. ServiceChannel channel;
  44. bool doneReceiving;
  45. bool hasRegisterBeenCalled;
  46. bool hasSession;
  47. int isPumpAcquired;
  48. bool isChannelTerminated;
  49. bool isConcurrent;
  50. bool isManualAddressing;
  51. MessageVersion messageVersion;
  52. ErrorHandlingReceiver receiver;
  53. bool receiveSynchronously;
  54. bool receiveWithTransaction;
  55. RequestContext replied;
  56. RequestContext requestWaitingForThrottle;
  57. WrappedTransaction acceptTransaction;
  58. ServiceThrottle instanceContextThrottle;
  59. SharedTransactedBatchContext sharedTransactedBatchContext;
  60. TransactedBatchContext transactedBatchContext;
  61. bool isMainTransactedBatchHandler;
  62. EventTraceActivity eventTraceActivity;
  63. SessionOpenNotification sessionOpenNotification;
  64. bool needToCreateSessionOpenNotificationMessage;
  65. bool shouldRejectMessageWithOnOpenActionHeader;
  66. internal ChannelHandler(MessageVersion messageVersion, IChannelBinder binder, ServiceChannel channel)
  67. {
  68. ClientRuntime clientRuntime = channel.ClientRuntime;
  69. this.messageVersion = messageVersion;
  70. this.isManualAddressing = clientRuntime.ManualAddressing;
  71. this.binder = binder;
  72. this.channel = channel;
  73. this.isConcurrent = true;
  74. this.duplexBinder = binder as DuplexChannelBinder;
  75. this.hasSession = binder.HasSession;
  76. this.isCallback = true;
  77. DispatchRuntime dispatchRuntime = clientRuntime.DispatchRuntime;
  78. if (dispatchRuntime == null)
  79. {
  80. this.receiver = new ErrorHandlingReceiver(binder, null);
  81. }
  82. else
  83. {
  84. this.receiver = new ErrorHandlingReceiver(binder, dispatchRuntime.ChannelDispatcher);
  85. }
  86. this.requestInfo = new RequestInfo(this);
  87. }
  88. internal ChannelHandler(MessageVersion messageVersion, IChannelBinder binder, ServiceThrottle throttle,
  89. ListenerHandler listener, bool wasChannelThrottled, WrappedTransaction acceptTransaction, SessionIdleManager idleManager)
  90. {
  91. ChannelDispatcher channelDispatcher = listener.ChannelDispatcher;
  92. this.messageVersion = messageVersion;
  93. this.isManualAddressing = channelDispatcher.ManualAddressing;
  94. this.binder = binder;
  95. this.throttle = throttle;
  96. this.listener = listener;
  97. this.wasChannelThrottled = wasChannelThrottled;
  98. this.host = listener.Host;
  99. this.receiveSynchronously = channelDispatcher.ReceiveSynchronously;
  100. this.sendAsynchronously = channelDispatcher.SendAsynchronously;
  101. this.duplexBinder = binder as DuplexChannelBinder;
  102. this.hasSession = binder.HasSession;
  103. this.isConcurrent = ConcurrencyBehavior.IsConcurrent(channelDispatcher, this.hasSession);
  104. if (channelDispatcher.MaxPendingReceives > 1)
  105. {
  106. // We need to preserve order if the ChannelHandler is not concurrent.
  107. this.binder = new MultipleReceiveBinder(
  108. this.binder,
  109. channelDispatcher.MaxPendingReceives,
  110. !this.isConcurrent);
  111. }
  112. if (channelDispatcher.BufferedReceiveEnabled)
  113. {
  114. this.binder = new BufferedReceiveBinder(this.binder);
  115. }
  116. this.receiver = new ErrorHandlingReceiver(this.binder, channelDispatcher);
  117. this.idleManager = idleManager;
  118. Fx.Assert((this.idleManager != null) == (this.binder.HasSession && this.listener.ChannelDispatcher.DefaultCommunicationTimeouts.ReceiveTimeout != TimeSpan.MaxValue), "idle manager is present only when there is a session with a finite receive timeout");
  119. if (channelDispatcher.IsTransactedReceive && !channelDispatcher.ReceiveContextEnabled)
  120. {
  121. receiveSynchronously = true;
  122. receiveWithTransaction = true;
  123. if (channelDispatcher.MaxTransactedBatchSize > 0)
  124. {
  125. int maxConcurrentBatches = 1;
  126. if (null != throttle && throttle.MaxConcurrentCalls > 1)
  127. {
  128. maxConcurrentBatches = throttle.MaxConcurrentCalls;
  129. foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
  130. {
  131. if (ConcurrencyMode.Multiple != endpointDispatcher.DispatchRuntime.ConcurrencyMode)
  132. {
  133. maxConcurrentBatches = 1;
  134. break;
  135. }
  136. }
  137. }
  138. this.sharedTransactedBatchContext = new SharedTransactedBatchContext(this, channelDispatcher, maxConcurrentBatches);
  139. this.isMainTransactedBatchHandler = true;
  140. this.throttle = null;
  141. }
  142. }
  143. else if (channelDispatcher.IsTransactedReceive && channelDispatcher.ReceiveContextEnabled && channelDispatcher.MaxTransactedBatchSize > 0)
  144. {
  145. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.IncompatibleBehaviors)));
  146. }
  147. if (this.binder.HasSession)
  148. {
  149. this.sessionOpenNotification = this.binder.Channel.GetProperty<SessionOpenNotification>();
  150. this.needToCreateSessionOpenNotificationMessage = this.sessionOpenNotification != null && this.sessionOpenNotification.IsEnabled;
  151. }
  152. this.acceptTransaction = acceptTransaction;
  153. this.requestInfo = new RequestInfo(this);
  154. if (this.listener.State == CommunicationState.Opened)
  155. {
  156. this.listener.ChannelDispatcher.Channels.IncrementActivityCount();
  157. this.incrementedActivityCountInConstructor = true;
  158. }
  159. }
  160. internal ChannelHandler(ChannelHandler handler, TransactedBatchContext context)
  161. {
  162. this.messageVersion = handler.messageVersion;
  163. this.isManualAddressing = handler.isManualAddressing;
  164. this.binder = handler.binder;
  165. this.listener = handler.listener;
  166. this.wasChannelThrottled = handler.wasChannelThrottled;
  167. this.host = handler.host;
  168. this.receiveSynchronously = true;
  169. this.receiveWithTransaction = true;
  170. this.duplexBinder = handler.duplexBinder;
  171. this.hasSession = handler.hasSession;
  172. this.isConcurrent = handler.isConcurrent;
  173. this.receiver = handler.receiver;
  174. this.sharedTransactedBatchContext = context.Shared;
  175. this.transactedBatchContext = context;
  176. this.requestInfo = new RequestInfo(this);
  177. this.sendAsynchronously = handler.sendAsynchronously;
  178. this.sessionOpenNotification = handler.sessionOpenNotification;
  179. this.needToCreateSessionOpenNotificationMessage = handler.needToCreateSessionOpenNotificationMessage;
  180. this.shouldRejectMessageWithOnOpenActionHeader = handler.shouldRejectMessageWithOnOpenActionHeader;
  181. }
  182. internal IChannelBinder Binder
  183. {
  184. get { return this.binder; }
  185. }
  186. internal ServiceChannel Channel
  187. {
  188. get { return this.channel; }
  189. }
  190. internal bool HasRegisterBeenCalled
  191. {
  192. get { return this.hasRegisterBeenCalled; }
  193. }
  194. internal InstanceContext InstanceContext
  195. {
  196. get { return (this.channel != null) ? this.channel.InstanceContext : null; }
  197. }
  198. internal ServiceThrottle InstanceContextServiceThrottle
  199. {
  200. get
  201. {
  202. return this.instanceContextThrottle;
  203. }
  204. set
  205. {
  206. this.instanceContextThrottle = value;
  207. }
  208. }
  209. bool IsOpen
  210. {
  211. get { return this.binder.Channel.State == CommunicationState.Opened; }
  212. }
  213. EndpointAddress LocalAddress
  214. {
  215. get
  216. {
  217. if (this.binder != null)
  218. {
  219. IInputChannel input = this.binder.Channel as IInputChannel;
  220. if (input != null)
  221. {
  222. return input.LocalAddress;
  223. }
  224. IReplyChannel reply = this.binder.Channel as IReplyChannel;
  225. if (reply != null)
  226. {
  227. return reply.LocalAddress;
  228. }
  229. }
  230. return null;
  231. }
  232. }
  233. object ThisLock
  234. {
  235. get { return this; }
  236. }
  237. EventTraceActivity EventTraceActivity
  238. {
  239. get
  240. {
  241. if (this.eventTraceActivity == null)
  242. {
  243. this.eventTraceActivity = new EventTraceActivity();
  244. }
  245. return this.eventTraceActivity;
  246. }
  247. }
  248. internal static void Register(ChannelHandler handler)
  249. {
  250. handler.Register();
  251. }
  252. internal static void Register(ChannelHandler handler, RequestContext request)
  253. {
  254. BufferedReceiveBinder bufferedBinder = handler.Binder as BufferedReceiveBinder;
  255. Fx.Assert(bufferedBinder != null, "ChannelHandler.Binder is not a BufferedReceiveBinder");
  256. bufferedBinder.InjectRequest(request);
  257. handler.Register();
  258. }
  259. void Register()
  260. {
  261. this.hasRegisterBeenCalled = true;
  262. if (this.binder.Channel.State == CommunicationState.Created)
  263. {
  264. ActionItem.Schedule(openAndEnsurePump, this);
  265. }
  266. else
  267. {
  268. this.EnsurePump();
  269. }
  270. }
  271. void AsyncMessagePump()
  272. {
  273. IAsyncResult result = this.BeginTryReceive();
  274. if ((result != null) && result.CompletedSynchronously)
  275. {
  276. this.AsyncMessagePump(result);
  277. }
  278. }
  279. void AsyncMessagePump(IAsyncResult result)
  280. {
  281. if (TD.ChannelReceiveStopIsEnabled())
  282. {
  283. TD.ChannelReceiveStop(this.EventTraceActivity, this.GetHashCode());
  284. }
  285. for (;;)
  286. {
  287. RequestContext request;
  288. while (!this.EndTryReceive(result, out request))
  289. {
  290. result = this.BeginTryReceive();
  291. if ((result == null) || !result.CompletedSynchronously)
  292. {
  293. return;
  294. }
  295. }
  296. if (!HandleRequest(request, null))
  297. {
  298. break;
  299. }
  300. if (!TryAcquirePump())
  301. {
  302. break;
  303. }
  304. result = this.BeginTryReceive();
  305. if (result == null || !result.CompletedSynchronously)
  306. {
  307. break;
  308. }
  309. }
  310. }
  311. IAsyncResult BeginTryReceive()
  312. {
  313. this.requestInfo.Cleanup();
  314. if (TD.ChannelReceiveStartIsEnabled())
  315. {
  316. TD.ChannelReceiveStart(this.EventTraceActivity, this.GetHashCode());
  317. }
  318. this.shouldRejectMessageWithOnOpenActionHeader = !this.needToCreateSessionOpenNotificationMessage;
  319. if (this.needToCreateSessionOpenNotificationMessage)
  320. {
  321. return new CompletedAsyncResult(ChannelHandler.onAsyncReceiveComplete, this);
  322. }
  323. return this.receiver.BeginTryReceive(TimeSpan.MaxValue, ChannelHandler.onAsyncReceiveComplete, this);
  324. }
  325. bool DispatchAndReleasePump(RequestContext request, bool cleanThread, OperationContext currentOperationContext)
  326. {
  327. ServiceChannel channel = this.requestInfo.Channel;
  328. EndpointDispatcher endpoint = this.requestInfo.Endpoint;
  329. bool releasedPump = false;
  330. try
  331. {
  332. DispatchRuntime dispatchBehavior = this.requestInfo.DispatchRuntime;
  333. if (channel == null || dispatchBehavior == null)
  334. {
  335. Fx.Assert("System.ServiceModel.Dispatcher.ChannelHandler.Dispatch(): (channel == null || dispatchBehavior == null)");
  336. return true;
  337. }
  338. MessageBuffer buffer = null;
  339. Message message;
  340. EventTraceActivity eventTraceActivity = TraceDispatchMessageStart(request.RequestMessage);
  341. AspNetEnvironment.Current.PrepareMessageForDispatch(request.RequestMessage);
  342. if (dispatchBehavior.PreserveMessage)
  343. {
  344. object previousBuffer = null;
  345. if (request.RequestMessage.Properties.TryGetValue(MessageBufferPropertyName, out previousBuffer))
  346. {
  347. buffer = (MessageBuffer)previousBuffer;
  348. message = buffer.CreateMessage();
  349. }
  350. else
  351. {
  352. //
  353. buffer = request.RequestMessage.CreateBufferedCopy(int.MaxValue);
  354. message = buffer.CreateMessage();
  355. }
  356. }
  357. else
  358. {
  359. message = request.RequestMessage;
  360. }
  361. DispatchOperationRuntime operation = dispatchBehavior.GetOperation(ref message);
  362. if (operation == null)
  363. {
  364. Fx.Assert("ChannelHandler.Dispatch (operation == null)");
  365. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "No DispatchOperationRuntime found to process message.")));
  366. }
  367. if (this.shouldRejectMessageWithOnOpenActionHeader && message.Headers.Action == OperationDescription.SessionOpenedAction)
  368. {
  369. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoEndpointMatchingAddressForConnectionOpeningMessage, message.Headers.Action, "Open")));
  370. }
  371. if (MessageLogger.LoggingEnabled)
  372. {
  373. MessageLogger.LogMessage(ref message, (operation.IsOneWay ? MessageLoggingSource.ServiceLevelReceiveDatagram : MessageLoggingSource.ServiceLevelReceiveRequest) | MessageLoggingSource.LastChance);
  374. }
  375. if (operation.IsTerminating && this.hasSession)
  376. {
  377. this.isChannelTerminated = true;
  378. }
  379. bool hasOperationContextBeenSet;
  380. if (currentOperationContext != null)
  381. {
  382. hasOperationContextBeenSet = true;
  383. currentOperationContext.ReInit(request, message, channel);
  384. }
  385. else
  386. {
  387. hasOperationContextBeenSet = false;
  388. currentOperationContext = new OperationContext(request, message, channel, this.host);
  389. }
  390. if (dispatchBehavior.PreserveMessage)
  391. {
  392. currentOperationContext.IncomingMessageProperties.Add(MessageBufferPropertyName, buffer);
  393. }
  394. if (currentOperationContext.EndpointDispatcher == null && this.listener != null)
  395. {
  396. currentOperationContext.EndpointDispatcher = endpoint;
  397. }
  398. MessageRpc rpc = new MessageRpc(request, message, operation, channel, this.host,
  399. this, cleanThread, currentOperationContext, this.requestInfo.ExistingInstanceContext, eventTraceActivity);
  400. TraceUtility.MessageFlowAtMessageReceived(message, currentOperationContext, eventTraceActivity, true);
  401. rpc.TransactedBatchContext = this.transactedBatchContext;
  402. // passing responsibility for call throttle to MessageRpc
  403. // (MessageRpc implicitly owns this throttle once it's created)
  404. this.requestInfo.ChannelHandlerOwnsCallThrottle = false;
  405. // explicitly passing responsibility for instance throttle to MessageRpc
  406. rpc.MessageRpcOwnsInstanceContextThrottle = this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle;
  407. this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle = false;
  408. // These need to happen before Dispatch but after accessing any ChannelHandler
  409. // state, because we go multi-threaded after this until we reacquire pump mutex.
  410. this.ReleasePump();
  411. releasedPump = true;
  412. return operation.Parent.Dispatch(ref rpc, hasOperationContextBeenSet);
  413. }
  414. catch (Exception e)
  415. {
  416. if (Fx.IsFatal(e))
  417. {
  418. throw;
  419. }
  420. return this.HandleError(e, request, channel);
  421. }
  422. finally
  423. {
  424. if (!releasedPump)
  425. {
  426. this.ReleasePump();
  427. }
  428. }
  429. }
  430. internal void DispatchDone()
  431. {
  432. if (this.throttle != null)
  433. {
  434. this.throttle.DeactivateCall();
  435. }
  436. }
  437. RequestContext GetSessionOpenNotificationRequestContext()
  438. {
  439. Fx.Assert(this.sessionOpenNotification != null, "this.sessionOpenNotification should not be null.");
  440. Message message = Message.CreateMessage(this.Binder.Channel.GetProperty<MessageVersion>(), OperationDescription.SessionOpenedAction);
  441. Fx.Assert(this.LocalAddress != null, "this.LocalAddress should not be null.");
  442. message.Headers.To = this.LocalAddress.Uri;
  443. this.sessionOpenNotification.UpdateMessageProperties(message.Properties);
  444. return this.Binder.CreateRequestContext(message);
  445. }
  446. bool EndTryReceive(IAsyncResult result, out RequestContext requestContext)
  447. {
  448. bool valid;
  449. if (this.needToCreateSessionOpenNotificationMessage)
  450. {
  451. this.needToCreateSessionOpenNotificationMessage = false;
  452. Fx.Assert(result is CompletedAsyncResult, "result must be CompletedAsyncResult");
  453. CompletedAsyncResult.End(result);
  454. requestContext = this.GetSessionOpenNotificationRequestContext();
  455. valid = true;
  456. }
  457. else
  458. {
  459. valid = this.receiver.EndTryReceive(result, out requestContext);
  460. }
  461. if (valid)
  462. {
  463. this.HandleReceiveComplete(requestContext);
  464. }
  465. return valid;
  466. }
  467. void EnsureChannelAndEndpoint(RequestContext request)
  468. {
  469. this.requestInfo.Channel = this.channel;
  470. if (this.requestInfo.Channel == null)
  471. {
  472. bool addressMatched;
  473. if (this.hasSession)
  474. {
  475. this.requestInfo.Channel = this.GetSessionChannel(request.RequestMessage, out this.requestInfo.Endpoint, out addressMatched);
  476. }
  477. else
  478. {
  479. this.requestInfo.Channel = this.GetDatagramChannel(request.RequestMessage, out this.requestInfo.Endpoint, out addressMatched);
  480. }
  481. if (this.requestInfo.Channel == null)
  482. {
  483. this.host.RaiseUnknownMessageReceived(request.RequestMessage);
  484. if (addressMatched)
  485. {
  486. this.ReplyContractFilterDidNotMatch(request);
  487. }
  488. else
  489. {
  490. this.ReplyAddressFilterDidNotMatch(request);
  491. }
  492. }
  493. }
  494. else
  495. {
  496. this.requestInfo.Endpoint = this.requestInfo.Channel.EndpointDispatcher;
  497. //For sessionful contracts, the InstanceContext throttle is not copied over to the channel
  498. //as we create the channel before acquiring the lock
  499. if (this.InstanceContextServiceThrottle != null && this.requestInfo.Channel.InstanceContextServiceThrottle == null)
  500. {
  501. this.requestInfo.Channel.InstanceContextServiceThrottle = this.InstanceContextServiceThrottle;
  502. }
  503. }
  504. this.requestInfo.EndpointLookupDone = true;
  505. if (this.requestInfo.Channel == null)
  506. {
  507. // SFx drops a message here
  508. TraceUtility.TraceDroppedMessage(request.RequestMessage, this.requestInfo.Endpoint);
  509. request.Close();
  510. return;
  511. }
  512. if (this.requestInfo.Channel.HasSession || this.isCallback)
  513. {
  514. this.requestInfo.DispatchRuntime = this.requestInfo.Channel.DispatchRuntime;
  515. }
  516. else
  517. {
  518. this.requestInfo.DispatchRuntime = this.requestInfo.Endpoint.DispatchRuntime;
  519. }
  520. }
  521. void EnsurePump()
  522. {
  523. if (null == this.sharedTransactedBatchContext || this.isMainTransactedBatchHandler)
  524. {
  525. if (TryAcquirePump())
  526. {
  527. if (this.receiveSynchronously)
  528. {
  529. ActionItem.Schedule(ChannelHandler.onStartSyncMessagePump, this);
  530. }
  531. else
  532. {
  533. if (Thread.CurrentThread.IsThreadPoolThread)
  534. {
  535. IAsyncResult result = this.BeginTryReceive();
  536. if ((result != null) && result.CompletedSynchronously)
  537. {
  538. ActionItem.Schedule(ChannelHandler.onContinueAsyncReceive, result);
  539. }
  540. }
  541. else
  542. {
  543. // Since this is not a threadpool thread, we don't know if this thread will exit
  544. // while the IO is still pending (which would cancel the IO), so we have to get
  545. // over to a threadpool thread which we know will not exit while there is pending IO.
  546. ActionItem.Schedule(ChannelHandler.onStartAsyncMessagePump, this);
  547. }
  548. }
  549. }
  550. }
  551. else
  552. {
  553. ActionItem.Schedule(ChannelHandler.onStartSingleTransactedBatch, this);
  554. }
  555. }
  556. ServiceChannel GetDatagramChannel(Message message, out EndpointDispatcher endpoint, out bool addressMatched)
  557. {
  558. addressMatched = false;
  559. endpoint = this.GetEndpointDispatcher(message, out addressMatched);
  560. if (endpoint == null)
  561. {
  562. return null;
  563. }
  564. if (endpoint.DatagramChannel == null)
  565. {
  566. lock (this.listener.ThisLock)
  567. {
  568. if (endpoint.DatagramChannel == null)
  569. {
  570. endpoint.DatagramChannel = new ServiceChannel(this.binder, endpoint, this.listener.ChannelDispatcher, this.idleManager);
  571. this.InitializeServiceChannel(endpoint.DatagramChannel);
  572. }
  573. }
  574. }
  575. return endpoint.DatagramChannel;
  576. }
  577. EndpointDispatcher GetEndpointDispatcher(Message message, out bool addressMatched)
  578. {
  579. return this.listener.Endpoints.Lookup(message, out addressMatched);
  580. }
  581. ServiceChannel GetSessionChannel(Message message, out EndpointDispatcher endpoint, out bool addressMatched)
  582. {
  583. addressMatched = false;
  584. if (this.channel == null)
  585. {
  586. lock (this.ThisLock)
  587. {
  588. if (this.channel == null)
  589. {
  590. endpoint = this.GetEndpointDispatcher(message, out addressMatched);
  591. if (endpoint != null)
  592. {
  593. this.channel = new ServiceChannel(this.binder, endpoint, this.listener.ChannelDispatcher, this.idleManager);
  594. this.InitializeServiceChannel(this.channel);
  595. }
  596. }
  597. }
  598. }
  599. if (this.channel == null)
  600. {
  601. endpoint = null;
  602. }
  603. else
  604. {
  605. endpoint = this.channel.EndpointDispatcher;
  606. }
  607. return this.channel;
  608. }
  609. void InitializeServiceChannel(ServiceChannel channel)
  610. {
  611. if (this.wasChannelThrottled)
  612. {
  613. // TFS#500703, when the idle timeout was hit, the constructor of ServiceChannel will abort itself directly. So
  614. // the session throttle will not be released and thus lead to a service unavailablity.
  615. // Note that if the channel is already aborted, the next line "channel.ServiceThrottle = this.throttle;" will throw an exception,
  616. // so we are not going to do any more work inside this method.
  617. // Ideally we should do a thorough refactoring work for this throttling issue. However, it's too risky as a QFE. We should consider
  618. // this in a whole release.
  619. // Note that the "wasChannelThrottled" boolean will only be true if we aquired the session throttle. So we don't have to check HasSession
  620. // again here.
  621. if (channel.Aborted && this.throttle != null)
  622. {
  623. // This line will release the "session" throttle.
  624. this.throttle.DeactivateChannel();
  625. }
  626. channel.ServiceThrottle = this.throttle;
  627. }
  628. if (this.InstanceContextServiceThrottle != null)
  629. {
  630. channel.InstanceContextServiceThrottle = this.InstanceContextServiceThrottle;
  631. }
  632. ClientRuntime clientRuntime = channel.ClientRuntime;
  633. if (clientRuntime != null)
  634. {
  635. Type contractType = clientRuntime.ContractClientType;
  636. Type callbackType = clientRuntime.CallbackClientType;
  637. if (contractType != null)
  638. {
  639. channel.Proxy = ServiceChannelFactory.CreateProxy(contractType, callbackType, MessageDirection.Output, channel);
  640. }
  641. }
  642. if (this.listener != null)
  643. {
  644. this.listener.ChannelDispatcher.InitializeChannel((IClientChannel)channel.Proxy);
  645. }
  646. ((IChannel)channel).Open();
  647. }
  648. void ProvideFault(Exception e, ref ErrorHandlerFaultInfo faultInfo)
  649. {
  650. if (this.listener != null)
  651. {
  652. this.listener.ChannelDispatcher.ProvideFault(e, this.requestInfo.Channel == null ? this.binder.Channel.GetProperty<FaultConverter>() : this.requestInfo.Channel.GetProperty<FaultConverter>(), ref faultInfo);
  653. }
  654. else if (this.channel != null)
  655. {
  656. DispatchRuntime dispatchBehavior = this.channel.ClientRuntime.CallbackDispatchRuntime;
  657. dispatchBehavior.ChannelDispatcher.ProvideFault(e, this.channel.GetProperty<FaultConverter>(), ref faultInfo);
  658. }
  659. }
  660. internal bool HandleError(Exception e)
  661. {
  662. ErrorHandlerFaultInfo dummy = new ErrorHandlerFaultInfo();
  663. return this.HandleError(e, ref dummy);
  664. }
  665. bool HandleError(Exception e, ref ErrorHandlerFaultInfo faultInfo)
  666. {
  667. if (!(e != null))
  668. {
  669. Fx.Assert(SR.GetString(SR.GetString(SR.SFxNonExceptionThrown)));
  670. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.GetString(SR.SFxNonExceptionThrown))));
  671. }
  672. if (this.listener != null)
  673. {
  674. return listener.ChannelDispatcher.HandleError(e, ref faultInfo);
  675. }
  676. else if (this.channel != null)
  677. {
  678. return this.channel.ClientRuntime.CallbackDispatchRuntime.ChannelDispatcher.HandleError(e, ref faultInfo);
  679. }
  680. else
  681. {
  682. return false;
  683. }
  684. }
  685. bool HandleError(Exception e, RequestContext request, ServiceChannel channel)
  686. {
  687. ErrorHandlerFaultInfo faultInfo = new ErrorHandlerFaultInfo(this.messageVersion.Addressing.DefaultFaultAction);
  688. bool replied, replySentAsync;
  689. ProvideFaultAndReplyFailure(request, e, ref faultInfo, out replied, out replySentAsync);
  690. if (!replySentAsync)
  691. {
  692. return this.HandleErrorContinuation(e, request, channel, ref faultInfo, replied);
  693. }
  694. else
  695. {
  696. return false;
  697. }
  698. }
  699. bool HandleErrorContinuation(Exception e, RequestContext request, ServiceChannel channel, ref ErrorHandlerFaultInfo faultInfo, bool replied)
  700. {
  701. if (replied)
  702. {
  703. try
  704. {
  705. request.Close();
  706. }
  707. catch (Exception e1)
  708. {
  709. if (Fx.IsFatal(e1))
  710. {
  711. throw;
  712. }
  713. this.HandleError(e1);
  714. }
  715. }
  716. else
  717. {
  718. request.Abort();
  719. }
  720. if (!this.HandleError(e, ref faultInfo) && this.hasSession)
  721. {
  722. if (channel != null)
  723. {
  724. if (replied)
  725. {
  726. TimeoutHelper timeoutHelper = new TimeoutHelper(CloseAfterFaultTimeout);
  727. try
  728. {
  729. channel.Close(timeoutHelper.RemainingTime());
  730. }
  731. catch (Exception e2)
  732. {
  733. if (Fx.IsFatal(e2))
  734. {
  735. throw;
  736. }
  737. this.HandleError(e2);
  738. }
  739. try
  740. {
  741. this.binder.CloseAfterFault(timeoutHelper.RemainingTime());
  742. }
  743. catch (Exception e3)
  744. {
  745. if (Fx.IsFatal(e3))
  746. {
  747. throw;
  748. }
  749. this.HandleError(e3);
  750. }
  751. }
  752. else
  753. {
  754. channel.Abort();
  755. this.binder.Abort();
  756. }
  757. }
  758. else
  759. {
  760. if (replied)
  761. {
  762. try
  763. {
  764. this.binder.CloseAfterFault(CloseAfterFaultTimeout);
  765. }
  766. catch (Exception e4)
  767. {
  768. if (Fx.IsFatal(e4))
  769. {
  770. throw;
  771. }
  772. this.HandleError(e4);
  773. }
  774. }
  775. else
  776. {
  777. this.binder.Abort();
  778. }
  779. }
  780. }
  781. return true;
  782. }
  783. void HandleReceiveComplete(RequestContext context)
  784. {
  785. try
  786. {
  787. if (this.channel != null)
  788. {
  789. this.channel.HandleReceiveComplete(context);
  790. }
  791. else
  792. {
  793. if (context == null && this.hasSession)
  794. {
  795. bool close;
  796. lock (this.ThisLock)
  797. {
  798. close = !this.doneReceiving;
  799. this.doneReceiving = true;
  800. }
  801. if (close)
  802. {
  803. this.receiver.Close();
  804. if (this.idleManager != null)
  805. {
  806. this.idleManager.CancelTimer();
  807. }
  808. ServiceThrottle throttle = this.throttle;
  809. if (throttle != null)
  810. {
  811. throttle.DeactivateChannel();
  812. }
  813. }
  814. }
  815. }
  816. }
  817. finally
  818. {
  819. if ((context == null) && this.incrementedActivityCountInConstructor)
  820. {
  821. this.listener.ChannelDispatcher.Channels.DecrementActivityCount();
  822. }
  823. }
  824. }
  825. bool HandleRequest(RequestContext request, OperationContext currentOperationContext)
  826. {
  827. if (request == null)
  828. {
  829. // channel EOF, stop receiving
  830. return false;
  831. }
  832. ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? TraceUtility.ExtractActivity(request.RequestMessage) : null;
  833. using (ServiceModelActivity.BoundOperation(activity))
  834. {
  835. if (this.HandleRequestAsReply(request))
  836. {
  837. this.ReleasePump();
  838. return true;
  839. }
  840. if (this.isChannelTerminated)
  841. {
  842. this.ReleasePump();
  843. this.ReplyChannelTerminated(request);
  844. return true;
  845. }
  846. if (this.requestInfo.RequestContext != null)
  847. {
  848. Fx.Assert("ChannelHandler.HandleRequest: this.requestInfo.RequestContext != null");
  849. }
  850. this.requestInfo.RequestContext = request;
  851. if (!this.TryAcquireCallThrottle(request))
  852. {
  853. // this.ThrottleAcquiredForCall will be called to continue
  854. return false;
  855. }
  856. // NOTE: from here on down, ensure that this code is the same as ThrottleAcquiredForCall (see 55460)
  857. if (this.requestInfo.ChannelHandlerOwnsCallThrottle)
  858. {
  859. Fx.Assert("ChannelHandler.HandleRequest: this.requestInfo.ChannelHandlerOwnsCallThrottle");
  860. }
  861. this.requestInfo.ChannelHandlerOwnsCallThrottle = true;
  862. if (!this.TryRetrievingInstanceContext(request))
  863. {
  864. //Would have replied and close the request.
  865. return true;
  866. }
  867. this.requestInfo.Channel.CompletedIOOperation();
  868. //Only acquire InstanceContext throttle if one doesnt already exist.
  869. if (!this.TryAcquireThrottle(request, (this.requestInfo.ExistingInstanceContext == null)))
  870. {
  871. // this.ThrottleAcquired will be called to continue
  872. return false;
  873. }
  874. if (this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle)
  875. {
  876. Fx.Assert("ChannelHandler.HandleRequest: this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle");
  877. }
  878. this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle = (this.requestInfo.ExistingInstanceContext == null);
  879. if (!this.DispatchAndReleasePump(request, true, currentOperationContext))
  880. {
  881. // this.DispatchDone will be called to continue
  882. return false;
  883. }
  884. }
  885. return true;
  886. }
  887. bool HandleRequestAsReply(RequestContext request)
  888. {
  889. if (this.duplexBinder != null)
  890. {
  891. if (this.duplexBinder.HandleRequestAsReply(request.RequestMessage))
  892. {
  893. return true;
  894. }
  895. }
  896. return false;
  897. }
  898. static void OnStartAsyncMessagePump(object state)
  899. {
  900. ((ChannelHandler)state).AsyncMessagePump();
  901. }
  902. static void OnStartSyncMessagePump(object state)
  903. {
  904. ChannelHandler handler = state as ChannelHandler;
  905. if (TD.ChannelReceiveStopIsEnabled())
  906. {
  907. TD.ChannelReceiveStop(handler.EventTraceActivity, state.GetHashCode());
  908. }
  909. if (handler.receiveWithTransaction)
  910. {
  911. handler.SyncTransactionalMessagePump();
  912. }
  913. else
  914. {
  915. handler.SyncMessagePump();
  916. }
  917. }
  918. static void OnStartSingleTransactedBatch(object state)
  919. {
  920. ChannelHandler handler = state as ChannelHandler;
  921. handler.TransactedBatchLoop();
  922. }
  923. static void OnAsyncReceiveComplete(IAsyncResult result)
  924. {
  925. if (!result.CompletedSynchronously)
  926. {
  927. ((ChannelHandler)result.AsyncState).AsyncMessagePump(result);
  928. }
  929. }
  930. static void OnContinueAsyncReceive(object state)
  931. {
  932. IAsyncResult result = (IAsyncResult)state;
  933. ((ChannelHandler)result.AsyncState).AsyncMessagePump(result);
  934. }
  935. static void OpenAndEnsurePump(object state)
  936. {
  937. ((ChannelHandler)state).OpenAndEnsurePump();
  938. }
  939. void OpenAndEnsurePump()
  940. {
  941. Exception exception = null;
  942. try
  943. {
  944. this.binder.Channel.Open();
  945. }
  946. catch (Exception e)
  947. {
  948. if (Fx.IsFatal(e))
  949. {
  950. throw;
  951. }
  952. exception = e;
  953. }
  954. if (exception != null)
  955. {
  956. if (DiagnosticUtility.ShouldTraceWarning)
  957. {
  958. TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Warning,
  959. TraceCode.FailedToOpenIncomingChannel,
  960. SR.GetString(SR.TraceCodeFailedToOpenIncomingChannel));
  961. }
  962. SessionIdleManager idleManager = this.idleManager;
  963. if (idleManager != null)
  964. {
  965. idleManager.CancelTimer();
  966. }
  967. if ((this.throttle != null) && this.hasSession)
  968. {
  969. this.throttle.DeactivateChannel();
  970. }
  971. bool errorHandled = this.HandleError(exception);
  972. if (this.incrementedActivityCountInConstructor)
  973. {
  974. this.listener.ChannelDispatcher.Channels.DecrementActivityCount();
  975. }
  976. if (!errorHandled)
  977. {
  978. this.binder.Channel.Abort();
  979. }
  980. }
  981. else
  982. {
  983. this.EnsurePump();
  984. }
  985. }
  986. bool TryReceive(TimeSpan timeout, out RequestContext requestContext)
  987. {
  988. this.shouldRejectMessageWithOnOpenActionHeader = !this.needToCreateSessionOpenNotificationMessage;
  989. bool valid;
  990. if (this.needToCreateSessionOpenNotificationMessage)
  991. {
  992. this.needToCreateSessionOpenNotificationMessage = false;
  993. requestContext = this.GetSessionOpenNotificationRequestContext();
  994. valid = true;
  995. }
  996. else
  997. {
  998. valid = this.receiver.TryReceive(timeout, out requestContext);
  999. }
  1000. if (valid)
  1001. {
  1002. this.HandleReceiveComplete(requestContext);
  1003. }
  1004. return valid;
  1005. }
  1006. void ReplyAddressFilterDidNotMatch(RequestContext request)
  1007. {
  1008. FaultCode code = FaultCode.CreateSenderFaultCode(AddressingStrings.DestinationUnreachable,
  1009. this.messageVersion.Addressing.Namespace);
  1010. string reason = SR.GetString(SR.SFxNoEndpointMatchingAddress, request.RequestMessage.Headers.To);
  1011. ReplyFailure(request, code, reason);
  1012. }
  1013. void ReplyContractFilterDidNotMatch(RequestContext request)
  1014. {
  1015. // By default, the contract filter is just a filter over the set of initiating actions in
  1016. // the contract, so we do error messages accordingly
  1017. AddressingVersion addressingVersion = this.messageVersion.Addressing;
  1018. if (addressingVersion != AddressingVersion.None && request.RequestMessage.Headers.Action == null)
  1019. {
  1020. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  1021. new MessageHeaderException(
  1022. SR.GetString(SR.SFxMissingActionHeader, addressingVersion.Namespace), AddressingStrings.Action, addressingVersion.Namespace));
  1023. }
  1024. else
  1025. {
  1026. // some of this code is duplicated in DispatchRuntime.UnhandledActionInvoker
  1027. // ideally both places would use FaultConverter and ActionNotSupportedException
  1028. FaultCode code = FaultCode.CreateSenderFaultCode(AddressingStrings.ActionNotSupported,
  1029. this.messageVersion.Addressing.Namespace);
  1030. string reason = SR.GetString(SR.SFxNoEndpointMatchingContract, request.RequestMessage.Headers.Action);
  1031. ReplyFailure(request, code, reason, this.messageVersion.Addressing.FaultAction);
  1032. }
  1033. }
  1034. void ReplyChannelTerminated(RequestContext request)
  1035. {
  1036. FaultCode code = FaultCode.CreateSenderFaultCode(FaultCodeConstants.Codes.SessionTerminated,
  1037. FaultCodeConstants.Namespaces.NetDispatch);
  1038. string reason = SR.GetString(SR.SFxChannelTerminated0);
  1039. string action = FaultCodeConstants.Actions.NetDispatcher;
  1040. Message fault = Message.CreateMessage(this.messageVersion, code, reason, action);
  1041. ReplyFailure(request, fault, action, reason, code);
  1042. }
  1043. void ReplyFailure(RequestContext request, FaultCode code, string reason)
  1044. {
  1045. string action = this.messageVersion.Addressing.DefaultFaultAction;
  1046. ReplyFailure(request, code, reason, action);
  1047. }
  1048. void ReplyFailure(RequestContext request, FaultCode code, string reason, string action)
  1049. {
  1050. Message fault = Message.CreateMessage(this.messageVersion, code, reason, action);
  1051. ReplyFailure(request, fault, action, reason, code);
  1052. }
  1053. void ReplyFailure(RequestContext request, Message fault, string action, string reason, FaultCode code)
  1054. {
  1055. FaultException exception = new FaultException(reason, code);
  1056. ErrorBehavior.ThrowAndCatch(exception);
  1057. ErrorHandlerFaultInfo faultInfo = new ErrorHandlerFaultInfo(action);
  1058. faultInfo.Fault = fault;
  1059. bool replied, replySentAsync;
  1060. ProvideFaultAndReplyFailure(request, exception, ref faultInfo, out replied, out replySentAsync);
  1061. this.HandleError(exception, ref faultInfo);
  1062. }
  1063. void ProvideFaultAndReplyFailure(RequestContext request, Exception exception, ref ErrorHandlerFaultInfo faultInfo, out bool replied, out bool replySentAsync)
  1064. {
  1065. replied = false;
  1066. replySentAsync = false;
  1067. bool requestMessageIsFault = false;
  1068. try
  1069. {
  1070. requestMessageIsFault = request.RequestMessage.IsFault;
  1071. }
  1072. #pragma warning suppress 56500 // covered by FxCOP
  1073. catch (Exception e)
  1074. {
  1075. if (Fx.IsFatal(e))
  1076. {
  1077. throw;
  1078. }
  1079. // ---- it
  1080. }
  1081. bool enableFaults = false;
  1082. if (this.listener != null)
  1083. {
  1084. enableFaults = this.listener.ChannelDispatcher.EnableFaults;
  1085. }
  1086. else if (this.channel != null && this.channel.IsClient)
  1087. {
  1088. enableFaults = this.channel.ClientRuntime.EnableFaults;
  1089. }
  1090. if ((!requestMessageIsFault) && enableFaults)
  1091. {
  1092. this.ProvideFault(exception, ref faultInfo);
  1093. if (faultInfo.Fault != null)
  1094. {
  1095. Message reply = faultInfo.Fault;
  1096. try
  1097. {
  1098. try
  1099. {
  1100. if (this.PrepareReply(request, reply))
  1101. {
  1102. if (this.sendAsynchronously)
  1103. {
  1104. var state = new ContinuationState { ChannelHandler = this, Channel = channel, Exception = exception, FaultInfo = faultInfo, Request = request, Reply = reply };
  1105. var result = request.BeginReply(reply, ChannelHandler.onAsyncReplyComplete, state);
  1106. if (result.CompletedSynchronously)
  1107. {
  1108. ChannelHandler.AsyncReplyComplete(result, state);
  1109. replied = true;
  1110. }
  1111. else
  1112. {
  1113. replySentAsync = true;
  1114. }
  1115. }
  1116. else
  1117. {
  1118. request.Reply(reply);
  1119. replied = true;
  1120. }
  1121. }
  1122. }
  1123. finally
  1124. {
  1125. if (!replySentAsync)
  1126. {
  1127. reply.Close();
  1128. }
  1129. }
  1130. }
  1131. #pragma warning suppress 56500 // covered by FxCOP
  1132. catch (Exception e)
  1133. {
  1134. if (Fx.IsFatal(e))
  1135. {
  1136. throw;
  1137. }
  1138. this.HandleError(e);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. /// <summary>
  1144. /// Prepares a reply that can either be sent asynchronously or synchronously depending on the value of
  1145. /// sendAsynchronously
  1146. /// </summary>
  1147. /// <param name="request">The request context to prepare</param>
  1148. /// <param name="reply">The reply to prepare</param>
  1149. /// <returns>True if channel is open and prepared reply should be sent; otherwise false.</returns>
  1150. bool PrepareReply(RequestContext request, Message reply)
  1151. {
  1152. // Ensure we only reply once (we may hit the same error multiple times)
  1153. if (this.replied == request)
  1154. {
  1155. return false;
  1156. }
  1157. this.replied = request;
  1158. bool canSendReply = true;
  1159. Message requestMessage = null;
  1160. try
  1161. {
  1162. requestMessage = request.RequestMessage;
  1163. }
  1164. #pragma warning suppress 56500 // covered by FxCOP
  1165. catch (Exception e)
  1166. {
  1167. if (Fx.IsFatal(e))
  1168. {
  1169. throw;
  1170. }
  1171. // ---- it
  1172. }
  1173. if (!object.ReferenceEquals(requestMessage, null))
  1174. {
  1175. UniqueId requestID = null;
  1176. try
  1177. {
  1178. requestID = requestMessage.Headers.MessageId;
  1179. }
  1180. catch (MessageHeaderException)
  1181. {
  1182. // ---- it - we don't need to correlate the reply if the MessageId header is bad
  1183. }
  1184. if (!object.ReferenceEquals(requestID, null) && !this.isManualAddressing)
  1185. {
  1186. System.ServiceModel.Channels.RequestReplyCorrelator.PrepareReply(reply, requestID);
  1187. }
  1188. if (!this.hasSession && !this.isManualAddressing)
  1189. {
  1190. try
  1191. {
  1192. canSendReply = System.ServiceModel.Channels.RequestReplyCorrelator.AddressReply(reply, requestMessage);
  1193. }
  1194. catch (MessageHeaderException)
  1195. {
  1196. // ---- it - we don't need to address the reply if the FaultTo header is bad
  1197. }
  1198. }
  1199. }
  1200. // ObjectDisposeException can happen
  1201. // if the channel is closed in a different
  1202. // thread. 99% this check will avoid false
  1203. // exceptions.
  1204. return this.IsOpen && canSendReply;
  1205. }
  1206. static void AsyncReplyComplete(IAsyncResult result, ContinuationState state)
  1207. {
  1208. try
  1209. {
  1210. state.Request.EndReply(result);
  1211. }
  1212. catch (Exception e)
  1213. {
  1214. DiagnosticUtility.TraceHandledException(e, System.Diagnostics.TraceEventType.Error);
  1215. if (Fx.IsFatal(e))
  1216. {
  1217. throw;
  1218. }
  1219. state.ChannelHandler.HandleError(e);
  1220. }
  1221. try
  1222. {
  1223. state.Reply.Close();
  1224. }
  1225. catch (Exception e)
  1226. {
  1227. DiagnosticUtility.TraceHandledException(e, System.Diagnostics.TraceEventType.Error);
  1228. if (Fx.IsFatal(e))
  1229. {
  1230. throw;
  1231. }
  1232. state.ChannelHandler.HandleError(e);
  1233. }
  1234. try
  1235. {
  1236. state.ChannelHandler.HandleErrorContinuation(state.Exception, state.Request, state.Channel, ref state.FaultInfo, true);
  1237. }
  1238. catch (Exception e)
  1239. {
  1240. DiagnosticUtility.TraceHandledException(e, System.Diagnostics.TraceEventType.Error);
  1241. if (Fx.IsFatal(e))
  1242. {
  1243. throw;
  1244. }
  1245. state.ChannelHandler.HandleError(e);
  1246. }
  1247. state.ChannelHandler.EnsurePump();
  1248. }
  1249. static void OnAsyncReplyComplete(IAsyncResult result)
  1250. {
  1251. if (result.CompletedSynchronously)
  1252. {
  1253. return;
  1254. }
  1255. try
  1256. {
  1257. var state = (ContinuationState)result.AsyncState;
  1258. ChannelHandler.AsyncReplyComplete(result, state);
  1259. }
  1260. catch (Exception e)
  1261. {
  1262. DiagnosticUtility.TraceHandledException(e, System.Diagnostics.TraceEventType.Error);
  1263. if (Fx.IsFatal(e))
  1264. {
  1265. throw;
  1266. }
  1267. }
  1268. }
  1269. void ReleasePump()
  1270. {
  1271. if (this.isConcurrent)
  1272. {
  1273. this.isPumpAcquired = 0;
  1274. }
  1275. }
  1276. void SyncMessagePump()
  1277. {
  1278. OperationContext existingOperationContext = OperationContext.Current;
  1279. try
  1280. {
  1281. OperationContext currentOperationContext = new OperationContext(this.host);
  1282. OperationContext.Current = currentOperationContext;
  1283. for (;;)
  1284. {
  1285. RequestContext request;
  1286. this.requestInfo.Cleanup();
  1287. while (!TryReceive(TimeSpan.MaxValue, out request))
  1288. {
  1289. }
  1290. if (!HandleRequest(request, currentOperationContext))
  1291. {
  1292. break;
  1293. }
  1294. if (!TryAcquirePump())
  1295. {
  1296. break;
  1297. }
  1298. currentOperationContext.Recycle();
  1299. }
  1300. }
  1301. finally
  1302. {
  1303. OperationContext.Current = existingOperationContext;
  1304. }
  1305. }
  1306. [MethodImpl(MethodImplOptions.NoInlining)]
  1307. void SyncTransactionalMessagePump()
  1308. {
  1309. for (;;)
  1310. {
  1311. bool completedSynchronously;
  1312. if (null == sharedTransactedBatchContext)
  1313. {
  1314. completedSynchronously = TransactedLoop();
  1315. }
  1316. else
  1317. {
  1318. completedSynchronously = TransactedBatchLoop();
  1319. }
  1320. if (!completedSynchronously)
  1321. {
  1322. return;
  1323. }
  1324. }
  1325. }
  1326. bool TransactedLoop()
  1327. {
  1328. try
  1329. {
  1330. this.receiver.WaitForMessage();
  1331. }
  1332. catch (Exception ex)
  1333. {
  1334. if (Fx.IsFatal(ex))
  1335. {
  1336. throw;
  1337. }
  1338. if (!this.HandleError(ex))
  1339. {
  1340. throw;
  1341. }
  1342. }
  1343. RequestContext request;
  1344. Transaction tx = CreateOrGetAttachedTransaction();
  1345. OperationContext existingOperationContext = OperationContext.Current;
  1346. try
  1347. {
  1348. OperationContext currentOperationContext = new OperationContext(this.host);
  1349. OperationContext.Current = currentOperationContext;
  1350. for (;;)
  1351. {
  1352. this.requestInfo.Cleanup();
  1353. bool received = TryTransactionalReceive(tx, out request);
  1354. if (!received)
  1355. {
  1356. return IsOpen;
  1357. }
  1358. if (null == request)
  1359. {
  1360. return false;
  1361. }
  1362. TransactionMessageProperty.Set(tx, request.RequestMessage);
  1363. if (!HandleRequest(request, currentOperationContext))
  1364. {
  1365. return false;
  1366. }
  1367. if (!TryAcquirePump())
  1368. {
  1369. return false;
  1370. }
  1371. tx = CreateOrGetAttachedTransaction();
  1372. currentOperationContext.Recycle();
  1373. }
  1374. }
  1375. finally
  1376. {
  1377. OperationContext.Current = existingOperationContext;
  1378. }
  1379. }
  1380. bool TransactedBatchLoop()
  1381. {
  1382. if (null != this.transactedBatchContext)
  1383. {
  1384. if (this.transactedBatchContext.InDispatch)
  1385. {
  1386. this.transactedBatchContext.ForceRollback();
  1387. this.transactedBatchContext.InDispatch = false;
  1388. }
  1389. if (!this.transactedBatchContext.IsActive)
  1390. {
  1391. if (!this.isMainTransactedBatchHandler)
  1392. {
  1393. return false;
  1394. }
  1395. this.transactedBatchContext = null;
  1396. }
  1397. }
  1398. if (null == this.transactedBatchContext)
  1399. {
  1400. try
  1401. {
  1402. this.receiver.WaitForMessage();
  1403. }
  1404. catch (Exception ex)
  1405. {
  1406. if (Fx.IsFatal(ex))
  1407. {
  1408. throw;
  1409. }
  1410. if (!this.HandleError(ex))
  1411. {
  1412. throw;
  1413. }
  1414. }
  1415. this.transactedBatchContext = this.sharedTransactedBatchContext.CreateTransactedBatchContext();
  1416. }
  1417. OperationContext existingOperationContext = OperationContext.Current;
  1418. try
  1419. {
  1420. OperationContext currentOperationContext = new OperationContext(this.host);
  1421. OperationContext.Current = currentOperationContext;
  1422. RequestContext request;
  1423. while (this.transactedBatchContext.IsActive)
  1424. {
  1425. this.requestInfo.Cleanup();
  1426. bool valid = TryTransactionalReceive(this.transactedBatchContext.Transaction, out request);
  1427. if (!valid)
  1428. {
  1429. if (this.IsOpen)
  1430. {
  1431. this.transactedBatchContext.ForceCommit();
  1432. return true;
  1433. }
  1434. else
  1435. {
  1436. this.transactedBatchContext.ForceRollback();
  1437. return false;
  1438. }
  1439. }
  1440. if (null == request)
  1441. {
  1442. this.transactedBatchContext.ForceRollback();
  1443. return false;
  1444. }
  1445. TransactionMessageProperty.Set(this.transactedBatchContext.Transaction, request.RequestMessage);
  1446. this.transactedBatchContext.InDispatch = true;
  1447. if (!HandleRequest(request, currentOperationContext))
  1448. {
  1449. return false;
  1450. }
  1451. if (this.transactedBatchContext.InDispatch)
  1452. {
  1453. this.transactedBatchContext.ForceRollback();
  1454. this.transactedBatchContext.InDispatch = false;
  1455. return true;
  1456. }
  1457. if (!TryAcquirePump())
  1458. {
  1459. Fx.Assert("System.ServiceModel.Dispatcher.ChannelHandler.TransactedBatchLoop(): (TryAcquiredPump returned false)");
  1460. return false;
  1461. }
  1462. currentOperationContext.Recycle();
  1463. }
  1464. }
  1465. finally
  1466. {
  1467. OperationContext.Current = existingOperationContext;
  1468. }
  1469. return true;
  1470. }
  1471. Transaction CreateOrGetAttachedTransaction()
  1472. {
  1473. if (null != this.acceptTransaction)
  1474. {
  1475. lock (ThisLock)
  1476. {
  1477. if (null != this.acceptTransaction)
  1478. {
  1479. Transaction tx = this.acceptTransaction.Transaction;
  1480. this.acceptTransaction = null;
  1481. return tx;
  1482. }
  1483. }
  1484. }
  1485. if (null != this.InstanceContext && this.InstanceContext.HasTransaction)
  1486. {
  1487. return InstanceContext.Transaction.Attached;
  1488. }
  1489. else
  1490. {
  1491. return TransactionBehavior.CreateTransaction(
  1492. this.listener.ChannelDispatcher.TransactionIsolationLevel,
  1493. TransactionBehavior.NormalizeTimeout(this.listener.ChannelDispatcher.TransactionTimeout));
  1494. }
  1495. }
  1496. // calls receive on the channel; returns false if no message during the "short timeout"
  1497. bool TryTransactionalReceive(Transaction tx, out RequestContext request)
  1498. {
  1499. request = null;
  1500. bool received = false;
  1501. try
  1502. {
  1503. using (TransactionScope scope = new TransactionScope(tx))
  1504. {
  1505. if (null != this.sharedTransactedBatchContext)
  1506. {
  1507. lock (this.sharedTransactedBatchContext.ReceiveLock)
  1508. {
  1509. if (this.transactedBatchContext.AboutToExpire)
  1510. {
  1511. return false;
  1512. }
  1513. received = this.receiver.TryReceive(TimeSpan.Zero, out request);
  1514. }
  1515. }
  1516. else
  1517. {
  1518. TimeSpan receiveTimeout = TimeoutHelper.Min(this.listener.ChannelDispatcher.TransactionTimeout, this.listener.ChannelDispatcher.DefaultCommunicationTimeouts.ReceiveTimeout);
  1519. received = this.receiver.TryReceive(TransactionBehavior.NormalizeTimeout(receiveTimeout), out request);
  1520. }
  1521. scope.Complete();
  1522. }
  1523. if (received)
  1524. {
  1525. this.HandleReceiveComplete(request);
  1526. }
  1527. }
  1528. catch (ObjectDisposedException ex) // thrown from the transaction
  1529. {
  1530. this.HandleError(ex);
  1531. request = null;
  1532. return false;
  1533. }
  1534. catch (TransactionException ex)
  1535. {
  1536. this.HandleError(ex);
  1537. request = null;
  1538. return false;
  1539. }
  1540. catch (Exception ex)
  1541. {
  1542. if (Fx.IsFatal(ex))
  1543. {
  1544. throw;
  1545. }
  1546. if (!this.HandleError(ex))
  1547. {
  1548. throw;
  1549. }
  1550. }
  1551. return received;
  1552. }
  1553. // This callback always occurs async and always on a dirty thread
  1554. internal void ThrottleAcquiredForCall()
  1555. {
  1556. RequestContext request = this.requestWaitingForThrottle;
  1557. this.requestWaitingForThrottle = null;
  1558. if (this.requestInfo.ChannelHandlerOwnsCallThrottle)
  1559. {
  1560. Fx.Assert("ChannelHandler.ThrottleAcquiredForCall: this.requestInfo.ChannelHandlerOwnsCallThrottle");
  1561. }
  1562. this.requestInfo.ChannelHandlerOwnsCallThrottle = true;
  1563. if (!this.TryRetrievingInstanceContext(request))
  1564. {
  1565. //Should reply/close request and also close the pump
  1566. this.EnsurePump();
  1567. return;
  1568. }
  1569. this.requestInfo.Channel.CompletedIOOperation();
  1570. if (this.TryAcquireThrottle(request, (this.requestInfo.ExistingInstanceContext == null)))
  1571. {
  1572. if (this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle)
  1573. {
  1574. Fx.Assert("ChannelHandler.ThrottleAcquiredForCall: this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle");
  1575. }
  1576. this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle = (this.requestInfo.ExistingInstanceContext == null);
  1577. if (this.DispatchAndReleasePump(request, false, null))
  1578. {
  1579. this.EnsurePump();
  1580. }
  1581. }
  1582. }
  1583. //Return: False denotes failure, Caller should discard the request.
  1584. // : True denotes operation is sucessful.
  1585. bool TryRetrievingInstanceContext(RequestContext request)
  1586. {
  1587. bool releasePump = true;
  1588. try
  1589. {
  1590. if (!this.requestInfo.EndpointLookupDone)
  1591. {
  1592. this.EnsureChannelAndEndpoint(request);
  1593. }
  1594. if (this.requestInfo.Channel == null)
  1595. {
  1596. return false;
  1597. }
  1598. if (this.requestInfo.DispatchRuntime != null)
  1599. {
  1600. IContextChannel transparentProxy = this.requestInfo.Channel.Proxy as IContextChannel;
  1601. try
  1602. {
  1603. this.requestInfo.ExistingInstanceContext = this.requestInfo.DispatchRuntime.InstanceContextProvider.GetExistingInstanceContext(request.RequestMessage, transparentProxy);
  1604. releasePump = false;
  1605. }
  1606. catch (Exception e)
  1607. {
  1608. if (Fx.IsFatal(e))
  1609. {
  1610. throw;
  1611. }
  1612. this.requestInfo.Channel = null;
  1613. this.HandleError(e, request, channel);
  1614. return false;
  1615. }
  1616. }
  1617. else
  1618. {
  1619. // This can happen if we are pumping for an async client,
  1620. // and we receive a bogus reply. In that case, there is no
  1621. // DispatchRuntime, because we are only expecting replies.
  1622. //
  1623. // One possible fix for this would be in DuplexChannelBinder
  1624. // to drop all messages with a RelatesTo that do not match a
  1625. // pending request.
  1626. //
  1627. // However, that would not fix:
  1628. // (a) we could get a valid request message with a
  1629. // RelatesTo that we should try to process.
  1630. // (b) we could get a reply message that does not have
  1631. // a RelatesTo.
  1632. //
  1633. // So we do the null check here.
  1634. //
  1635. // SFx drops a message here
  1636. TraceUtility.TraceDroppedMessage(request.RequestMessage, this.requestInfo.Endpoint);
  1637. request.Close();
  1638. return false;
  1639. }
  1640. }
  1641. catch (Exception e)
  1642. {
  1643. if (Fx.IsFatal(e))
  1644. {
  1645. throw;
  1646. }
  1647. this.HandleError(e, request, channel);
  1648. return false;
  1649. }
  1650. finally
  1651. {
  1652. if (releasePump)
  1653. {
  1654. this.ReleasePump();
  1655. }
  1656. }
  1657. return true;
  1658. }
  1659. // This callback always occurs async and always on a dirty thread
  1660. internal void ThrottleAcquired()
  1661. {
  1662. RequestContext request = this.requestWaitingForThrottle;
  1663. this.requestWaitingForThrottle = null;
  1664. if (this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle)
  1665. {
  1666. Fx.Assert("ChannelHandler.ThrottleAcquired: this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle");
  1667. }
  1668. this.requestInfo.ChannelHandlerOwnsInstanceContextThrottle = (this.requestInfo.ExistingInstanceContext == null);
  1669. if (this.DispatchAndReleasePump(request, false, null))
  1670. {
  1671. this.EnsurePump();
  1672. }
  1673. }
  1674. bool TryAcquireThrottle(RequestContext request, bool acquireInstanceContextThrottle)
  1675. {
  1676. ServiceThrottle throttle = this.throttle;
  1677. if ((throttle != null) && (throttle.IsActive))
  1678. {
  1679. this.requestWaitingForThrottle = request;
  1680. if (throttle.AcquireInstanceContextAndDynamic(this, acquireInstanceContextThrottle))
  1681. {
  1682. this.requestWaitingForThrottle = null;
  1683. return true;
  1684. }
  1685. else
  1686. {
  1687. return false;
  1688. }
  1689. }
  1690. else
  1691. {
  1692. return true;
  1693. }
  1694. }
  1695. bool TryAcquireCallThrottle(RequestContext request)
  1696. {
  1697. ServiceThrottle throttle = this.throttle;
  1698. if ((throttle != null) && (throttle.IsActive))
  1699. {
  1700. this.requestWaitingForThrottle = request;
  1701. if (throttle.AcquireCall(this))
  1702. {
  1703. this.requestWaitingForThrottle = null;
  1704. return true;
  1705. }
  1706. else
  1707. {
  1708. return false;
  1709. }
  1710. }
  1711. else
  1712. {
  1713. return true;
  1714. }
  1715. }
  1716. bool TryAcquirePump()
  1717. {
  1718. if (this.isConcurrent)
  1719. {
  1720. if (this.isPumpAcquired != 0 || Interlocked.CompareExchange(ref this.isPumpAcquired, 1, 0) != 0)
  1721. {
  1722. return false;
  1723. }
  1724. }
  1725. return true;
  1726. }
  1727. struct RequestInfo
  1728. {
  1729. public EndpointDispatcher Endpoint;
  1730. public InstanceContext ExistingInstanceContext;
  1731. public ServiceChannel Channel;
  1732. public bool EndpointLookupDone;
  1733. public DispatchRuntime DispatchRuntime;
  1734. public RequestContext RequestContext;
  1735. public ChannelHandler ChannelHandler;
  1736. public bool ChannelHandlerOwnsCallThrottle; // if true, we are responsible for call throttle
  1737. public bool ChannelHandlerOwnsInstanceContextThrottle; // if true, we are responsible for instance/dynamic throttle
  1738. public RequestInfo(ChannelHandler channelHandler)
  1739. {
  1740. this.Endpoint = null;
  1741. this.ExistingInstanceContext = null;
  1742. this.Channel = null;
  1743. this.EndpointLookupDone = false;
  1744. this.DispatchRuntime = null;
  1745. this.RequestContext = null;
  1746. this.ChannelHandler = channelHandler;
  1747. this.ChannelHandlerOwnsCallThrottle = false;
  1748. this.ChannelHandlerOwnsInstanceContextThrottle = false;
  1749. }
  1750. public void Cleanup()
  1751. {
  1752. if (this.ChannelHandlerOwnsInstanceContextThrottle)
  1753. {
  1754. this.ChannelHandler.throttle.DeactivateInstanceContext();
  1755. this.ChannelHandlerOwnsInstanceContextThrottle = false;
  1756. }
  1757. this.Endpoint = null;
  1758. this.ExistingInstanceContext = null;
  1759. this.Channel = null;
  1760. this.EndpointLookupDone = false;
  1761. this.RequestContext = null;
  1762. if (this.ChannelHandlerOwnsCallThrottle)
  1763. {
  1764. this.ChannelHandler.DispatchDone();
  1765. this.ChannelHandlerOwnsCallThrottle = false;
  1766. }
  1767. }
  1768. }
  1769. EventTraceActivity TraceDispatchMessageStart(Message message)
  1770. {
  1771. if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && message != null)
  1772. {
  1773. EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
  1774. if (TD.DispatchMessageStartIsEnabled())
  1775. {
  1776. TD.DispatchMessageStart(eventTraceActivity);
  1777. }
  1778. return eventTraceActivity;
  1779. }
  1780. return null;
  1781. }
  1782. /// <summary>
  1783. /// Data structure used to carry state for asynchronous replies
  1784. /// </summary>
  1785. struct ContinuationState
  1786. {
  1787. public ChannelHandler ChannelHandler;
  1788. public Exception Exception;
  1789. public RequestContext Request;
  1790. public Message Reply;
  1791. public ServiceChannel Channel;
  1792. public ErrorHandlerFaultInfo FaultInfo;
  1793. }
  1794. }
  1795. }