StreamedFramingRequestChannel.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.Runtime;
  7. using System.Security.Authentication.ExtendedProtection;
  8. using System.ServiceModel;
  9. using System.ServiceModel.Security;
  10. using System.Threading;
  11. class StreamedFramingRequestChannel : RequestChannel
  12. {
  13. IConnectionInitiator connectionInitiator;
  14. ConnectionPool connectionPool;
  15. MessageEncoder messageEncoder;
  16. IConnectionOrientedTransportFactorySettings settings;
  17. byte[] startBytes;
  18. StreamUpgradeProvider upgrade;
  19. ChannelBinding channelBindingToken;
  20. public StreamedFramingRequestChannel(ChannelManagerBase factory, IConnectionOrientedTransportChannelFactorySettings settings,
  21. EndpointAddress remoteAddresss, Uri via, IConnectionInitiator connectionInitiator, ConnectionPool connectionPool)
  22. : base(factory, remoteAddresss, via, settings.ManualAddressing)
  23. {
  24. this.settings = settings;
  25. this.connectionInitiator = connectionInitiator;
  26. this.connectionPool = connectionPool;
  27. this.messageEncoder = settings.MessageEncoderFactory.Encoder;
  28. this.upgrade = settings.Upgrade;
  29. }
  30. byte[] Preamble
  31. {
  32. get { return this.startBytes; }
  33. }
  34. protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
  35. {
  36. return new CompletedAsyncResult(callback, state);
  37. }
  38. protected override void OnEndOpen(IAsyncResult result)
  39. {
  40. CompletedAsyncResult.End(result);
  41. }
  42. protected override void OnOpen(TimeSpan timeout)
  43. {
  44. }
  45. protected override void OnOpened()
  46. {
  47. // setup our preamble which we'll use for all connections we establish
  48. EncodedVia encodedVia = new EncodedVia(this.Via.AbsoluteUri);
  49. EncodedContentType encodedContentType = EncodedContentType.Create(settings.MessageEncoderFactory.Encoder.ContentType);
  50. int startSize = ClientSingletonEncoder.ModeBytes.Length + ClientSingletonEncoder.CalcStartSize(encodedVia, encodedContentType);
  51. int preambleEndOffset = 0;
  52. if (this.upgrade == null)
  53. {
  54. preambleEndOffset = startSize;
  55. startSize += ClientDuplexEncoder.PreambleEndBytes.Length;
  56. }
  57. this.startBytes = DiagnosticUtility.Utility.AllocateByteArray(startSize);
  58. Buffer.BlockCopy(ClientSingletonEncoder.ModeBytes, 0, startBytes, 0, ClientSingletonEncoder.ModeBytes.Length);
  59. ClientSingletonEncoder.EncodeStart(this.startBytes, ClientSingletonEncoder.ModeBytes.Length, encodedVia, encodedContentType);
  60. if (preambleEndOffset > 0)
  61. {
  62. Buffer.BlockCopy(ClientSingletonEncoder.PreambleEndBytes, 0, startBytes, preambleEndOffset, ClientSingletonEncoder.PreambleEndBytes.Length);
  63. }
  64. // and then transition to the Opened state
  65. base.OnOpened();
  66. }
  67. protected override IAsyncRequest CreateAsyncRequest(Message message, AsyncCallback callback, object state)
  68. {
  69. return new StreamedFramingAsyncRequest(this, callback, state);
  70. }
  71. protected override IRequest CreateRequest(Message message)
  72. {
  73. return new StreamedFramingRequest(this);
  74. }
  75. IConnection SendPreamble(IConnection connection, ref TimeoutHelper timeoutHelper,
  76. ClientFramingDecoder decoder, out SecurityMessageProperty remoteSecurity)
  77. {
  78. connection.Write(Preamble, 0, Preamble.Length, true, timeoutHelper.RemainingTime());
  79. if (upgrade != null)
  80. {
  81. IStreamUpgradeChannelBindingProvider channelBindingProvider = upgrade.GetProperty<IStreamUpgradeChannelBindingProvider>();
  82. StreamUpgradeInitiator upgradeInitiator = upgrade.CreateUpgradeInitiator(this.RemoteAddress, this.Via);
  83. if (!ConnectionUpgradeHelper.InitiateUpgrade(upgradeInitiator, ref connection, decoder,
  84. this, ref timeoutHelper))
  85. {
  86. ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, Via, messageEncoder.ContentType, ref timeoutHelper);
  87. }
  88. if (channelBindingProvider != null && channelBindingProvider.IsChannelBindingSupportEnabled)
  89. {
  90. this.channelBindingToken = channelBindingProvider.GetChannelBinding(upgradeInitiator, ChannelBindingKind.Endpoint);
  91. }
  92. remoteSecurity = StreamSecurityUpgradeInitiator.GetRemoteSecurity(upgradeInitiator);
  93. connection.Write(ClientSingletonEncoder.PreambleEndBytes, 0,
  94. ClientSingletonEncoder.PreambleEndBytes.Length, true, timeoutHelper.RemainingTime());
  95. }
  96. else
  97. {
  98. remoteSecurity = null;
  99. }
  100. // read ACK
  101. byte[] ackBuffer = new byte[1];
  102. int ackBytesRead = connection.Read(ackBuffer, 0, ackBuffer.Length, timeoutHelper.RemainingTime());
  103. if (!ConnectionUpgradeHelper.ValidatePreambleResponse(ackBuffer, ackBytesRead, decoder, this.Via))
  104. {
  105. ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, Via, messageEncoder.ContentType, ref timeoutHelper);
  106. }
  107. return connection;
  108. }
  109. protected override void OnClose(TimeSpan timeout)
  110. {
  111. base.WaitForPendingRequests(timeout);
  112. }
  113. protected override void OnClosed()
  114. {
  115. base.OnClosed();
  116. // clean up the CBT after transitioning to the closed state
  117. ChannelBindingUtility.Dispose(ref this.channelBindingToken);
  118. }
  119. protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
  120. {
  121. return base.BeginWaitForPendingRequests(timeout, callback, state);
  122. }
  123. protected override void OnEndClose(IAsyncResult result)
  124. {
  125. base.EndWaitForPendingRequests(result);
  126. }
  127. internal class StreamedConnectionPoolHelper : ConnectionPoolHelper
  128. {
  129. StreamedFramingRequestChannel channel;
  130. ClientSingletonDecoder decoder;
  131. SecurityMessageProperty remoteSecurity;
  132. public StreamedConnectionPoolHelper(StreamedFramingRequestChannel channel)
  133. : base(channel.connectionPool, channel.connectionInitiator, channel.Via)
  134. {
  135. this.channel = channel;
  136. }
  137. public ClientSingletonDecoder Decoder
  138. {
  139. get { return this.decoder; }
  140. }
  141. public SecurityMessageProperty RemoteSecurity
  142. {
  143. get { return this.remoteSecurity; }
  144. }
  145. protected override TimeoutException CreateNewConnectionTimeoutException(TimeSpan timeout, TimeoutException innerException)
  146. {
  147. return new TimeoutException(SR.GetString(SR.RequestTimedOutEstablishingTransportSession,
  148. timeout, channel.Via.AbsoluteUri), innerException);
  149. }
  150. protected override IConnection AcceptPooledConnection(IConnection connection, ref TimeoutHelper timeoutHelper)
  151. {
  152. this.decoder = new ClientSingletonDecoder(0);
  153. return channel.SendPreamble(connection, ref timeoutHelper, this.decoder, out this.remoteSecurity);
  154. }
  155. protected override IAsyncResult BeginAcceptPooledConnection(IConnection connection, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state)
  156. {
  157. this.decoder = new ClientSingletonDecoder(0);
  158. return new SendPreambleAsyncResult(channel, connection, ref timeoutHelper, decoder, callback, state);
  159. }
  160. protected override IConnection EndAcceptPooledConnection(IAsyncResult result)
  161. {
  162. return SendPreambleAsyncResult.End(result, out this.remoteSecurity);
  163. }
  164. class SendPreambleAsyncResult : AsyncResult
  165. {
  166. StreamedFramingRequestChannel channel;
  167. IConnection connection;
  168. ClientFramingDecoder decoder;
  169. StreamUpgradeInitiator upgradeInitiator;
  170. SecurityMessageProperty remoteSecurity;
  171. TimeoutHelper timeoutHelper;
  172. static WaitCallback onWritePreamble = Fx.ThunkCallback(new WaitCallback(OnWritePreamble));
  173. static WaitCallback onWritePreambleEnd;
  174. static WaitCallback onReadPreambleAck = new WaitCallback(OnReadPreambleAck);
  175. static AsyncCallback onUpgrade;
  176. static AsyncCallback onFailedUpgrade;
  177. IStreamUpgradeChannelBindingProvider channelBindingProvider;
  178. public SendPreambleAsyncResult(StreamedFramingRequestChannel channel, IConnection connection,
  179. ref TimeoutHelper timeoutHelper, ClientFramingDecoder decoder, AsyncCallback callback, object state)
  180. : base(callback, state)
  181. {
  182. this.channel = channel;
  183. this.connection = connection;
  184. this.timeoutHelper = timeoutHelper;
  185. this.decoder = decoder;
  186. AsyncCompletionResult writePreambleResult = connection.BeginWrite(channel.Preamble, 0, channel.Preamble.Length,
  187. true, timeoutHelper.RemainingTime(), onWritePreamble, this);
  188. if (writePreambleResult == AsyncCompletionResult.Queued)
  189. {
  190. return;
  191. }
  192. if (HandleWritePreamble())
  193. {
  194. base.Complete(true);
  195. }
  196. }
  197. public static IConnection End(IAsyncResult result, out SecurityMessageProperty remoteSecurity)
  198. {
  199. SendPreambleAsyncResult thisPtr = AsyncResult.End<SendPreambleAsyncResult>(result);
  200. remoteSecurity = thisPtr.remoteSecurity;
  201. return thisPtr.connection;
  202. }
  203. bool HandleWritePreamble()
  204. {
  205. connection.EndWrite();
  206. if (channel.upgrade == null)
  207. {
  208. return ReadPreambleAck();
  209. }
  210. else
  211. {
  212. this.channelBindingProvider = channel.upgrade.GetProperty<IStreamUpgradeChannelBindingProvider>();
  213. this.upgradeInitiator = channel.upgrade.CreateUpgradeInitiator(channel.RemoteAddress, channel.Via);
  214. if (onUpgrade == null)
  215. {
  216. onUpgrade = Fx.ThunkCallback(new AsyncCallback(OnUpgrade));
  217. }
  218. IAsyncResult initiateUpgradeResult = ConnectionUpgradeHelper.BeginInitiateUpgrade(channel.settings, channel.RemoteAddress,
  219. connection, decoder, this.upgradeInitiator, channel.messageEncoder.ContentType, null,
  220. this.timeoutHelper, onUpgrade, this);
  221. if (!initiateUpgradeResult.CompletedSynchronously)
  222. {
  223. return false;
  224. }
  225. return HandleUpgrade(initiateUpgradeResult);
  226. }
  227. }
  228. bool HandleUpgrade(IAsyncResult result)
  229. {
  230. connection = ConnectionUpgradeHelper.EndInitiateUpgrade(result);
  231. if (this.channelBindingProvider != null && this.channelBindingProvider.IsChannelBindingSupportEnabled)
  232. {
  233. this.channel.channelBindingToken = this.channelBindingProvider.GetChannelBinding(this.upgradeInitiator, ChannelBindingKind.Endpoint);
  234. }
  235. this.remoteSecurity = StreamSecurityUpgradeInitiator.GetRemoteSecurity(this.upgradeInitiator);
  236. this.upgradeInitiator = null; // we're done with the initiator
  237. if (onWritePreambleEnd == null)
  238. {
  239. onWritePreambleEnd = Fx.ThunkCallback(new WaitCallback(OnWritePreambleEnd));
  240. }
  241. AsyncCompletionResult writePreambleResult = connection.BeginWrite(
  242. ClientSingletonEncoder.PreambleEndBytes, 0, ClientSingletonEncoder.PreambleEndBytes.Length, true,
  243. timeoutHelper.RemainingTime(), onWritePreambleEnd, this);
  244. if (writePreambleResult == AsyncCompletionResult.Queued)
  245. {
  246. return false;
  247. }
  248. connection.EndWrite();
  249. return ReadPreambleAck();
  250. }
  251. bool ReadPreambleAck()
  252. {
  253. AsyncCompletionResult readAckResult = connection.BeginRead(0, 1,
  254. timeoutHelper.RemainingTime(), onReadPreambleAck, this);
  255. if (readAckResult == AsyncCompletionResult.Queued)
  256. {
  257. return false;
  258. }
  259. return HandlePreambleAck();
  260. }
  261. bool HandlePreambleAck()
  262. {
  263. int ackBytesRead = connection.EndRead();
  264. if (!ConnectionUpgradeHelper.ValidatePreambleResponse(
  265. connection.AsyncReadBuffer, ackBytesRead, decoder, channel.Via))
  266. {
  267. if (onFailedUpgrade == null)
  268. {
  269. onFailedUpgrade = Fx.ThunkCallback(new AsyncCallback(OnFailedUpgrade));
  270. }
  271. IAsyncResult decodeFaultResult = ConnectionUpgradeHelper.BeginDecodeFramingFault(decoder,
  272. connection, channel.Via, channel.messageEncoder.ContentType, ref timeoutHelper,
  273. onFailedUpgrade, this);
  274. if (!decodeFaultResult.CompletedSynchronously)
  275. {
  276. return false;
  277. }
  278. ConnectionUpgradeHelper.EndDecodeFramingFault(decodeFaultResult);
  279. return true;
  280. }
  281. return true;
  282. }
  283. static void OnWritePreamble(object asyncState)
  284. {
  285. SendPreambleAsyncResult thisPtr = (SendPreambleAsyncResult)asyncState;
  286. Exception completionException = null;
  287. bool completeSelf;
  288. try
  289. {
  290. completeSelf = thisPtr.HandleWritePreamble();
  291. }
  292. #pragma warning suppress 56500 // [....], transferring exception to another thread
  293. catch (Exception e)
  294. {
  295. if (Fx.IsFatal(e))
  296. {
  297. throw;
  298. }
  299. completeSelf = true;
  300. completionException = e;
  301. }
  302. if (completeSelf)
  303. {
  304. thisPtr.Complete(false, completionException);
  305. }
  306. }
  307. static void OnWritePreambleEnd(object asyncState)
  308. {
  309. SendPreambleAsyncResult thisPtr = (SendPreambleAsyncResult)asyncState;
  310. Exception completionException = null;
  311. bool completeSelf;
  312. try
  313. {
  314. thisPtr.connection.EndWrite();
  315. completeSelf = thisPtr.ReadPreambleAck();
  316. }
  317. #pragma warning suppress 56500 // [....], transferring exception to another thread
  318. catch (Exception e)
  319. {
  320. if (Fx.IsFatal(e))
  321. {
  322. throw;
  323. }
  324. completeSelf = true;
  325. completionException = e;
  326. }
  327. if (completeSelf)
  328. {
  329. thisPtr.Complete(false, completionException);
  330. }
  331. }
  332. static void OnReadPreambleAck(object state)
  333. {
  334. SendPreambleAsyncResult thisPtr = (SendPreambleAsyncResult)state;
  335. Exception completionException = null;
  336. bool completeSelf;
  337. try
  338. {
  339. completeSelf = thisPtr.HandlePreambleAck();
  340. }
  341. #pragma warning suppress 56500 // [....], transferring exception to another thread
  342. catch (Exception e)
  343. {
  344. if (Fx.IsFatal(e))
  345. {
  346. throw;
  347. }
  348. completeSelf = true;
  349. completionException = e;
  350. }
  351. if (completeSelf)
  352. {
  353. thisPtr.Complete(false, completionException);
  354. }
  355. }
  356. static void OnUpgrade(IAsyncResult result)
  357. {
  358. if (result.CompletedSynchronously)
  359. {
  360. return;
  361. }
  362. SendPreambleAsyncResult thisPtr = (SendPreambleAsyncResult)result.AsyncState;
  363. Exception completionException = null;
  364. bool completeSelf;
  365. try
  366. {
  367. completeSelf = thisPtr.HandleUpgrade(result);
  368. }
  369. #pragma warning suppress 56500 // [....], transferring exception to another thread
  370. catch (Exception e)
  371. {
  372. if (Fx.IsFatal(e))
  373. {
  374. throw;
  375. }
  376. completeSelf = true;
  377. completionException = e;
  378. }
  379. if (completeSelf)
  380. {
  381. thisPtr.Complete(false, completionException);
  382. }
  383. }
  384. static void OnFailedUpgrade(IAsyncResult result)
  385. {
  386. if (result.CompletedSynchronously)
  387. {
  388. return;
  389. }
  390. SendPreambleAsyncResult thisPtr = (SendPreambleAsyncResult)result.AsyncState;
  391. Exception completionException = null;
  392. try
  393. {
  394. ConnectionUpgradeHelper.EndDecodeFramingFault(result);
  395. }
  396. #pragma warning suppress 56500 // [....], transferring exception to another thread
  397. catch (Exception e)
  398. {
  399. if (Fx.IsFatal(e))
  400. {
  401. throw;
  402. }
  403. completionException = e;
  404. }
  405. thisPtr.Complete(false, completionException);
  406. }
  407. }
  408. }
  409. class ClientSingletonConnectionReader : SingletonConnectionReader
  410. {
  411. StreamedConnectionPoolHelper connectionPoolHelper;
  412. public ClientSingletonConnectionReader(IConnection connection, StreamedConnectionPoolHelper connectionPoolHelper,
  413. IConnectionOrientedTransportFactorySettings settings)
  414. : base(connection, 0, 0, connectionPoolHelper.RemoteSecurity, settings, null)
  415. {
  416. this.connectionPoolHelper = connectionPoolHelper;
  417. }
  418. protected override long StreamPosition
  419. {
  420. get { return connectionPoolHelper.Decoder.StreamPosition; }
  421. }
  422. protected override bool DecodeBytes(byte[] buffer, ref int offset, ref int size, ref bool isAtEof)
  423. {
  424. while (size > 0)
  425. {
  426. int bytesRead = connectionPoolHelper.Decoder.Decode(buffer, offset, size);
  427. if (bytesRead > 0)
  428. {
  429. offset += bytesRead;
  430. size -= bytesRead;
  431. }
  432. switch (connectionPoolHelper.Decoder.CurrentState)
  433. {
  434. case ClientFramingDecoderState.EnvelopeStart:
  435. // we're at the envelope
  436. return true;
  437. case ClientFramingDecoderState.End:
  438. isAtEof = true;
  439. return false;
  440. }
  441. }
  442. return false;
  443. }
  444. protected override void OnClose(TimeSpan timeout)
  445. {
  446. connectionPoolHelper.Close(timeout);
  447. }
  448. }
  449. class StreamedFramingRequest : IRequest
  450. {
  451. StreamedFramingRequestChannel channel;
  452. StreamedConnectionPoolHelper connectionPoolHelper;
  453. IConnection connection;
  454. public StreamedFramingRequest(StreamedFramingRequestChannel channel)
  455. {
  456. this.channel = channel;
  457. this.connectionPoolHelper = new StreamedConnectionPoolHelper(channel);
  458. }
  459. public void SendRequest(Message message, TimeSpan timeout)
  460. {
  461. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  462. try
  463. {
  464. this.connection = connectionPoolHelper.EstablishConnection(timeoutHelper.RemainingTime());
  465. ChannelBindingUtility.TryAddToMessage(this.channel.channelBindingToken, message, false);
  466. bool success = false;
  467. try
  468. {
  469. StreamingConnectionHelper.WriteMessage(message, this.connection, true, channel.settings, ref timeoutHelper);
  470. success = true;
  471. }
  472. finally
  473. {
  474. if (!success)
  475. {
  476. connectionPoolHelper.Abort();
  477. }
  478. }
  479. }
  480. catch (TimeoutException exception)
  481. {
  482. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  483. new TimeoutException(SR.GetString(SR.TimeoutOnRequest, timeout), exception));
  484. }
  485. }
  486. public Message WaitForReply(TimeSpan timeout)
  487. {
  488. ClientSingletonConnectionReader connectionReader = new ClientSingletonConnectionReader(
  489. connection, connectionPoolHelper, channel.settings);
  490. connectionReader.DoneSending(TimeSpan.Zero); // we still need to receive
  491. Message message = connectionReader.Receive(timeout);
  492. if (message != null)
  493. {
  494. ChannelBindingUtility.TryAddToMessage(this.channel.channelBindingToken, message, false);
  495. }
  496. return message;
  497. }
  498. void Cleanup()
  499. {
  500. this.connectionPoolHelper.Abort();
  501. }
  502. public void Abort(RequestChannel requestChannel)
  503. {
  504. Cleanup();
  505. }
  506. public void Fault(RequestChannel requestChannel)
  507. {
  508. Cleanup();
  509. }
  510. public void OnReleaseRequest()
  511. {
  512. }
  513. }
  514. class StreamedFramingAsyncRequest : AsyncResult, IAsyncRequest
  515. {
  516. StreamedFramingRequestChannel channel;
  517. IConnection connection;
  518. StreamedConnectionPoolHelper connectionPoolHelper;
  519. Message message;
  520. Message replyMessage;
  521. TimeoutHelper timeoutHelper;
  522. static AsyncCallback onEstablishConnection = Fx.ThunkCallback(new AsyncCallback(OnEstablishConnection));
  523. static AsyncCallback onWriteMessage = Fx.ThunkCallback(new AsyncCallback(OnWriteMessage));
  524. static AsyncCallback onReceiveReply = Fx.ThunkCallback(new AsyncCallback(OnReceiveReply));
  525. ClientSingletonConnectionReader connectionReader;
  526. public StreamedFramingAsyncRequest(StreamedFramingRequestChannel channel, AsyncCallback callback, object state)
  527. : base(callback, state)
  528. {
  529. this.channel = channel;
  530. this.connectionPoolHelper = new StreamedConnectionPoolHelper(channel);
  531. }
  532. public void BeginSendRequest(Message message, TimeSpan timeout)
  533. {
  534. this.timeoutHelper = new TimeoutHelper(timeout);
  535. this.message = message;
  536. bool completeSelf = false;
  537. bool success = false;
  538. try
  539. {
  540. try
  541. {
  542. IAsyncResult result = connectionPoolHelper.BeginEstablishConnection(timeoutHelper.RemainingTime(), onEstablishConnection, this);
  543. if (result.CompletedSynchronously)
  544. {
  545. completeSelf = HandleEstablishConnection(result);
  546. }
  547. }
  548. catch (TimeoutException exception)
  549. {
  550. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  551. new TimeoutException(SR.GetString(SR.TimeoutOnRequest, timeout), exception));
  552. }
  553. success = true;
  554. }
  555. finally
  556. {
  557. if (!success)
  558. {
  559. Cleanup();
  560. }
  561. }
  562. if (completeSelf)
  563. {
  564. base.Complete(true);
  565. }
  566. }
  567. bool HandleEstablishConnection(IAsyncResult result)
  568. {
  569. this.connection = connectionPoolHelper.EndEstablishConnection(result);
  570. ChannelBindingUtility.TryAddToMessage(this.channel.channelBindingToken, this.message, false);
  571. IAsyncResult writeResult = StreamingConnectionHelper.BeginWriteMessage(this.message, this.connection, true, this.channel.settings, ref timeoutHelper, onWriteMessage, this);
  572. if (!writeResult.CompletedSynchronously)
  573. {
  574. return false;
  575. }
  576. return HandleWriteMessage(writeResult);
  577. }
  578. public Message End()
  579. {
  580. try
  581. {
  582. AsyncResult.End<StreamedFramingAsyncRequest>(this);
  583. }
  584. catch (TimeoutException exception)
  585. {
  586. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  587. new TimeoutException(SR.GetString(SR.TimeoutOnRequest, this.timeoutHelper.OriginalTimeout), exception));
  588. }
  589. return replyMessage;
  590. }
  591. public void Abort(RequestChannel requestChannel)
  592. {
  593. Cleanup();
  594. }
  595. public void Fault(RequestChannel requestChannel)
  596. {
  597. Cleanup();
  598. }
  599. void Cleanup()
  600. {
  601. connectionPoolHelper.Abort();
  602. }
  603. bool HandleWriteMessage(IAsyncResult result)
  604. {
  605. // write out the streamed message
  606. StreamingConnectionHelper.EndWriteMessage(result);
  607. connectionReader = new ClientSingletonConnectionReader(connection, connectionPoolHelper, channel.settings);
  608. connectionReader.DoneSending(TimeSpan.Zero); // we still need to receive
  609. IAsyncResult receiveResult = connectionReader.BeginReceive(timeoutHelper.RemainingTime(), onReceiveReply, this);
  610. if (!receiveResult.CompletedSynchronously)
  611. {
  612. return false;
  613. }
  614. return CompleteReceiveReply(receiveResult);
  615. }
  616. bool CompleteReceiveReply(IAsyncResult result)
  617. {
  618. this.replyMessage = connectionReader.EndReceive(result);
  619. if (this.replyMessage != null)
  620. {
  621. ChannelBindingUtility.TryAddToMessage(this.channel.channelBindingToken, this.replyMessage, false);
  622. }
  623. return true;
  624. }
  625. static void OnEstablishConnection(IAsyncResult result)
  626. {
  627. if (result.CompletedSynchronously)
  628. {
  629. return;
  630. }
  631. StreamedFramingAsyncRequest thisPtr = (StreamedFramingAsyncRequest)result.AsyncState;
  632. Exception completionException = null;
  633. bool completeSelf;
  634. bool throwing = true;
  635. try
  636. {
  637. completeSelf = thisPtr.HandleEstablishConnection(result);
  638. throwing = false;
  639. }
  640. #pragma warning suppress 56500 // [....], transferring exception to another thread
  641. catch (Exception e)
  642. {
  643. if (Fx.IsFatal(e))
  644. {
  645. throw;
  646. }
  647. completeSelf = true;
  648. completionException = e;
  649. }
  650. finally
  651. {
  652. if (throwing)
  653. {
  654. thisPtr.Cleanup();
  655. }
  656. }
  657. if (completeSelf)
  658. {
  659. thisPtr.Complete(false, completionException);
  660. }
  661. }
  662. static void OnWriteMessage(IAsyncResult result)
  663. {
  664. if (result.CompletedSynchronously)
  665. {
  666. return;
  667. }
  668. StreamedFramingAsyncRequest thisPtr = (StreamedFramingAsyncRequest)result.AsyncState;
  669. Exception completionException = null;
  670. bool completeSelf;
  671. bool throwing = true;
  672. try
  673. {
  674. completeSelf = thisPtr.HandleWriteMessage(result);
  675. throwing = false;
  676. }
  677. #pragma warning suppress 56500 // [....], transferring exception to another thread
  678. catch (Exception e)
  679. {
  680. if (Fx.IsFatal(e))
  681. {
  682. throw;
  683. }
  684. completeSelf = true;
  685. completionException = e;
  686. }
  687. finally
  688. {
  689. if (throwing)
  690. {
  691. thisPtr.Cleanup();
  692. }
  693. }
  694. if (completeSelf)
  695. {
  696. thisPtr.Complete(false, completionException);
  697. }
  698. }
  699. static void OnReceiveReply(IAsyncResult result)
  700. {
  701. StreamedFramingAsyncRequest thisPtr = (StreamedFramingAsyncRequest)result.AsyncState;
  702. Exception completionException = null;
  703. bool completeSelf;
  704. bool throwing = true;
  705. try
  706. {
  707. completeSelf = thisPtr.CompleteReceiveReply(result);
  708. throwing = false;
  709. }
  710. #pragma warning suppress 56500 // [....], transferring exception to another thread
  711. catch (Exception e)
  712. {
  713. if (Fx.IsFatal(e))
  714. {
  715. throw;
  716. }
  717. completeSelf = true;
  718. completionException = e;
  719. }
  720. finally
  721. {
  722. if (throwing)
  723. {
  724. thisPtr.Cleanup();
  725. }
  726. }
  727. if (completeSelf)
  728. {
  729. thisPtr.Complete(false, completionException);
  730. }
  731. }
  732. public void OnReleaseRequest()
  733. {
  734. }
  735. }
  736. }
  737. }