HttpRequestChannel.cs 11 KB

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