HttpRequestChannel.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. // 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. string pname = HttpRequestMessageProperty.Name;
  128. if (message.Properties.ContainsKey (pname)) {
  129. HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
  130. foreach (var key in hp.Headers.AllKeys) {
  131. if (WebHeaderCollection.IsRestricted (key)) { // do not ignore this. WebHeaderCollection rejects restricted ones.
  132. // FIXME: huh, there should be any better way to do such stupid conversion.
  133. switch (key) {
  134. case "Accept":
  135. web_request.Accept = hp.Headers [key];
  136. break;
  137. case "Connection":
  138. web_request.Connection = hp.Headers [key];
  139. break;
  140. //case "ContentLength":
  141. // web_request.ContentLength = hp.Headers [key];
  142. // break;
  143. case "ContentType":
  144. web_request.ContentType = hp.Headers [key];
  145. break;
  146. //case "Date":
  147. // web_request.Date = hp.Headers [key];
  148. // break;
  149. case "Expect":
  150. web_request.Expect = hp.Headers [key];
  151. break;
  152. case "Host":
  153. web_request.Host = hp.Headers [key];
  154. break;
  155. //case "If-Modified-Since":
  156. // web_request.IfModifiedSince = hp.Headers [key];
  157. // break;
  158. case "Referer":
  159. web_request.Referer = hp.Headers [key];
  160. break;
  161. case "Transfer-Encoding":
  162. web_request.TransferEncoding = hp.Headers [key];
  163. break;
  164. case "User-Agent":
  165. web_request.UserAgent = hp.Headers [key];
  166. break;
  167. }
  168. }
  169. else
  170. web_request.Headers [key] = hp.Headers [key];
  171. }
  172. web_request.Method = hp.Method;
  173. // FIXME: do we have to handle hp.QueryString ?
  174. if (hp.SuppressEntityBody)
  175. suppressEntityBody = true;
  176. }
  177. #if !MOBILE
  178. if (source.ClientCredentials != null) {
  179. var cred = source.ClientCredentials;
  180. if ((cred.ClientCertificate != null) && (cred.ClientCertificate.Certificate != null))
  181. ((HttpWebRequest)web_request).ClientCertificates.Add (cred.ClientCertificate.Certificate);
  182. }
  183. #endif
  184. if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
  185. MemoryStream buffer = new MemoryStream ();
  186. Encoder.WriteMessage (message, buffer);
  187. if (buffer.Length > int.MaxValue)
  188. throw new InvalidOperationException ("The argument message is too large.");
  189. web_request.ContentLength = (int) buffer.Length;
  190. web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
  191. try {
  192. result.CompletedSynchronously &= r.CompletedSynchronously;
  193. using (Stream s = web_request.EndGetRequestStream (r))
  194. s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
  195. web_request.BeginGetResponse (GotResponse, result);
  196. } catch (WebException ex) {
  197. switch (ex.Status) {
  198. case WebExceptionStatus.NameResolutionFailure:
  199. case WebExceptionStatus.ConnectFailure:
  200. result.Complete (new EndpointNotFoundException (new EndpointNotFoundException ().Message, ex));
  201. break;
  202. default:
  203. result.Complete (ex);
  204. break;
  205. }
  206. } catch (Exception ex) {
  207. result.Complete (ex);
  208. }
  209. }, null);
  210. } else {
  211. web_request.BeginGetResponse (GotResponse, result);
  212. }
  213. }
  214. void GotResponse (IAsyncResult result)
  215. {
  216. HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
  217. channelResult.CompletedSynchronously &= result.CompletedSynchronously;
  218. WebResponse res;
  219. Stream resstr;
  220. try {
  221. res = channelResult.WebRequest.EndGetResponse (result);
  222. resstr = res.GetResponseStream ();
  223. } catch (WebException we) {
  224. res = we.Response;
  225. if (res == null) {
  226. channelResult.Complete (we);
  227. return;
  228. }
  229. var hrr2 = (HttpWebResponse) res;
  230. if ((int) hrr2.StatusCode >= 400 && (int) hrr2.StatusCode < 500) {
  231. Exception exception = new WebException (
  232. String.Format ("There was an error on processing web request: Status code {0}({1}): {2}",
  233. (int) hrr2.StatusCode, hrr2.StatusCode, hrr2.StatusDescription), null,
  234. WebExceptionStatus.ProtocolError, hrr2);
  235. if ((int) hrr2.StatusCode == 404) {
  236. // Throw the same exception .NET does
  237. exception = new EndpointNotFoundException (
  238. "There was no endpoint listening at {0} that could accept the message. This is often caused by an incorrect address " +
  239. "or SOAP action. See InnerException, if present, for more details.",
  240. exception);
  241. }
  242. channelResult.Complete (exception);
  243. return;
  244. }
  245. try {
  246. // The response might contain SOAP fault. It might not.
  247. resstr = res.GetResponseStream ();
  248. } catch (WebException we2) {
  249. channelResult.Complete (we2);
  250. return;
  251. }
  252. }
  253. var hrr = (HttpWebResponse) res;
  254. if ((int) hrr.StatusCode >= 400 && (int) hrr.StatusCode < 500) {
  255. 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)));
  256. }
  257. try {
  258. Message ret;
  259. // TODO: unit test to make sure an empty response never throws
  260. // an exception at this level
  261. if (hrr.ContentLength == 0) {
  262. ret = Message.CreateMessage (Encoder.MessageVersion, String.Empty);
  263. } else {
  264. using (var responseStream = resstr) {
  265. MemoryStream ms = new MemoryStream ();
  266. byte [] b = new byte [65536];
  267. int n = 0;
  268. while (true) {
  269. n = responseStream.Read (b, 0, 65536);
  270. if (n == 0)
  271. break;
  272. ms.Write (b, 0, n);
  273. }
  274. ms.Seek (0, SeekOrigin.Begin);
  275. ret = Encoder.ReadMessage (
  276. ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
  277. }
  278. }
  279. var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
  280. foreach (var key in hrr.Headers.AllKeys)
  281. rp.Headers [key] = hrr.Headers [key];
  282. ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
  283. channelResult.Response = ret;
  284. channelResult.Complete ();
  285. } catch (Exception ex) {
  286. channelResult.Complete (ex);
  287. } finally {
  288. res.Close ();
  289. }
  290. }
  291. public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
  292. {
  293. ThrowIfDisposedOrNotOpen ();
  294. HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, this, callback, state);
  295. BeginProcessRequest (result);
  296. return result;
  297. }
  298. public override Message EndRequest (IAsyncResult result)
  299. {
  300. if (result == null)
  301. throw new ArgumentNullException ("result");
  302. HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
  303. if (r == null)
  304. throw new InvalidOperationException ("Wrong IAsyncResult");
  305. r.WaitEnd ();
  306. return r.Response;
  307. }
  308. // Abort
  309. protected override void OnAbort ()
  310. {
  311. foreach (var web_request in web_requests.ToArray ())
  312. web_request.Abort ();
  313. web_requests.Clear ();
  314. }
  315. // Close
  316. protected override void OnClose (TimeSpan timeout)
  317. {
  318. OnAbort ();
  319. }
  320. protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
  321. {
  322. OnAbort ();
  323. return base.OnBeginClose (timeout, callback, state);
  324. }
  325. protected override void OnEndClose (IAsyncResult result)
  326. {
  327. base.OnEndClose (result);
  328. }
  329. // Open
  330. protected override void OnOpen (TimeSpan timeout)
  331. {
  332. }
  333. [MonoTODO ("find out what to do here")]
  334. protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
  335. {
  336. return base.OnBeginOpen (timeout, callback, state);
  337. }
  338. [MonoTODO ("find out what to do here")]
  339. protected override void OnEndOpen (IAsyncResult result)
  340. {
  341. base.OnEndOpen (result);
  342. }
  343. class HttpChannelRequestAsyncResult : IAsyncResult, IDisposable
  344. {
  345. public Message Message {
  346. get; private set;
  347. }
  348. public TimeSpan Timeout {
  349. get; private set;
  350. }
  351. AsyncCallback callback;
  352. ManualResetEvent wait;
  353. Exception error;
  354. object locker = new object ();
  355. bool is_completed;
  356. HttpRequestChannel owner;
  357. public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, HttpRequestChannel owner, AsyncCallback callback, object state)
  358. {
  359. Message = message;
  360. Timeout = timeout;
  361. this.owner = owner;
  362. this.callback = callback;
  363. AsyncState = state;
  364. }
  365. public Message Response {
  366. get; set;
  367. }
  368. public WebRequest WebRequest { get; set; }
  369. public WaitHandle AsyncWaitHandle {
  370. get {
  371. lock (locker) {
  372. if (wait == null)
  373. wait = new ManualResetEvent (is_completed);
  374. }
  375. return wait;
  376. }
  377. }
  378. public object AsyncState {
  379. get; private set;
  380. }
  381. public void Complete ()
  382. {
  383. Complete (null);
  384. }
  385. public void Complete (Exception ex)
  386. {
  387. if (IsCompleted) {
  388. return;
  389. }
  390. // If we've already stored an error, don't replace it
  391. error = error ?? ex;
  392. IsCompleted = true;
  393. if (callback != null)
  394. callback (this);
  395. }
  396. public bool CompletedSynchronously {
  397. get; set;
  398. }
  399. public bool IsCompleted {
  400. get { return is_completed; }
  401. set {
  402. is_completed = value;
  403. lock (locker) {
  404. if (is_completed && wait != null)
  405. wait.Set ();
  406. Cleanup ();
  407. }
  408. }
  409. }
  410. public void WaitEnd ()
  411. {
  412. if (!IsCompleted) {
  413. // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
  414. // Is the current request cancelled and an exception thrown? If so we need to pass the
  415. // exception to the Complete () method and allow the result to complete 'normally'.
  416. #if MOBILE
  417. // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
  418. bool result = AsyncWaitHandle.WaitOne (Timeout);
  419. #else
  420. bool result = AsyncWaitHandle.WaitOne (Timeout, true);
  421. #endif
  422. if (!result)
  423. throw new TimeoutException ();
  424. }
  425. if (error != null)
  426. throw error;
  427. }
  428. public void Dispose ()
  429. {
  430. Cleanup ();
  431. }
  432. void Cleanup ()
  433. {
  434. owner.web_requests.Remove (WebRequest);
  435. }
  436. }
  437. }
  438. }