HttpRequestChannel.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. EndpointAddress address;
  43. Uri via;
  44. WebRequest web_request;
  45. // FIXME: supply maxSizeOfHeaders.
  46. int max_headers = 0x10000;
  47. // Constructor
  48. public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
  49. EndpointAddress address, Uri via)
  50. : base (factory)
  51. {
  52. this.source = factory;
  53. this.address = address;
  54. this.via = via;
  55. }
  56. public int MaxSizeOfHeaders {
  57. get { return max_headers; }
  58. }
  59. public MessageEncoder Encoder {
  60. get { return source.MessageEncoder; }
  61. }
  62. public override EndpointAddress RemoteAddress {
  63. get { return address; }
  64. }
  65. public override Uri Via {
  66. get { return via; }
  67. }
  68. // Request
  69. public override Message Request (Message message, TimeSpan timeout)
  70. {
  71. return ProcessRequest (message, timeout);
  72. }
  73. Message ProcessRequest (Message message, TimeSpan timeout)
  74. {
  75. // FIXME: is distination really like this?
  76. Uri destination = message.Headers.To ?? Via ?? RemoteAddress.Uri;
  77. web_request = HttpWebRequest.Create (destination);
  78. web_request.Method = "POST";
  79. web_request.ContentType = Encoder.ContentType;
  80. #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
  81. web_request.Timeout = (int) timeout.TotalMilliseconds;
  82. #endif
  83. // There is no SOAP Action/To header when AddressingVersion is None.
  84. if (message.Version.Addressing == AddressingVersion.None) {
  85. if (message.Headers.Action != null) {
  86. web_request.Headers ["SOAPAction"] = message.Headers.Action;
  87. message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
  88. if (message.Headers.Action != null) throw new Exception (message.Headers.Action);
  89. }
  90. }
  91. // apply HttpRequestMessageProperty if exists.
  92. bool suppressEntityBody = false;
  93. #if !NET_2_1
  94. string pname = HttpRequestMessageProperty.Name;
  95. if (message.Properties.ContainsKey (pname)) {
  96. HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
  97. web_request.Headers.Add (hp.Headers);
  98. web_request.Method = hp.Method;
  99. // FIXME: do we have to handle hp.QueryString ?
  100. if (hp.SuppressEntityBody)
  101. suppressEntityBody = true;
  102. }
  103. #endif
  104. if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
  105. MemoryStream buffer = new MemoryStream ();
  106. Encoder.WriteMessage (message, buffer);
  107. if (buffer.Length > int.MaxValue)
  108. throw new InvalidOperationException ("The argument message is too large.");
  109. #if !NET_2_1
  110. web_request.ContentLength = (int) buffer.Length;
  111. #endif
  112. #if NET_2_1
  113. // We can verify cross domain access policy
  114. // with full set of headers and target URL.
  115. if (!CrossDomainAccessManager.Current.IsAllowed (destination, web_request.Headers.AllKeys))
  116. throw new InvalidOperationException (String.Format ("Cross domain web service access to {0} is not allowed", destination));
  117. #endif
  118. Stream requestStream = web_request.EndGetRequestStream (web_request.BeginGetRequestStream (null, null));
  119. requestStream.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
  120. requestStream.Close ();
  121. }
  122. WebResponse res;
  123. Stream resstr;
  124. try {
  125. res = web_request.EndGetResponse (web_request.BeginGetResponse (null, null));
  126. resstr = res.GetResponseStream ();
  127. } catch (WebException we) {
  128. res = we.Response;
  129. #if NET_2_1 // debug
  130. Console.WriteLine (we);
  131. #endif
  132. try {
  133. // The response might contain SOAP fault. It might not.
  134. resstr = res.GetResponseStream ();
  135. } catch (WebException we2) {
  136. #if NET_2_1 // debug
  137. Console.WriteLine (we2);
  138. #endif
  139. throw we;
  140. }
  141. }
  142. try {
  143. using (var responseStream = resstr) {
  144. MemoryStream ms = new MemoryStream ();
  145. byte [] b = new byte [65536];
  146. int n = 0;
  147. while (true) {
  148. n = responseStream.Read (b, 0, 65536);
  149. if (n == 0)
  150. break;
  151. ms.Write (b, 0, n);
  152. }
  153. ms.Seek (0, SeekOrigin.Begin);
  154. Message ret = Encoder.ReadMessage (
  155. //responseStream, MaxSizeOfHeaders);
  156. ms, MaxSizeOfHeaders, res.ContentType);
  157. /*
  158. MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
  159. ret = buf.CreateMessage ();
  160. System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
  161. w.Formatting = System.Xml.Formatting.Indented;
  162. buf.CreateMessage ().WriteMessage (w);
  163. w.Close ();
  164. */
  165. return ret;
  166. }
  167. } finally {
  168. res.Close ();
  169. }
  170. }
  171. public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
  172. {
  173. ThrowIfDisposedOrNotOpen ();
  174. return new HttpChannelRequestAsyncResult (this, message, timeout, callback, state);
  175. }
  176. public override Message EndRequest (IAsyncResult result)
  177. {
  178. if (result == null)
  179. throw new ArgumentNullException ("result");
  180. HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
  181. if (r == null)
  182. throw new InvalidOperationException ("Wrong IAsyncResult");
  183. r.WaitEnd ();
  184. return r.Response;
  185. }
  186. // Abort
  187. protected override void OnAbort ()
  188. {
  189. throw new NotImplementedException ();
  190. }
  191. // Close
  192. protected override void OnClose (TimeSpan timeout)
  193. {
  194. if (web_request != null)
  195. web_request.Abort ();
  196. web_request = null;
  197. }
  198. protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
  199. {
  200. throw new NotImplementedException ();
  201. }
  202. protected override void OnEndClose (IAsyncResult result)
  203. {
  204. throw new NotImplementedException ();
  205. }
  206. // Open
  207. protected override void OnOpen (TimeSpan timeout)
  208. {
  209. }
  210. protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
  211. {
  212. throw new NotImplementedException ();
  213. }
  214. protected override void OnEndOpen (IAsyncResult result)
  215. {
  216. throw new NotImplementedException ();
  217. }
  218. class HttpChannelRequestAsyncResult : IAsyncResult
  219. {
  220. HttpRequestChannel channel;
  221. Message message;
  222. TimeSpan timeout;
  223. AsyncCallback callback;
  224. object state;
  225. AutoResetEvent wait;
  226. bool done, waiting;
  227. Message response;
  228. Exception error;
  229. public HttpChannelRequestAsyncResult (HttpRequestChannel channel, Message message, TimeSpan timeout, AsyncCallback callback, object state)
  230. {
  231. this.channel = channel;
  232. this.message = message;
  233. this.timeout = timeout;
  234. this.callback = callback;
  235. this.state = state;
  236. wait = new AutoResetEvent (false);
  237. Thread t = new Thread (delegate () {
  238. try {
  239. response = channel.ProcessRequest (message, timeout);
  240. if (callback != null)
  241. callback (this);
  242. } catch (Exception ex) {
  243. error = ex;
  244. } finally {
  245. done = true;
  246. wait.Set ();
  247. }
  248. });
  249. t.Start ();
  250. }
  251. public Message Response {
  252. get { return response; }
  253. }
  254. public WaitHandle AsyncWaitHandle {
  255. get { return wait; }
  256. }
  257. public object AsyncState {
  258. get { return state; }
  259. }
  260. public bool CompletedSynchronously {
  261. get { return done && !waiting; }
  262. }
  263. public bool IsCompleted {
  264. get { return done; }
  265. }
  266. public void WaitEnd ()
  267. {
  268. if (!done) {
  269. waiting = true;
  270. wait.WaitOne (timeout, true);
  271. }
  272. if (error != null)
  273. throw error;
  274. }
  275. }
  276. }
  277. }