HttpReplyChannel.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. //
  2. // HttpReplyChannel.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2006 Novell, Inc. http://www.novell.com
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Collections.Specialized;
  31. using System.IO;
  32. using System.Net;
  33. using System.ServiceModel;
  34. using System.Text;
  35. using System.Threading;
  36. namespace System.ServiceModel.Channels
  37. {
  38. internal class HttpSimpleReplyChannel : HttpReplyChannel
  39. {
  40. HttpSimpleChannelListener<IReplyChannel> source;
  41. List<HttpListenerContext> waiting = new List<HttpListenerContext> ();
  42. RequestContext reqctx;
  43. public HttpSimpleReplyChannel (HttpSimpleChannelListener<IReplyChannel> listener)
  44. : base (listener)
  45. {
  46. this.source = listener;
  47. }
  48. protected override void OnAbort ()
  49. {
  50. AbortConnections (TimeSpan.Zero);
  51. base.OnAbort (); // FIXME: remove it. The base is wrong. But it is somehow required to not block some tests.
  52. }
  53. public override bool CancelAsync (TimeSpan timeout)
  54. {
  55. AbortConnections (timeout);
  56. // FIXME: this wait is sort of hack (because it should not be required), but without it some tests are blocked.
  57. // This hack even had better be moved to base.CancelAsync().
  58. if (CurrentAsyncResult != null)
  59. CurrentAsyncResult.AsyncWaitHandle.WaitOne (TimeSpan.FromMilliseconds (300));
  60. return base.CancelAsync (timeout);
  61. }
  62. void SignalAsyncWait ()
  63. {
  64. if (wait == null)
  65. return;
  66. var wait_ = wait;
  67. wait = null;
  68. wait_.Set ();
  69. }
  70. void AbortConnections (TimeSpan timeout)
  71. {
  72. // FIXME: use timeout
  73. lock (waiting)
  74. foreach (var ctx in waiting)
  75. ctx.Response.Close ();
  76. if (wait != null)
  77. source.ListenerManager.CancelGetHttpContextAsync ();
  78. }
  79. protected override void OnClose (TimeSpan timeout)
  80. {
  81. DateTime start = DateTime.Now;
  82. if (reqctx != null)
  83. reqctx.Close (timeout);
  84. // FIXME: consider timeout
  85. AbortConnections (timeout - (DateTime.Now - start));
  86. base.OnClose (timeout - (DateTime.Now - start));
  87. }
  88. public override bool TryReceiveRequest (TimeSpan timeout, out RequestContext context)
  89. {
  90. context = null;
  91. if (waiting.Count == 0 && !WaitForRequest (timeout))
  92. return false;
  93. HttpListenerContext ctx = null;
  94. lock (waiting) {
  95. if (waiting.Count > 0) {
  96. ctx = waiting [0];
  97. waiting.RemoveAt (0);
  98. }
  99. }
  100. if (ctx == null)
  101. // Though as long as this instance is used
  102. // synchronously, it should not happen.
  103. return false;
  104. if (ctx.Response.StatusCode != 200) {
  105. ctx.Response.Close ();
  106. return false;
  107. }
  108. // FIXME: supply maxSizeOfHeaders.
  109. int maxSizeOfHeaders = 0x10000;
  110. Message msg = null;
  111. if (ctx.Request.HttpMethod == "POST") {
  112. if (!Encoder.IsContentTypeSupported (ctx.Request.ContentType)) {
  113. ctx.Response.StatusCode = (int) HttpStatusCode.UnsupportedMediaType;
  114. ctx.Response.StatusDescription = String.Format (
  115. "Expected content-type '{0}' but got '{1}'", Encoder.ContentType, ctx.Request.ContentType);
  116. ctx.Response.Close ();
  117. return false;
  118. }
  119. msg = Encoder.ReadMessage (
  120. ctx.Request.InputStream, maxSizeOfHeaders);
  121. if (MessageVersion.Envelope.Equals (EnvelopeVersion.Soap11) ||
  122. MessageVersion.Addressing.Equals (AddressingVersion.None)) {
  123. string action = GetHeaderItem (ctx.Request.Headers ["SOAPAction"]);
  124. if (action != null) {
  125. if (action.Length > 2 && action [0] == '"' && action [action.Length] == '"')
  126. action = action.Substring (1, action.Length - 2);
  127. msg.Headers.Action = action;
  128. }
  129. }
  130. } else if (ctx.Request.HttpMethod == "GET") {
  131. msg = Message.CreateMessage (MessageVersion.None, null);
  132. }
  133. if (msg.Headers.To == null)
  134. msg.Headers.To = ctx.Request.Url;
  135. msg.Properties.Add ("Via", LocalAddress.Uri);
  136. msg.Properties.Add (HttpRequestMessageProperty.Name, CreateRequestProperty (ctx.Request.HttpMethod, ctx.Request.Url.Query, ctx.Request.Headers));
  137. /*
  138. MessageBuffer buf = msg.CreateBufferedCopy (0x10000);
  139. msg = buf.CreateMessage ();
  140. Console.WriteLine (buf.CreateMessage ());
  141. */
  142. context = new HttpRequestContext (this, msg, ctx);
  143. reqctx = context;
  144. return true;
  145. }
  146. ManualResetEvent wait;
  147. public override bool WaitForRequest (TimeSpan timeout)
  148. {
  149. if (wait != null)
  150. throw new InvalidOperationException ("Another wait operation is in progress");
  151. try {
  152. var wait_ = new ManualResetEvent (false);
  153. wait = wait_; // wait can be set to null if HttpContextAcquired runs to completion before we do WaitOne
  154. source.ListenerManager.GetHttpContextAsync (timeout, HttpContextAcquired);
  155. return wait_.WaitOne (timeout, false) && waiting.Count > 0;
  156. } catch (HttpListenerException e) {
  157. // FIXME: does this make sense? I doubt.
  158. if ((uint) e.ErrorCode == 0x80004005) // invalid handle. Happens during shutdown.
  159. while (true) Thread.Sleep (1000); // thread is about to be terminated.
  160. throw;
  161. } catch (ObjectDisposedException) {
  162. return false;
  163. } finally {
  164. wait = null;
  165. }
  166. }
  167. void HttpContextAcquired (HttpContextInfo ctx)
  168. {
  169. if (wait == null)
  170. throw new InvalidOperationException ("WaitForRequest operation has not started");
  171. var sctx = (HttpListenerContextInfo) ctx;
  172. if (State == CommunicationState.Opened && ctx != null)
  173. lock (waiting)
  174. waiting.Add (sctx.Source);
  175. SignalAsyncWait ();
  176. }
  177. }
  178. internal abstract class HttpReplyChannel : InternalReplyChannelBase
  179. {
  180. HttpChannelListenerBase<IReplyChannel> source;
  181. public HttpReplyChannel (HttpChannelListenerBase<IReplyChannel> listener)
  182. : base (listener)
  183. {
  184. this.source = listener;
  185. }
  186. public MessageEncoder Encoder {
  187. get { return source.MessageEncoder; }
  188. }
  189. internal MessageVersion MessageVersion {
  190. get { return source.MessageEncoder.MessageVersion; }
  191. }
  192. public override RequestContext ReceiveRequest (TimeSpan timeout)
  193. {
  194. RequestContext ctx;
  195. TryReceiveRequest (timeout, out ctx);
  196. return ctx;
  197. }
  198. protected override void OnOpen (TimeSpan timeout)
  199. {
  200. }
  201. protected string GetHeaderItem (string raw)
  202. {
  203. if (raw == null || raw.Length == 0)
  204. return raw;
  205. switch (raw [0]) {
  206. case '\'':
  207. case '"':
  208. if (raw [raw.Length - 1] == raw [0])
  209. return raw.Substring (1, raw.Length - 2);
  210. // FIXME: is it simply an error?
  211. break;
  212. }
  213. return raw;
  214. }
  215. protected HttpRequestMessageProperty CreateRequestProperty (string method, string query, NameValueCollection headers)
  216. {
  217. var prop = new HttpRequestMessageProperty ();
  218. prop.Method = method;
  219. prop.QueryString = query.StartsWith ("?") ? query.Substring (1) : query;
  220. // FIXME: prop.SuppressEntityBody
  221. prop.Headers.Add (headers);
  222. return prop;
  223. }
  224. }
  225. }