HttpRequestChannel.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. //
  2. // HttpRequestChannel.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.IO;
  31. using System.Net;
  32. using System.Net.Security;
  33. using System.ServiceModel;
  34. using System.ServiceModel.Description;
  35. using System.ServiceModel.Security;
  36. using System.Threading;
  37. namespace System.ServiceModel.Channels
  38. {
  39. internal class HttpRequestChannel : RequestChannelBase
  40. {
  41. HttpChannelFactory<IRequestChannel> source;
  42. WebRequest web_request;
  43. // FIXME: supply maxSizeOfHeaders.
  44. int max_headers = 0x10000;
  45. // Constructor
  46. public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
  47. EndpointAddress address, Uri via)
  48. : base (factory, address, via)
  49. {
  50. this.source = factory;
  51. }
  52. public int MaxSizeOfHeaders {
  53. get { return max_headers; }
  54. }
  55. public MessageEncoder Encoder {
  56. get { return source.MessageEncoder; }
  57. }
  58. // Request
  59. public override Message Request (Message message, TimeSpan timeout)
  60. {
  61. return EndRequest (BeginRequest (message, timeout, null, null));
  62. }
  63. void BeginProcessRequest (HttpChannelRequestAsyncResult result)
  64. {
  65. Message message = result.Message;
  66. TimeSpan timeout = result.Timeout;
  67. // FIXME: is distination really like this?
  68. Uri destination = message.Headers.To;
  69. if (destination == null) {
  70. if (source.Source.ManualAddressing)
  71. throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address.");
  72. else
  73. destination = Via ?? RemoteAddress.Uri;
  74. }
  75. web_request = HttpWebRequest.Create (destination);
  76. web_request.Method = "POST";
  77. web_request.ContentType = Encoder.ContentType;
  78. #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
  79. web_request.Timeout = (int) timeout.TotalMilliseconds;
  80. #endif
  81. // There is no SOAP Action/To header when AddressingVersion is None.
  82. if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
  83. message.Version.Addressing.Equals (AddressingVersion.None)) {
  84. if (message.Headers.Action != null) {
  85. web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
  86. message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
  87. }
  88. }
  89. // apply HttpRequestMessageProperty if exists.
  90. bool suppressEntityBody = false;
  91. #if !NET_2_1
  92. string pname = HttpRequestMessageProperty.Name;
  93. if (message.Properties.ContainsKey (pname)) {
  94. HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
  95. web_request.Headers.Add (hp.Headers);
  96. web_request.Method = hp.Method;
  97. // FIXME: do we have to handle hp.QueryString ?
  98. if (hp.SuppressEntityBody)
  99. suppressEntityBody = true;
  100. }
  101. #endif
  102. if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
  103. MemoryStream buffer = new MemoryStream ();
  104. Encoder.WriteMessage (message, buffer);
  105. if (buffer.Length > int.MaxValue)
  106. throw new InvalidOperationException ("The argument message is too large.");
  107. #if !NET_2_1
  108. web_request.ContentLength = (int) buffer.Length;
  109. #endif
  110. web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
  111. try {
  112. result.CompletedSynchronously &= r.CompletedSynchronously;
  113. using (Stream s = web_request.EndGetRequestStream (r))
  114. s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
  115. web_request.BeginGetResponse (GotResponse, result);
  116. } catch (Exception ex) {
  117. result.Complete (ex);
  118. }
  119. }, null);
  120. } else {
  121. web_request.BeginGetResponse (GotResponse, result);
  122. }
  123. }
  124. void GotResponse (IAsyncResult result)
  125. {
  126. HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
  127. channelResult.CompletedSynchronously &= result.CompletedSynchronously;
  128. WebResponse res;
  129. Stream resstr;
  130. try {
  131. res = web_request.EndGetResponse (result);
  132. resstr = res.GetResponseStream ();
  133. } catch (WebException we) {
  134. res = we.Response;
  135. try {
  136. // The response might contain SOAP fault. It might not.
  137. resstr = res.GetResponseStream ();
  138. } catch (WebException we2) {
  139. channelResult.Complete (we2);
  140. return;
  141. }
  142. }
  143. try {
  144. using (var responseStream = resstr) {
  145. MemoryStream ms = new MemoryStream ();
  146. byte [] b = new byte [65536];
  147. int n = 0;
  148. while (true) {
  149. n = responseStream.Read (b, 0, 65536);
  150. if (n == 0)
  151. break;
  152. ms.Write (b, 0, n);
  153. }
  154. ms.Seek (0, SeekOrigin.Begin);
  155. channelResult.Response = Encoder.ReadMessage (
  156. //responseStream, MaxSizeOfHeaders);
  157. ms, MaxSizeOfHeaders, res.ContentType);
  158. /*
  159. MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
  160. ret = buf.CreateMessage ();
  161. System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
  162. w.Formatting = System.Xml.Formatting.Indented;
  163. buf.CreateMessage ().WriteMessage (w);
  164. w.Close ();
  165. */
  166. channelResult.Complete ();
  167. }
  168. } catch (Exception ex) {
  169. channelResult.Complete (ex);
  170. } finally {
  171. res.Close ();
  172. }
  173. }
  174. public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
  175. {
  176. ThrowIfDisposedOrNotOpen ();
  177. HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, callback, state);
  178. BeginProcessRequest (result);
  179. return result;
  180. }
  181. public override Message EndRequest (IAsyncResult result)
  182. {
  183. if (result == null)
  184. throw new ArgumentNullException ("result");
  185. HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
  186. if (r == null)
  187. throw new InvalidOperationException ("Wrong IAsyncResult");
  188. r.WaitEnd ();
  189. return r.Response;
  190. }
  191. // Abort
  192. protected override void OnAbort ()
  193. {
  194. if (web_request != null)
  195. web_request.Abort ();
  196. web_request = null;
  197. }
  198. // Close
  199. protected override void OnClose (TimeSpan timeout)
  200. {
  201. if (web_request != null)
  202. web_request.Abort ();
  203. web_request = null;
  204. }
  205. protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
  206. {
  207. throw new NotImplementedException ();
  208. }
  209. protected override void OnEndClose (IAsyncResult result)
  210. {
  211. throw new NotImplementedException ();
  212. }
  213. // Open
  214. protected override void OnOpen (TimeSpan timeout)
  215. {
  216. }
  217. protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
  218. {
  219. throw new NotImplementedException ();
  220. }
  221. protected override void OnEndOpen (IAsyncResult result)
  222. {
  223. throw new NotImplementedException ();
  224. }
  225. class HttpChannelRequestAsyncResult : IAsyncResult
  226. {
  227. public Message Message {
  228. get; private set;
  229. }
  230. public TimeSpan Timeout {
  231. get; private set;
  232. }
  233. AsyncCallback callback;
  234. ManualResetEvent wait;
  235. Exception error;
  236. public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
  237. {
  238. CompletedSynchronously = true;
  239. Message = message;
  240. Timeout = timeout;
  241. this.callback = callback;
  242. AsyncState = state;
  243. wait = new ManualResetEvent (false);
  244. }
  245. public Message Response {
  246. get; set;
  247. }
  248. public WaitHandle AsyncWaitHandle {
  249. get { return wait; }
  250. }
  251. public object AsyncState {
  252. get; private set;
  253. }
  254. public void Complete ()
  255. {
  256. Complete (null);
  257. }
  258. public void Complete (Exception ex)
  259. {
  260. if (IsCompleted) {
  261. return;
  262. }
  263. // If we've already stored an error, don't replace it
  264. error = error ?? ex;
  265. IsCompleted = true;
  266. wait.Set ();
  267. if (callback != null)
  268. callback (this);
  269. }
  270. public bool CompletedSynchronously {
  271. get; set;
  272. }
  273. public bool IsCompleted {
  274. get; private set;
  275. }
  276. public void WaitEnd ()
  277. {
  278. if (!IsCompleted) {
  279. // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
  280. // Is the current request cancelled and an exception thrown? If so we need to pass the
  281. // exception to the Complete () method and allow the result to complete 'normally'.
  282. #if NET_2_1 || MONOTOUCH
  283. // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
  284. bool result = wait.WaitOne (Timeout);
  285. #else
  286. bool result = wait.WaitOne (Timeout, true);
  287. #endif
  288. if (!result)
  289. throw new TimeoutException ();
  290. }
  291. if (error != null)
  292. throw error;
  293. }
  294. }
  295. }
  296. }