2
0

HttpRequestChannel.cs 12 KB

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