HttpRequestChannel.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. // Constructor
  44. public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
  45. EndpointAddress address, Uri via)
  46. : base (factory, address, via)
  47. {
  48. this.source = factory;
  49. }
  50. public MessageEncoder Encoder {
  51. get { return source.MessageEncoder; }
  52. }
  53. // Request
  54. public override Message Request (Message message, TimeSpan timeout)
  55. {
  56. return EndRequest (BeginRequest (message, timeout, null, null));
  57. }
  58. void BeginProcessRequest (HttpChannelRequestAsyncResult result)
  59. {
  60. Message message = result.Message;
  61. TimeSpan timeout = result.Timeout;
  62. // FIXME: is distination really like this?
  63. Uri destination = message.Headers.To;
  64. if (destination == null) {
  65. if (source.Transport.ManualAddressing)
  66. throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address.");
  67. else
  68. destination = Via ?? RemoteAddress.Uri;
  69. }
  70. web_request = HttpWebRequest.Create (destination);
  71. web_request.Method = "POST";
  72. web_request.ContentType = Encoder.ContentType;
  73. #if NET_2_1
  74. var cmgr = source.GetProperty<IHttpCookieContainerManager> ();
  75. if (cmgr != null)
  76. ((HttpWebRequest) web_request).CookieContainer = cmgr.CookieContainer;
  77. #endif
  78. #if !MOONLIGHT // until we support NetworkCredential like SL4 will do.
  79. // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
  80. var httpbe = (HttpTransportBindingElement) source.Transport;
  81. string authType = null;
  82. switch (httpbe.AuthenticationScheme) {
  83. // AuthenticationSchemes.Anonymous is the default, ignored.
  84. case AuthenticationSchemes.Basic:
  85. authType = "Basic";
  86. break;
  87. case AuthenticationSchemes.Digest:
  88. authType = "Digest";
  89. break;
  90. case AuthenticationSchemes.Ntlm:
  91. authType = "Ntlm";
  92. break;
  93. case AuthenticationSchemes.Negotiate:
  94. authType = "Negotiate";
  95. break;
  96. }
  97. if (authType != null) {
  98. var cred = source.ClientCredentials;
  99. string user = cred != null ? cred.UserName.UserName : null;
  100. string pwd = cred != null ? cred.UserName.Password : null;
  101. if (String.IsNullOrEmpty (user))
  102. throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
  103. var nc = new NetworkCredential (user, pwd);
  104. web_request.Credentials = nc;
  105. // FIXME: it is said required in SL4, but it blocks full WCF.
  106. //web_request.UseDefaultCredentials = false;
  107. }
  108. #endif
  109. #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
  110. web_request.Timeout = (int) timeout.TotalMilliseconds;
  111. #endif
  112. // There is no SOAP Action/To header when AddressingVersion is None.
  113. if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
  114. message.Version.Addressing.Equals (AddressingVersion.None)) {
  115. if (message.Headers.Action != null) {
  116. web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
  117. message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
  118. }
  119. }
  120. // apply HttpRequestMessageProperty if exists.
  121. bool suppressEntityBody = false;
  122. #if !NET_2_1
  123. string pname = HttpRequestMessageProperty.Name;
  124. if (message.Properties.ContainsKey (pname)) {
  125. HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
  126. web_request.Headers.Clear ();
  127. web_request.Headers.Add (hp.Headers);
  128. web_request.Method = hp.Method;
  129. // FIXME: do we have to handle hp.QueryString ?
  130. if (hp.SuppressEntityBody)
  131. suppressEntityBody = true;
  132. }
  133. #endif
  134. if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
  135. MemoryStream buffer = new MemoryStream ();
  136. Encoder.WriteMessage (message, buffer);
  137. if (buffer.Length > int.MaxValue)
  138. throw new InvalidOperationException ("The argument message is too large.");
  139. #if !NET_2_1
  140. web_request.ContentLength = (int) buffer.Length;
  141. #endif
  142. web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
  143. try {
  144. result.CompletedSynchronously &= r.CompletedSynchronously;
  145. using (Stream s = web_request.EndGetRequestStream (r))
  146. s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
  147. web_request.BeginGetResponse (GotResponse, result);
  148. } catch (Exception ex) {
  149. result.Complete (ex);
  150. }
  151. }, null);
  152. } else {
  153. web_request.BeginGetResponse (GotResponse, result);
  154. }
  155. }
  156. void GotResponse (IAsyncResult result)
  157. {
  158. HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
  159. channelResult.CompletedSynchronously &= result.CompletedSynchronously;
  160. WebResponse res;
  161. Stream resstr;
  162. try {
  163. res = web_request.EndGetResponse (result);
  164. resstr = res.GetResponseStream ();
  165. } catch (WebException we) {
  166. res = we.Response;
  167. if (res == null) {
  168. channelResult.Complete (we);
  169. return;
  170. }
  171. try {
  172. // The response might contain SOAP fault. It might not.
  173. resstr = res.GetResponseStream ();
  174. } catch (WebException we2) {
  175. channelResult.Complete (we2);
  176. return;
  177. }
  178. }
  179. var hrr = (HttpWebResponse) res;
  180. if ((int) hrr.StatusCode >= 400 && (int) hrr.StatusCode < 500) {
  181. channelResult.Complete (new WebException (String.Format ("There was an error on processing web request: Status code {0}({1}): {2}", (int) hrr.StatusCode, hrr.StatusCode, hrr.StatusDescription)));
  182. }
  183. try {
  184. using (var responseStream = resstr) {
  185. MemoryStream ms = new MemoryStream ();
  186. byte [] b = new byte [65536];
  187. int n = 0;
  188. while (true) {
  189. n = responseStream.Read (b, 0, 65536);
  190. if (n == 0)
  191. break;
  192. ms.Write (b, 0, n);
  193. }
  194. ms.Seek (0, SeekOrigin.Begin);
  195. Message ret = Encoder.ReadMessage (
  196. ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
  197. var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
  198. foreach (var key in hrr.Headers.AllKeys)
  199. rp.Headers [key] = hrr.Headers [key];
  200. ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
  201. /*
  202. MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
  203. ret = buf.CreateMessage ();
  204. System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
  205. w.Formatting = System.Xml.Formatting.Indented;
  206. buf.CreateMessage ().WriteMessage (w);
  207. w.Close ();
  208. */
  209. channelResult.Response = ret;
  210. channelResult.Complete ();
  211. }
  212. } catch (Exception ex) {
  213. channelResult.Complete (ex);
  214. } finally {
  215. res.Close ();
  216. }
  217. }
  218. public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
  219. {
  220. ThrowIfDisposedOrNotOpen ();
  221. HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, callback, state);
  222. BeginProcessRequest (result);
  223. return result;
  224. }
  225. public override Message EndRequest (IAsyncResult result)
  226. {
  227. if (result == null)
  228. throw new ArgumentNullException ("result");
  229. HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
  230. if (r == null)
  231. throw new InvalidOperationException ("Wrong IAsyncResult");
  232. r.WaitEnd ();
  233. return r.Response;
  234. }
  235. // Abort
  236. protected override void OnAbort ()
  237. {
  238. if (web_request != null)
  239. web_request.Abort ();
  240. web_request = null;
  241. }
  242. // Close
  243. protected override void OnClose (TimeSpan timeout)
  244. {
  245. if (web_request != null)
  246. web_request.Abort ();
  247. web_request = null;
  248. }
  249. protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
  250. {
  251. throw new NotImplementedException ();
  252. }
  253. protected override void OnEndClose (IAsyncResult result)
  254. {
  255. throw new NotImplementedException ();
  256. }
  257. // Open
  258. protected override void OnOpen (TimeSpan timeout)
  259. {
  260. }
  261. protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
  262. {
  263. throw new NotImplementedException ();
  264. }
  265. protected override void OnEndOpen (IAsyncResult result)
  266. {
  267. throw new NotImplementedException ();
  268. }
  269. class HttpChannelRequestAsyncResult : IAsyncResult
  270. {
  271. public Message Message {
  272. get; private set;
  273. }
  274. public TimeSpan Timeout {
  275. get; private set;
  276. }
  277. AsyncCallback callback;
  278. ManualResetEvent wait;
  279. Exception error;
  280. public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
  281. {
  282. CompletedSynchronously = true;
  283. Message = message;
  284. Timeout = timeout;
  285. this.callback = callback;
  286. AsyncState = state;
  287. wait = new ManualResetEvent (false);
  288. }
  289. public Message Response {
  290. get; set;
  291. }
  292. public WaitHandle AsyncWaitHandle {
  293. get { return wait; }
  294. }
  295. public object AsyncState {
  296. get; private set;
  297. }
  298. public void Complete ()
  299. {
  300. Complete (null);
  301. }
  302. public void Complete (Exception ex)
  303. {
  304. if (IsCompleted) {
  305. return;
  306. }
  307. // If we've already stored an error, don't replace it
  308. error = error ?? ex;
  309. IsCompleted = true;
  310. wait.Set ();
  311. if (callback != null)
  312. callback (this);
  313. }
  314. public bool CompletedSynchronously {
  315. get; set;
  316. }
  317. public bool IsCompleted {
  318. get; private set;
  319. }
  320. public void WaitEnd ()
  321. {
  322. if (!IsCompleted) {
  323. // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
  324. // Is the current request cancelled and an exception thrown? If so we need to pass the
  325. // exception to the Complete () method and allow the result to complete 'normally'.
  326. #if NET_2_1
  327. // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
  328. bool result = wait.WaitOne (Timeout);
  329. #else
  330. bool result = wait.WaitOne (Timeout, true);
  331. #endif
  332. if (!result)
  333. throw new TimeoutException ();
  334. }
  335. if (error != null)
  336. throw error;
  337. }
  338. }
  339. }
  340. }