HttpRequestContext.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. //----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //----------------------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Net.WebSockets;
  12. using System.Runtime;
  13. using System.Runtime.Diagnostics;
  14. using System.Security.Authentication.ExtendedProtection;
  15. using System.ServiceModel;
  16. using System.ServiceModel.Diagnostics;
  17. using System.ServiceModel.Diagnostics.Application;
  18. using System.ServiceModel.Security;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. using System.Xml;
  22. abstract class HttpRequestContext : RequestContextBase
  23. {
  24. HttpOutput httpOutput;
  25. bool errorGettingHttpInput;
  26. HttpChannelListener listener;
  27. SecurityMessageProperty securityProperty;
  28. EventTraceActivity eventTraceActivity;
  29. HttpPipeline httpPipeline;
  30. ServerWebSocketTransportDuplexSessionChannel webSocketChannel;
  31. protected HttpRequestContext(HttpChannelListener listener, Message requestMessage, EventTraceActivity eventTraceActivity)
  32. : base(requestMessage, listener.InternalCloseTimeout, listener.InternalSendTimeout)
  33. {
  34. this.listener = listener;
  35. this.eventTraceActivity = eventTraceActivity;
  36. }
  37. public bool KeepAliveEnabled
  38. {
  39. get
  40. {
  41. return listener.KeepAliveEnabled;
  42. }
  43. }
  44. public bool HttpMessagesSupported
  45. {
  46. get { return this.listener.HttpMessageSettings.HttpMessagesSupported; }
  47. }
  48. public abstract string HttpMethod { get; }
  49. public abstract bool IsWebSocketRequest { get; }
  50. internal ServerWebSocketTransportDuplexSessionChannel WebSocketChannel
  51. {
  52. get
  53. {
  54. return this.webSocketChannel;
  55. }
  56. set
  57. {
  58. Fx.Assert(this.webSocketChannel == null, "webSocketChannel should not be set twice.");
  59. this.webSocketChannel = value;
  60. }
  61. }
  62. internal HttpChannelListener Listener
  63. {
  64. get { return this.listener; }
  65. }
  66. internal EventTraceActivity EventTraceActivity
  67. {
  68. get
  69. {
  70. return this.eventTraceActivity;
  71. }
  72. }
  73. // Note: This method will return null in the case where throwOnError is false, and a non-fatal error occurs.
  74. // Please exercice caution when passing in throwOnError = false. This should basically only be done in error
  75. // code paths, or code paths where there is very good reason that you would not want this method to throw.
  76. // When passing in throwOnError = false, please handle the case where this method returns null.
  77. public HttpInput GetHttpInput(bool throwOnError)
  78. {
  79. HttpPipeline pipeline = this.httpPipeline;
  80. if ((pipeline != null) && pipeline.IsHttpInputInitialized)
  81. {
  82. return pipeline.HttpInput;
  83. }
  84. HttpInput httpInput = null;
  85. if (throwOnError || !this.errorGettingHttpInput)
  86. {
  87. try
  88. {
  89. httpInput = GetHttpInput();
  90. this.errorGettingHttpInput = false;
  91. }
  92. catch (Exception e)
  93. {
  94. this.errorGettingHttpInput = true;
  95. if (throwOnError || Fx.IsFatal(e))
  96. {
  97. throw;
  98. }
  99. DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
  100. }
  101. }
  102. return httpInput;
  103. }
  104. internal static HttpRequestContext CreateContext(HttpChannelListener listener, HttpListenerContext listenerContext, EventTraceActivity eventTraceActivity)
  105. {
  106. return new ListenerHttpContext(listener, listenerContext, eventTraceActivity);
  107. }
  108. protected abstract SecurityMessageProperty OnProcessAuthentication();
  109. public abstract HttpOutput GetHttpOutput(Message message);
  110. protected abstract HttpInput GetHttpInput();
  111. public HttpOutput GetHttpOutputCore(Message message)
  112. {
  113. if (this.httpOutput != null)
  114. {
  115. return this.httpOutput;
  116. }
  117. return this.GetHttpOutput(message);
  118. }
  119. protected override void OnAbort()
  120. {
  121. if (this.httpOutput != null)
  122. {
  123. this.httpOutput.Abort(HttpAbortReason.Aborted);
  124. }
  125. this.Cleanup();
  126. }
  127. protected override void OnClose(TimeSpan timeout)
  128. {
  129. try
  130. {
  131. if (this.httpOutput != null)
  132. {
  133. this.httpOutput.Close();
  134. }
  135. }
  136. finally
  137. {
  138. this.Cleanup();
  139. }
  140. }
  141. protected virtual void Cleanup()
  142. {
  143. if (this.httpPipeline != null)
  144. {
  145. this.httpPipeline.Close();
  146. }
  147. }
  148. public void InitializeHttpPipeline(TransportIntegrationHandler transportIntegrationHandler)
  149. {
  150. this.httpPipeline = HttpPipeline.CreateHttpPipeline(this, transportIntegrationHandler, this.IsWebSocketRequest);
  151. }
  152. internal void SetMessage(Message message, Exception requestException)
  153. {
  154. if ((message == null) && (requestException == null))
  155. {
  156. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  157. new ProtocolException(SR.GetString(SR.MessageXmlProtocolError),
  158. new XmlException(SR.GetString(SR.MessageIsEmpty))));
  159. }
  160. this.TraceHttpMessageReceived(message);
  161. if (requestException != null)
  162. {
  163. base.SetRequestMessage(requestException);
  164. message.Close();
  165. }
  166. else
  167. {
  168. message.Properties.Security = (this.securityProperty != null) ? (SecurityMessageProperty)this.securityProperty.CreateCopy() : null;
  169. base.SetRequestMessage(message);
  170. }
  171. }
  172. void TraceHttpMessageReceived(Message message)
  173. {
  174. if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
  175. {
  176. bool attached = false;
  177. Guid relatedId = this.eventTraceActivity != null ? this.eventTraceActivity.ActivityId : Guid.Empty;
  178. HttpRequestMessageProperty httpProperty;
  179. // Encoder will always add an activity. We need to remove this and read it
  180. // from the web headers for http since correlation might be propogated.
  181. if (message.Headers.MessageId == null &&
  182. message.Properties.TryGetValue<HttpRequestMessageProperty>(HttpRequestMessageProperty.Name, out httpProperty))
  183. {
  184. try
  185. {
  186. string e2eId = httpProperty.Headers[EventTraceActivity.Name];
  187. if (!String.IsNullOrEmpty(e2eId))
  188. {
  189. byte[] data = Convert.FromBase64String(e2eId);
  190. if (data != null && data.Length == 16)
  191. {
  192. Guid id = new Guid(data);
  193. this.eventTraceActivity = new EventTraceActivity(id, true);
  194. message.Properties[EventTraceActivity.Name] = this.eventTraceActivity;
  195. attached = true;
  196. }
  197. }
  198. }
  199. catch (Exception ex)
  200. {
  201. if (Fx.IsFatal(ex))
  202. {
  203. throw;
  204. }
  205. }
  206. }
  207. if (!attached)
  208. {
  209. this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message, true);
  210. }
  211. if (TD.MessageReceivedByTransportIsEnabled())
  212. {
  213. TD.MessageReceivedByTransport(
  214. this.eventTraceActivity,
  215. this.listener != null && this.listener.Uri != null ? this.listener.Uri.AbsoluteUri : string.Empty,
  216. relatedId);
  217. }
  218. }
  219. }
  220. protected abstract HttpStatusCode ValidateAuthentication();
  221. bool PrepareReply(ref Message message)
  222. {
  223. bool closeOnReceivedEof = false;
  224. // null means we're done
  225. if (message == null)
  226. {
  227. // A null message means either a one-way request or that the service operation returned null and
  228. // hence we can close the HttpOutput. By default we keep the HttpOutput open to allow the writing to the output
  229. // even after the HttpInput EOF is received and the HttpOutput will be closed only on close of the HttpRequestContext.
  230. closeOnReceivedEof = true;
  231. message = CreateAckMessage(HttpStatusCode.Accepted, string.Empty);
  232. }
  233. if (!listener.ManualAddressing)
  234. {
  235. if (message.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
  236. {
  237. if (message.Headers.To == null ||
  238. listener.AnonymousUriPrefixMatcher == null ||
  239. !listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To))
  240. {
  241. message.Headers.To = message.Version.Addressing.AnonymousUri;
  242. }
  243. }
  244. else if (message.Version.Addressing == AddressingVersion.WSAddressing10
  245. || message.Version.Addressing == AddressingVersion.None)
  246. {
  247. if (message.Headers.To != null &&
  248. (listener.AnonymousUriPrefixMatcher == null ||
  249. !listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To)))
  250. {
  251. message.Headers.To = null;
  252. }
  253. }
  254. else
  255. {
  256. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  257. new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, message.Version.Addressing)));
  258. }
  259. }
  260. message.Properties.AllowOutputBatching = false;
  261. this.httpOutput = GetHttpOutputCore(message);
  262. // Reuse the HttpInput we got previously.
  263. HttpInput input = this.httpPipeline.HttpInput;
  264. if (input != null)
  265. {
  266. HttpDelayedAcceptStream requestStream = input.GetInputStream(false) as HttpDelayedAcceptStream;
  267. if (requestStream != null && TransferModeHelper.IsRequestStreamed(listener.TransferMode)
  268. && requestStream.EnableDelayedAccept(this.httpOutput, closeOnReceivedEof))
  269. {
  270. return false;
  271. }
  272. }
  273. return true;
  274. }
  275. protected override void OnReply(Message message, TimeSpan timeout)
  276. {
  277. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  278. Message responseMessage = message;
  279. try
  280. {
  281. bool closeOutputAfterReply = PrepareReply(ref responseMessage);
  282. this.httpPipeline.SendReply(responseMessage, timeoutHelper.RemainingTime());
  283. if (closeOutputAfterReply)
  284. {
  285. httpOutput.Close();
  286. }
  287. if (TD.MessageSentByTransportIsEnabled())
  288. {
  289. TD.MessageSentByTransport(eventTraceActivity, this.Listener.Uri.AbsoluteUri);
  290. }
  291. }
  292. finally
  293. {
  294. if (message != null &&
  295. !object.ReferenceEquals(message, responseMessage))
  296. {
  297. responseMessage.Close();
  298. }
  299. }
  300. }
  301. protected override IAsyncResult OnBeginReply(
  302. Message message, TimeSpan timeout, AsyncCallback callback, object state)
  303. {
  304. return new ReplyAsyncResult(this, message, timeout, callback, state);
  305. }
  306. protected override void OnEndReply(IAsyncResult result)
  307. {
  308. ReplyAsyncResult.End(result);
  309. }
  310. public bool ProcessAuthentication()
  311. {
  312. if (TD.HttpContextBeforeProcessAuthenticationIsEnabled())
  313. {
  314. TD.HttpContextBeforeProcessAuthentication(this.eventTraceActivity);
  315. }
  316. HttpStatusCode statusCode = ValidateAuthentication();
  317. if (statusCode == HttpStatusCode.OK)
  318. {
  319. bool authenticationSucceeded = false;
  320. statusCode = HttpStatusCode.Forbidden;
  321. try
  322. {
  323. this.securityProperty = OnProcessAuthentication();
  324. authenticationSucceeded = true;
  325. return true;
  326. }
  327. catch (Exception e)
  328. {
  329. if (Fx.IsFatal(e))
  330. {
  331. throw;
  332. }
  333. if (e.Data.Contains(HttpChannelUtilities.HttpStatusCodeKey))
  334. {
  335. if (e.Data[HttpChannelUtilities.HttpStatusCodeKey] is HttpStatusCode)
  336. {
  337. statusCode = (HttpStatusCode)e.Data[HttpChannelUtilities.HttpStatusCodeKey];
  338. }
  339. }
  340. throw;
  341. }
  342. finally
  343. {
  344. if (!authenticationSucceeded)
  345. {
  346. SendResponseAndClose(statusCode);
  347. }
  348. }
  349. }
  350. else
  351. {
  352. SendResponseAndClose(statusCode);
  353. return false;
  354. }
  355. }
  356. internal void SendResponseAndClose(HttpStatusCode statusCode)
  357. {
  358. SendResponseAndClose(statusCode, string.Empty);
  359. }
  360. internal void SendResponseAndClose(HttpStatusCode statusCode, string statusDescription)
  361. {
  362. if (ReplyInitiated)
  363. {
  364. this.Close();
  365. return;
  366. }
  367. using (Message ackMessage = CreateAckMessage(statusCode, statusDescription))
  368. {
  369. this.Reply(ackMessage);
  370. }
  371. this.Close();
  372. }
  373. internal void SendResponseAndClose(HttpResponseMessage httpResponseMessage)
  374. {
  375. if (this.TryInitiateReply())
  376. {
  377. // Send the response message.
  378. try
  379. {
  380. if (this.httpOutput == null)
  381. {
  382. this.httpOutput = this.GetHttpOutputCore(new NullMessage());
  383. }
  384. this.httpOutput.Send(httpResponseMessage, this.DefaultSendTimeout);
  385. }
  386. catch (Exception ex)
  387. {
  388. if (Fx.IsFatal(ex))
  389. {
  390. throw;
  391. }
  392. DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information);
  393. }
  394. }
  395. // Close the request context.
  396. try
  397. {
  398. this.Close(); // this also closes the HttpOutput
  399. }
  400. catch (Exception ex)
  401. {
  402. if (Fx.IsFatal(ex))
  403. {
  404. throw;
  405. }
  406. DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information);
  407. }
  408. }
  409. Message CreateAckMessage(HttpStatusCode statusCode, string statusDescription)
  410. {
  411. Message ackMessage = new NullMessage();
  412. HttpResponseMessageProperty httpResponseProperty = new HttpResponseMessageProperty();
  413. httpResponseProperty.StatusCode = statusCode;
  414. httpResponseProperty.SuppressEntityBody = true;
  415. if (statusDescription.Length > 0)
  416. {
  417. httpResponseProperty.StatusDescription = statusDescription;
  418. }
  419. ackMessage.Properties.Add(HttpResponseMessageProperty.Name, httpResponseProperty);
  420. return ackMessage;
  421. }
  422. [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability104",
  423. Justification = "The exceptions will be traced and thrown by the handling method.")]
  424. public void AcceptWebSocket(HttpResponseMessage response, string protocol, TimeSpan timeout)
  425. {
  426. Task<WebSocketContext> acceptTask;
  427. bool success = false;
  428. try
  429. {
  430. acceptTask = this.AcceptWebSocketCore(response, protocol);
  431. try
  432. {
  433. if (!acceptTask.Wait(TimeoutHelper.ToMilliseconds(timeout)))
  434. {
  435. throw FxTrace.Exception.AsError(new TimeoutException(SR.GetString(SR.AcceptWebSocketTimedOutError)));
  436. }
  437. }
  438. catch (Exception ex)
  439. {
  440. if (Fx.IsFatal(ex))
  441. {
  442. throw;
  443. }
  444. WebSocketHelper.ThrowCorrectException(ex);
  445. }
  446. success = true;
  447. }
  448. finally
  449. {
  450. if (!success)
  451. {
  452. this.OnAcceptWebSocketError();
  453. }
  454. }
  455. this.SetReplySent();
  456. this.OnAcceptWebSocketSuccess(acceptTask.Result, response.RequestMessage);
  457. }
  458. protected abstract Task<WebSocketContext> AcceptWebSocketCore(HttpResponseMessage response, string protocol);
  459. protected virtual void OnAcceptWebSocketError()
  460. {
  461. }
  462. protected abstract void OnAcceptWebSocketSuccess(WebSocketContext context, HttpRequestMessage requestMessage);
  463. protected void OnAcceptWebSocketSuccess(
  464. WebSocketContext context,
  465. RemoteEndpointMessageProperty remoteEndpointMessageProperty,
  466. byte[] webSocketInternalBuffer,
  467. bool shouldDisposeWebSocketAfterClose,
  468. HttpRequestMessage requestMessage)
  469. {
  470. this.webSocketChannel.SetWebSocketInfo(
  471. context,
  472. remoteEndpointMessageProperty,
  473. this.securityProperty,
  474. webSocketInternalBuffer,
  475. shouldDisposeWebSocketAfterClose,
  476. requestMessage);
  477. }
  478. public IAsyncResult BeginAcceptWebSocket(HttpResponseMessage response, string protocol, AsyncCallback callback, object state)
  479. {
  480. return new AcceptWebSocketAsyncResult(this, response, protocol, callback, state);
  481. }
  482. public void EndAcceptWebSocket(IAsyncResult result)
  483. {
  484. AcceptWebSocketAsyncResult.End(result);
  485. }
  486. class ReplyAsyncResult : AsyncResult
  487. {
  488. static AsyncCallback onSendCompleted;
  489. static Action<object, HttpResponseMessage> onHttpPipelineSend;
  490. bool closeOutputAfterReply;
  491. HttpRequestContext context;
  492. Message message;
  493. Message responseMessage;
  494. TimeoutHelper timeoutHelper;
  495. public ReplyAsyncResult(HttpRequestContext context, Message message, TimeSpan timeout, AsyncCallback callback, object state)
  496. : base(callback, state)
  497. {
  498. this.context = context;
  499. this.message = message;
  500. this.responseMessage = null;
  501. this.timeoutHelper = new TimeoutHelper(timeout);
  502. ThreadTrace.Trace("Begin sending http reply");
  503. this.responseMessage = this.message;
  504. if (this.SendResponse())
  505. {
  506. base.Complete(true);
  507. }
  508. }
  509. public static void End(IAsyncResult result)
  510. {
  511. AsyncResult.End<ReplyAsyncResult>(result);
  512. }
  513. void OnSendResponseCompleted(IAsyncResult result)
  514. {
  515. try
  516. {
  517. context.httpOutput.EndSend(result);
  518. ThreadTrace.Trace("End sending http reply");
  519. if (this.closeOutputAfterReply)
  520. {
  521. context.httpOutput.Close();
  522. }
  523. }
  524. finally
  525. {
  526. if (this.message != null &&
  527. !object.ReferenceEquals(this.message, this.responseMessage))
  528. {
  529. this.responseMessage.Close();
  530. }
  531. }
  532. }
  533. static void OnSendResponseCompletedCallback(IAsyncResult result)
  534. {
  535. if (result.CompletedSynchronously)
  536. {
  537. return;
  538. }
  539. ReplyAsyncResult thisPtr = (ReplyAsyncResult)result.AsyncState;
  540. Exception completionException = null;
  541. try
  542. {
  543. thisPtr.OnSendResponseCompleted(result);
  544. }
  545. catch (Exception e)
  546. {
  547. if (Fx.IsFatal(e))
  548. {
  549. throw;
  550. }
  551. completionException = e;
  552. }
  553. thisPtr.Complete(false, completionException);
  554. }
  555. static void OnHttpPipelineSendCallback(object target, HttpResponseMessage httpResponseMessage)
  556. {
  557. ReplyAsyncResult thisPtr = (ReplyAsyncResult)target;
  558. Exception pendingException = null;
  559. bool completed = false;
  560. try
  561. {
  562. completed = thisPtr.SendResponse(httpResponseMessage);
  563. }
  564. catch (Exception e)
  565. {
  566. if (Fx.IsFatal(e))
  567. {
  568. throw;
  569. }
  570. pendingException = e;
  571. completed = true;
  572. }
  573. if (completed)
  574. {
  575. thisPtr.Complete(false, pendingException);
  576. }
  577. }
  578. public bool SendResponse(HttpResponseMessage httpResponseMessage)
  579. {
  580. if (onSendCompleted == null)
  581. {
  582. onSendCompleted = Fx.ThunkCallback(new AsyncCallback(OnSendResponseCompletedCallback));
  583. }
  584. bool success = false;
  585. try
  586. {
  587. return this.SendResponseCore(httpResponseMessage, out success);
  588. }
  589. finally
  590. {
  591. if (!success && this.message != null &&
  592. !object.ReferenceEquals(this.message, this.responseMessage))
  593. {
  594. this.responseMessage.Close();
  595. }
  596. }
  597. }
  598. public bool SendResponse()
  599. {
  600. if (onSendCompleted == null)
  601. {
  602. onSendCompleted = Fx.ThunkCallback(new AsyncCallback(OnSendResponseCompletedCallback));
  603. }
  604. bool success = false;
  605. try
  606. {
  607. this.closeOutputAfterReply = context.PrepareReply(ref this.responseMessage);
  608. if (onHttpPipelineSend == null)
  609. {
  610. onHttpPipelineSend = new Action<object, HttpResponseMessage>(OnHttpPipelineSendCallback);
  611. }
  612. if (context.httpPipeline.SendAsyncReply(this.responseMessage, onHttpPipelineSend, this) == AsyncCompletionResult.Queued)
  613. {
  614. //// In Async send + HTTP pipeline path, we will send the response back after the result coming out from the pipeline.
  615. //// So we don't need to call it here.
  616. success = true;
  617. return false;
  618. }
  619. HttpResponseMessage httpResponseMessage = null;
  620. if (this.context.HttpMessagesSupported)
  621. {
  622. httpResponseMessage = HttpResponseMessageProperty.GetHttpResponseMessageFromMessage(this.responseMessage);
  623. }
  624. return this.SendResponseCore(httpResponseMessage, out success);
  625. }
  626. finally
  627. {
  628. if (!success && this.message != null &&
  629. !object.ReferenceEquals(this.message, this.responseMessage))
  630. {
  631. this.responseMessage.Close();
  632. }
  633. }
  634. }
  635. bool SendResponseCore(HttpResponseMessage httpResponseMessage, out bool success)
  636. {
  637. success = false;
  638. IAsyncResult result;
  639. if (httpResponseMessage == null)
  640. {
  641. result = context.httpOutput.BeginSend(this.timeoutHelper.RemainingTime(), onSendCompleted, this);
  642. }
  643. else
  644. {
  645. result = context.httpOutput.BeginSend(httpResponseMessage, this.timeoutHelper.RemainingTime(), onSendCompleted, this);
  646. }
  647. success = true;
  648. if (!result.CompletedSynchronously)
  649. {
  650. return false;
  651. }
  652. this.OnSendResponseCompleted(result);
  653. return true;
  654. }
  655. }
  656. internal IAsyncResult BeginProcessInboundRequest(
  657. ReplyChannelAcceptor replyChannelAcceptor,
  658. Action acceptorCallback,
  659. AsyncCallback callback,
  660. object state)
  661. {
  662. return this.httpPipeline.BeginProcessInboundRequest(replyChannelAcceptor, acceptorCallback, callback, state);
  663. }
  664. internal void EndProcessInboundRequest(IAsyncResult result)
  665. {
  666. this.httpPipeline.EndProcessInboundRequest(result);
  667. }
  668. class ListenerHttpContext : HttpRequestContext, HttpRequestMessageProperty.IHttpHeaderProvider
  669. {
  670. HttpListenerContext listenerContext;
  671. byte[] webSocketInternalBuffer;
  672. public ListenerHttpContext(HttpChannelListener listener,
  673. HttpListenerContext listenerContext, EventTraceActivity eventTraceActivity)
  674. : base(listener, null, eventTraceActivity)
  675. {
  676. this.listenerContext = listenerContext;
  677. }
  678. public override string HttpMethod
  679. {
  680. get { return listenerContext.Request.HttpMethod; }
  681. }
  682. public override bool IsWebSocketRequest
  683. {
  684. get { return this.listenerContext.Request.IsWebSocketRequest; }
  685. }
  686. protected override HttpInput GetHttpInput()
  687. {
  688. return new ListenerContextHttpInput(this);
  689. }
  690. protected override Task<WebSocketContext> AcceptWebSocketCore(HttpResponseMessage response, string protocol)
  691. {
  692. // CopyHeaders would still throw when the response contains a "WWW-Authenticate"-header
  693. // But this is ok in this case because the "WWW-Authenticate"-header doesn't make sense
  694. // for a response returning 101 (Switching Protocol)
  695. HttpChannelUtilities.CopyHeaders(response, this.listenerContext.Response.Headers.Add);
  696. this.webSocketInternalBuffer = this.Listener.TakeWebSocketInternalBuffer();
  697. return this.listenerContext.AcceptWebSocketAsync(
  698. protocol,
  699. WebSocketHelper.GetReceiveBufferSize(this.listener.MaxReceivedMessageSize),
  700. this.Listener.WebSocketSettings.GetEffectiveKeepAliveInterval(),
  701. new ArraySegment<byte>(this.webSocketInternalBuffer)).Upcast<HttpListenerWebSocketContext, WebSocketContext>();
  702. }
  703. protected override void OnAcceptWebSocketError()
  704. {
  705. byte[] buffer = Interlocked.CompareExchange<byte[]>(ref this.webSocketInternalBuffer, null, this.webSocketInternalBuffer);
  706. if (buffer != null)
  707. {
  708. this.Listener.ReturnWebSocketInternalBuffer(buffer);
  709. }
  710. }
  711. protected override void OnAcceptWebSocketSuccess(WebSocketContext context, HttpRequestMessage requestMessage)
  712. {
  713. RemoteEndpointMessageProperty remoteEndpointMessageProperty = null;
  714. if (this.listenerContext.Request.RemoteEndPoint != null)
  715. {
  716. remoteEndpointMessageProperty = new RemoteEndpointMessageProperty(this.listenerContext.Request.RemoteEndPoint);
  717. }
  718. base.OnAcceptWebSocketSuccess(context, remoteEndpointMessageProperty, this.webSocketInternalBuffer, true, requestMessage);
  719. }
  720. public override HttpOutput GetHttpOutput(Message message)
  721. {
  722. // work around http.sys keep alive bug with chunked requests, see MB 49676, this is fixed in Vista
  723. if (listenerContext.Request.ContentLength64 == -1 && !OSEnvironmentHelper.IsVistaOrGreater)
  724. {
  725. listenerContext.Response.KeepAlive = false;
  726. }
  727. else
  728. {
  729. listenerContext.Response.KeepAlive = listener.KeepAliveEnabled;
  730. }
  731. ICompressedMessageEncoder compressedMessageEncoder = listener.MessageEncoderFactory.Encoder as ICompressedMessageEncoder;
  732. if (compressedMessageEncoder != null && compressedMessageEncoder.CompressionEnabled)
  733. {
  734. string acceptEncoding = listenerContext.Request.Headers[HttpChannelUtilities.AcceptEncodingHeader];
  735. compressedMessageEncoder.AddCompressedMessageProperties(message, acceptEncoding);
  736. }
  737. return HttpOutput.CreateHttpOutput(listenerContext.Response, Listener, message, this.HttpMethod);
  738. }
  739. protected override SecurityMessageProperty OnProcessAuthentication()
  740. {
  741. return Listener.ProcessAuthentication(listenerContext);
  742. }
  743. protected override HttpStatusCode ValidateAuthentication()
  744. {
  745. return Listener.ValidateAuthentication(listenerContext);
  746. }
  747. protected override void OnAbort()
  748. {
  749. listenerContext.Response.Abort();
  750. // CSDMain 259910, we should remove this and call base.OnAbort() instead to improve maintainability
  751. this.Cleanup();
  752. }
  753. protected override void OnClose(TimeSpan timeout)
  754. {
  755. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  756. base.OnClose(timeoutHelper.RemainingTime());
  757. try
  758. {
  759. listenerContext.Response.Close();
  760. }
  761. catch (HttpListenerException listenerException)
  762. {
  763. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  764. HttpChannelUtilities.CreateCommunicationException(listenerException));
  765. }
  766. }
  767. void HttpRequestMessageProperty.IHttpHeaderProvider.CopyHeaders(WebHeaderCollection headers)
  768. {
  769. HttpListenerRequest listenerRequest = this.listenerContext.Request;
  770. headers.Add(listenerRequest.Headers);
  771. // MB 57988 - System.Net strips off user-agent from the headers collection
  772. if (listenerRequest.UserAgent != null && headers[HttpRequestHeader.UserAgent] == null)
  773. {
  774. headers.Add(HttpRequestHeader.UserAgent, listenerRequest.UserAgent);
  775. }
  776. }
  777. class ListenerContextHttpInput : HttpInput
  778. {
  779. ListenerHttpContext listenerHttpContext;
  780. string cachedContentType; // accessing the header in System.Net involves a native transition
  781. byte[] preReadBuffer;
  782. public ListenerContextHttpInput(ListenerHttpContext listenerHttpContext)
  783. : base(listenerHttpContext.Listener, true, listenerHttpContext.listener.IsChannelBindingSupportEnabled)
  784. {
  785. this.listenerHttpContext = listenerHttpContext;
  786. if (this.listenerHttpContext.listenerContext.Request.ContentLength64 == -1)
  787. {
  788. this.preReadBuffer = new byte[1];
  789. if (this.listenerHttpContext.listenerContext.Request.InputStream.Read(preReadBuffer, 0, 1) == 0)
  790. {
  791. this.preReadBuffer = null;
  792. }
  793. }
  794. }
  795. public override long ContentLength
  796. {
  797. get
  798. {
  799. return this.listenerHttpContext.listenerContext.Request.ContentLength64;
  800. }
  801. }
  802. protected override string ContentTypeCore
  803. {
  804. get
  805. {
  806. if (this.cachedContentType == null)
  807. {
  808. this.cachedContentType = this.listenerHttpContext.listenerContext.Request.ContentType;
  809. }
  810. return this.cachedContentType;
  811. }
  812. }
  813. protected override bool HasContent
  814. {
  815. get { return (this.preReadBuffer != null || this.ContentLength > 0); }
  816. }
  817. protected override string SoapActionHeader
  818. {
  819. get
  820. {
  821. return this.listenerHttpContext.listenerContext.Request.Headers["SOAPAction"];
  822. }
  823. }
  824. protected override ChannelBinding ChannelBinding
  825. {
  826. get
  827. {
  828. return ChannelBindingUtility.GetToken(this.listenerHttpContext.listenerContext.Request.TransportContext);
  829. }
  830. }
  831. protected override void AddProperties(Message message)
  832. {
  833. HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty(this.listenerHttpContext);
  834. requestProperty.Method = this.listenerHttpContext.listenerContext.Request.HttpMethod;
  835. // Uri.Query always includes the '?'
  836. if (this.listenerHttpContext.listenerContext.Request.Url.Query.Length > 1)
  837. {
  838. requestProperty.QueryString = this.listenerHttpContext.listenerContext.Request.Url.Query.Substring(1);
  839. }
  840. message.Properties.Add(HttpRequestMessageProperty.Name, requestProperty);
  841. message.Properties.Via = this.listenerHttpContext.listenerContext.Request.Url;
  842. RemoteEndpointMessageProperty remoteEndpointProperty = new RemoteEndpointMessageProperty(this.listenerHttpContext.listenerContext.Request.RemoteEndPoint);
  843. message.Properties.Add(RemoteEndpointMessageProperty.Name, remoteEndpointProperty);
  844. }
  845. public override void ConfigureHttpRequestMessage(HttpRequestMessage message)
  846. {
  847. message.Method = new HttpMethod(this.listenerHttpContext.listenerContext.Request.HttpMethod);
  848. message.RequestUri = this.listenerHttpContext.listenerContext.Request.Url;
  849. foreach (string webHeaderKey in this.listenerHttpContext.listenerContext.Request.Headers.Keys)
  850. {
  851. message.AddHeader(webHeaderKey, this.listenerHttpContext.listenerContext.Request.Headers[webHeaderKey]);
  852. }
  853. message.Properties.Add(RemoteEndpointMessageProperty.Name, new RemoteEndpointMessageProperty(this.listenerHttpContext.listenerContext.Request.RemoteEndPoint));
  854. }
  855. protected override Stream GetInputStream()
  856. {
  857. if (this.preReadBuffer != null)
  858. {
  859. return new ListenerContextInputStream(listenerHttpContext, preReadBuffer);
  860. }
  861. else
  862. {
  863. return new ListenerContextInputStream(listenerHttpContext);
  864. }
  865. }
  866. class ListenerContextInputStream : HttpDelayedAcceptStream
  867. {
  868. public ListenerContextInputStream(ListenerHttpContext listenerHttpContext)
  869. : base(listenerHttpContext.listenerContext.Request.InputStream)
  870. {
  871. }
  872. public ListenerContextInputStream(ListenerHttpContext listenerHttpContext, byte[] preReadBuffer)
  873. : base(new PreReadStream(listenerHttpContext.listenerContext.Request.InputStream, preReadBuffer))
  874. {
  875. }
  876. public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  877. {
  878. try
  879. {
  880. return base.BeginRead(buffer, offset, count, callback, state);
  881. }
  882. catch (HttpListenerException listenerException)
  883. {
  884. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  885. HttpChannelUtilities.CreateCommunicationException(listenerException));
  886. }
  887. }
  888. public override int EndRead(IAsyncResult result)
  889. {
  890. try
  891. {
  892. return base.EndRead(result);
  893. }
  894. catch (HttpListenerException listenerException)
  895. {
  896. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  897. HttpChannelUtilities.CreateCommunicationException(listenerException));
  898. }
  899. }
  900. public override int Read(byte[] buffer, int offset, int count)
  901. {
  902. try
  903. {
  904. return base.Read(buffer, offset, count);
  905. }
  906. catch (HttpListenerException listenerException)
  907. {
  908. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  909. HttpChannelUtilities.CreateCommunicationException(listenerException));
  910. }
  911. }
  912. public override int ReadByte()
  913. {
  914. try
  915. {
  916. return base.ReadByte();
  917. }
  918. catch (HttpListenerException listenerException)
  919. {
  920. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  921. HttpChannelUtilities.CreateCommunicationException(listenerException));
  922. }
  923. }
  924. }
  925. }
  926. }
  927. class AcceptWebSocketAsyncResult : AsyncResult
  928. {
  929. static AsyncCallback onHandleAcceptWebSocketResult = Fx.ThunkCallback(new AsyncCallback(HandleAcceptWebSocketResult));
  930. HttpRequestContext context;
  931. SignalGate gate = new SignalGate();
  932. HttpResponseMessage response;
  933. public AcceptWebSocketAsyncResult(HttpRequestContext context, HttpResponseMessage response, string protocol, AsyncCallback callback, object state)
  934. : base(callback, state)
  935. {
  936. Fx.Assert(context != null, "context should not be null.");
  937. Fx.Assert(response != null, "response should not be null.");
  938. this.context = context;
  939. this.response = response;
  940. IAsyncResult result = this.context.AcceptWebSocketCore(response, protocol).AsAsyncResult<WebSocketContext>(onHandleAcceptWebSocketResult, this);
  941. if (this.gate.Unlock())
  942. {
  943. this.CompleteAcceptWebSocket(result);
  944. base.Complete(true);
  945. }
  946. }
  947. public static void End(IAsyncResult result)
  948. {
  949. AsyncResult.End<AcceptWebSocketAsyncResult>(result);
  950. }
  951. static void HandleAcceptWebSocketResult(IAsyncResult result)
  952. {
  953. AcceptWebSocketAsyncResult thisPtr = (AcceptWebSocketAsyncResult)result.AsyncState;
  954. if (!thisPtr.gate.Signal())
  955. {
  956. return;
  957. }
  958. Exception pendingException = null;
  959. try
  960. {
  961. thisPtr.CompleteAcceptWebSocket(result);
  962. }
  963. catch (Exception ex)
  964. {
  965. if (Fx.IsFatal(ex))
  966. {
  967. throw;
  968. }
  969. pendingException = ex;
  970. }
  971. thisPtr.Complete(false, pendingException);
  972. }
  973. void CompleteAcceptWebSocket(IAsyncResult result)
  974. {
  975. Task<WebSocketContext> acceptTask = result as Task<WebSocketContext>;
  976. Fx.Assert(acceptTask != null, "acceptTask should not be null.");
  977. if (acceptTask.IsFaulted)
  978. {
  979. this.context.OnAcceptWebSocketError();
  980. throw FxTrace.Exception.AsError<WebSocketException>(acceptTask.Exception);
  981. }
  982. else if (acceptTask.IsCanceled)
  983. {
  984. this.context.OnAcceptWebSocketError();
  985. //
  986. throw FxTrace.Exception.AsError(new TimeoutException(SR.GetString(SR.AcceptWebSocketTimedOutError)));
  987. }
  988. this.context.SetReplySent();
  989. this.context.OnAcceptWebSocketSuccess(acceptTask.Result, response.RequestMessage);
  990. }
  991. }
  992. }
  993. }