HttpRequestChannel.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. #if MOBILE
  54. public override T GetProperty<T> ()
  55. {
  56. if (typeof (T) == typeof (IHttpCookieContainerManager))
  57. return source.GetProperty<T> ();
  58. return base.GetProperty<T> ();
  59. }
  60. #endif
  61. // Request
  62. public override Message Request (Message message, TimeSpan timeout)
  63. {
  64. return EndRequest (BeginRequest (message, timeout, null, null));
  65. }
  66. void BeginProcessRequest (HttpChannelRequestAsyncResult result)
  67. {
  68. Message message = result.Message;
  69. TimeSpan timeout = result.Timeout;
  70. // FIXME: is distination really like this?
  71. Uri destination = message.Headers.To;
  72. if (destination == null) {
  73. if (source.Transport.ManualAddressing)
  74. throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address.");
  75. else
  76. destination = Via ?? RemoteAddress.Uri;
  77. }
  78. var web_request = (HttpWebRequest) HttpWebRequest.Create (destination);
  79. web_requests.Add (web_request);
  80. result.WebRequest = web_request;
  81. web_request.Method = "POST";
  82. web_request.ContentType = Encoder.ContentType;
  83. HttpWebRequest hwr = (web_request as HttpWebRequest);
  84. var cmgr = source.GetProperty<IHttpCookieContainerManager> ();
  85. if (cmgr != null)
  86. hwr.CookieContainer = cmgr.CookieContainer;
  87. // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
  88. var httpbe = (HttpTransportBindingElement) source.Transport;
  89. string authType = null;
  90. switch (httpbe.AuthenticationScheme) {
  91. // AuthenticationSchemes.Anonymous is the default, ignored.
  92. case AuthenticationSchemes.Basic:
  93. authType = "Basic";
  94. break;
  95. case AuthenticationSchemes.Digest:
  96. authType = "Digest";
  97. break;
  98. case AuthenticationSchemes.Ntlm:
  99. authType = "Ntlm";
  100. break;
  101. case AuthenticationSchemes.Negotiate:
  102. authType = "Negotiate";
  103. break;
  104. }
  105. if (authType != null) {
  106. var cred = source.ClientCredentials;
  107. string user = cred != null ? cred.UserName.UserName : null;
  108. string pwd = cred != null ? cred.UserName.Password : null;
  109. if (String.IsNullOrEmpty (user))
  110. throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
  111. var nc = new NetworkCredential (user, pwd);
  112. web_request.Credentials = nc;
  113. // FIXME: it is said required in SL4, but it blocks full WCF.
  114. //web_request.UseDefaultCredentials = false;
  115. }
  116. web_request.Timeout = (int) timeout.TotalMilliseconds;
  117. web_request.KeepAlive = httpbe.KeepAliveEnabled;
  118. // There is no SOAP Action/To header when AddressingVersion is None.
  119. if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
  120. message.Version.Addressing.Equals (AddressingVersion.None)) {
  121. if (message.Headers.Action != null) {
  122. web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
  123. message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
  124. }
  125. }
  126. // apply HttpRequestMessageProperty if exists.
  127. bool suppressEntityBody = false;
  128. string pname = HttpRequestMessageProperty.Name;
  129. if (message.Properties.ContainsKey (pname)) {
  130. HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
  131. foreach (var key in hp.Headers.AllKeys) {
  132. if (WebHeaderCollection.IsRestricted (key)) { // do not ignore this. WebHeaderCollection rejects restricted ones.
  133. // FIXME: huh, there should be any better way to do such stupid conversion.
  134. switch (key) {
  135. case "Accept":
  136. web_request.Accept = hp.Headers [key];
  137. break;
  138. case "Connection":
  139. web_request.Connection = hp.Headers [key];
  140. break;
  141. //case "ContentLength":
  142. // web_request.ContentLength = hp.Headers [key];
  143. // break;
  144. case "ContentType":
  145. web_request.ContentType = hp.Headers [key];
  146. break;
  147. //case "Date":
  148. // web_request.Date = hp.Headers [key];
  149. // break;
  150. case "Expect":
  151. web_request.Expect = hp.Headers [key];
  152. break;
  153. case "Host":
  154. web_request.Host = hp.Headers [key];
  155. break;
  156. //case "If-Modified-Since":
  157. // web_request.IfModifiedSince = hp.Headers [key];
  158. // break;
  159. case "Referer":
  160. web_request.Referer = hp.Headers [key];
  161. break;
  162. case "Transfer-Encoding":
  163. web_request.TransferEncoding = hp.Headers [key];
  164. break;
  165. case "User-Agent":
  166. web_request.UserAgent = hp.Headers [key];
  167. break;
  168. }
  169. }
  170. else
  171. web_request.Headers [key] = hp.Headers [key];
  172. }
  173. web_request.Method = hp.Method;
  174. // FIXME: do we have to handle hp.QueryString ?
  175. if (hp.SuppressEntityBody)
  176. suppressEntityBody = true;
  177. }
  178. #if !MOBILE
  179. if (source.ClientCredentials != null) {
  180. var cred = source.ClientCredentials;
  181. if ((cred.ClientCertificate != null) && (cred.ClientCertificate.Certificate != null))
  182. ((HttpWebRequest)web_request).ClientCertificates.Add (cred.ClientCertificate.Certificate);
  183. }
  184. #endif
  185. if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
  186. MemoryStream buffer = new MemoryStream ();
  187. Encoder.WriteMessage (message, buffer);
  188. if (buffer.Length > int.MaxValue)
  189. throw new InvalidOperationException ("The argument message is too large.");
  190. web_request.ContentLength = (int) buffer.Length;
  191. web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
  192. try {
  193. result.CompletedSynchronously &= r.CompletedSynchronously;
  194. using (Stream s = web_request.EndGetRequestStream (r))
  195. s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
  196. web_request.BeginGetResponse (GotResponse, result);
  197. } catch (WebException ex) {
  198. switch (ex.Status) {
  199. case WebExceptionStatus.NameResolutionFailure:
  200. case WebExceptionStatus.ConnectFailure:
  201. result.Complete (new EndpointNotFoundException (new EndpointNotFoundException ().Message, ex));
  202. break;
  203. default:
  204. result.Complete (ex);
  205. break;
  206. }
  207. } catch (Exception ex) {
  208. result.Complete (ex);
  209. }
  210. }, null);
  211. } else {
  212. web_request.BeginGetResponse (GotResponse, result);
  213. }
  214. }
  215. void GotResponse (IAsyncResult result)
  216. {
  217. HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
  218. channelResult.CompletedSynchronously &= result.CompletedSynchronously;
  219. WebResponse res;
  220. Stream resstr;
  221. try {
  222. res = channelResult.WebRequest.EndGetResponse (result);
  223. resstr = res.GetResponseStream ();
  224. } catch (WebException we) {
  225. res = we.Response;
  226. if (res == null) {
  227. channelResult.Complete (we);
  228. return;
  229. }
  230. var hrr2 = (HttpWebResponse) res;
  231. if ((int) hrr2.StatusCode >= 400 && (int) hrr2.StatusCode < 500) {
  232. Exception exception = new WebException (
  233. String.Format ("There was an error on processing web request: Status code {0}({1}): {2}",
  234. (int) hrr2.StatusCode, hrr2.StatusCode, hrr2.StatusDescription), null,
  235. WebExceptionStatus.ProtocolError, hrr2);
  236. if ((int) hrr2.StatusCode == 404) {
  237. // Throw the same exception .NET does
  238. exception = new EndpointNotFoundException (
  239. "There was no endpoint listening at {0} that could accept the message. This is often caused by an incorrect address " +
  240. "or SOAP action. See InnerException, if present, for more details.",
  241. exception);
  242. }
  243. channelResult.Complete (exception);
  244. return;
  245. }
  246. try {
  247. // The response might contain SOAP fault. It might not.
  248. resstr = res.GetResponseStream ();
  249. } catch (WebException we2) {
  250. channelResult.Complete (we2);
  251. return;
  252. }
  253. }
  254. var hrr = (HttpWebResponse) res;
  255. if ((int) hrr.StatusCode >= 400 && (int) hrr.StatusCode < 500) {
  256. 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)));
  257. }
  258. try {
  259. Message ret;
  260. // TODO: unit test to make sure an empty response never throws
  261. // an exception at this level
  262. if (hrr.ContentLength == 0) {
  263. ret = Message.CreateMessage (Encoder.MessageVersion, String.Empty);
  264. } else {
  265. using (var responseStream = resstr) {
  266. MemoryStream ms = new MemoryStream ();
  267. byte [] b = new byte [65536];
  268. int n = 0;
  269. while (true) {
  270. n = responseStream.Read (b, 0, 65536);
  271. if (n == 0)
  272. break;
  273. ms.Write (b, 0, n);
  274. }
  275. ms.Seek (0, SeekOrigin.Begin);
  276. ret = Encoder.ReadMessage (
  277. ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
  278. }
  279. }
  280. var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
  281. foreach (var key in hrr.Headers.AllKeys)
  282. rp.Headers [key] = hrr.Headers [key];
  283. ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
  284. channelResult.Response = ret;
  285. channelResult.Complete ();
  286. } catch (Exception ex) {
  287. channelResult.Complete (ex);
  288. } finally {
  289. res.Close ();
  290. }
  291. }
  292. public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
  293. {
  294. ThrowIfDisposedOrNotOpen ();
  295. HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, this, callback, state);
  296. BeginProcessRequest (result);
  297. return result;
  298. }
  299. public override Message EndRequest (IAsyncResult result)
  300. {
  301. if (result == null)
  302. throw new ArgumentNullException ("result");
  303. HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
  304. if (r == null)
  305. throw new InvalidOperationException ("Wrong IAsyncResult");
  306. r.WaitEnd ();
  307. return r.Response;
  308. }
  309. // Abort
  310. protected override void OnAbort ()
  311. {
  312. foreach (var web_request in web_requests.ToArray ())
  313. web_request.Abort ();
  314. web_requests.Clear ();
  315. }
  316. // Close
  317. protected override void OnClose (TimeSpan timeout)
  318. {
  319. OnAbort ();
  320. }
  321. protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
  322. {
  323. OnAbort ();
  324. return base.OnBeginClose (timeout, callback, state);
  325. }
  326. protected override void OnEndClose (IAsyncResult result)
  327. {
  328. base.OnEndClose (result);
  329. }
  330. // Open
  331. protected override void OnOpen (TimeSpan timeout)
  332. {
  333. }
  334. [MonoTODO ("find out what to do here")]
  335. protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
  336. {
  337. return base.OnBeginOpen (timeout, callback, state);
  338. }
  339. [MonoTODO ("find out what to do here")]
  340. protected override void OnEndOpen (IAsyncResult result)
  341. {
  342. base.OnEndOpen (result);
  343. }
  344. class HttpChannelRequestAsyncResult : IAsyncResult, IDisposable
  345. {
  346. public Message Message {
  347. get; private set;
  348. }
  349. public TimeSpan Timeout {
  350. get; private set;
  351. }
  352. AsyncCallback callback;
  353. ManualResetEvent wait;
  354. Exception error;
  355. object locker = new object ();
  356. bool is_completed;
  357. HttpRequestChannel owner;
  358. public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, HttpRequestChannel owner, AsyncCallback callback, object state)
  359. {
  360. Message = message;
  361. Timeout = timeout;
  362. this.owner = owner;
  363. this.callback = callback;
  364. AsyncState = state;
  365. }
  366. public Message Response {
  367. get; set;
  368. }
  369. public WebRequest WebRequest { get; set; }
  370. public WaitHandle AsyncWaitHandle {
  371. get {
  372. lock (locker) {
  373. if (wait == null)
  374. wait = new ManualResetEvent (is_completed);
  375. }
  376. return wait;
  377. }
  378. }
  379. public object AsyncState {
  380. get; private set;
  381. }
  382. public void Complete ()
  383. {
  384. Complete (null);
  385. }
  386. public void Complete (Exception ex)
  387. {
  388. if (IsCompleted) {
  389. return;
  390. }
  391. // If we've already stored an error, don't replace it
  392. error = error ?? ex;
  393. IsCompleted = true;
  394. if (callback != null)
  395. callback (this);
  396. }
  397. public bool CompletedSynchronously {
  398. get; set;
  399. }
  400. public bool IsCompleted {
  401. get { return is_completed; }
  402. set {
  403. is_completed = value;
  404. lock (locker) {
  405. if (is_completed && wait != null)
  406. wait.Set ();
  407. Cleanup ();
  408. }
  409. }
  410. }
  411. public void WaitEnd ()
  412. {
  413. if (!IsCompleted) {
  414. // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
  415. // Is the current request cancelled and an exception thrown? If so we need to pass the
  416. // exception to the Complete () method and allow the result to complete 'normally'.
  417. #if MOBILE
  418. // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
  419. bool result = AsyncWaitHandle.WaitOne (Timeout);
  420. #else
  421. bool result = AsyncWaitHandle.WaitOne (Timeout, true);
  422. #endif
  423. if (!result)
  424. throw new TimeoutException ();
  425. }
  426. if (error != null)
  427. throw error;
  428. }
  429. public void Dispose ()
  430. {
  431. Cleanup ();
  432. }
  433. void Cleanup ()
  434. {
  435. owner.web_requests.Remove (WebRequest);
  436. }
  437. }
  438. }
  439. }