HttpRequestChannel.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. object state = new object ();
  119. Stream requestStream = web_request.EndGetRequestStream (web_request.BeginGetRequestStream (delegate (IAsyncResult result) {
  120. if (result.AsyncState != state)
  121. throw new InvalidOperationException ("The argument async result has wrong state");
  122. }, state));
  123. requestStream.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
  124. requestStream.Close ();
  125. }
  126. WebResponse res;
  127. Stream resstr;
  128. try {
  129. object state = new object ();
  130. res = web_request.EndGetResponse (web_request.BeginGetResponse (delegate (IAsyncResult result) {
  131. if (result.AsyncState != state)
  132. throw new InvalidOperationException ("The argument async result has wrong state");
  133. }, state));
  134. resstr = res.GetResponseStream ();
  135. } catch (WebException we) {
  136. res = we.Response;
  137. #if NET_2_1 // debug
  138. Console.WriteLine (we);
  139. #endif
  140. try {
  141. // The response might contain SOAP fault. It might not.
  142. resstr = res.GetResponseStream ();
  143. } catch (WebException we2) {
  144. #if NET_2_1 // debug
  145. Console.WriteLine (we2);
  146. #endif
  147. throw we;
  148. }
  149. }
  150. try {
  151. using (var responseStream = resstr) {
  152. MemoryStream ms = new MemoryStream ();
  153. byte [] b = new byte [65536];
  154. int n = 0;
  155. while (true) {
  156. n = responseStream.Read (b, 0, 65536);
  157. if (n == 0)
  158. break;
  159. ms.Write (b, 0, n);
  160. }
  161. ms.Seek (0, SeekOrigin.Begin);
  162. Message ret = Encoder.ReadMessage (
  163. //responseStream, MaxSizeOfHeaders);
  164. ms, MaxSizeOfHeaders, res.ContentType);
  165. /*
  166. MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
  167. ret = buf.CreateMessage ();
  168. System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
  169. w.Formatting = System.Xml.Formatting.Indented;
  170. buf.CreateMessage ().WriteMessage (w);
  171. w.Close ();
  172. */
  173. return ret;
  174. }
  175. } finally {
  176. res.Close ();
  177. }
  178. }
  179. public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
  180. {
  181. ThrowIfDisposedOrNotOpen ();
  182. return new HttpChannelRequestAsyncResult (this, message, timeout, callback, state);
  183. }
  184. public override Message EndRequest (IAsyncResult result)
  185. {
  186. if (result == null)
  187. throw new ArgumentNullException ("result");
  188. HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
  189. if (r == null)
  190. throw new InvalidOperationException ("Wrong IAsyncResult");
  191. r.WaitEnd ();
  192. return r.Response;
  193. }
  194. // Abort
  195. protected override void OnAbort ()
  196. {
  197. throw new NotImplementedException ();
  198. }
  199. // Close
  200. protected override void OnClose (TimeSpan timeout)
  201. {
  202. if (web_request != null)
  203. web_request.Abort ();
  204. web_request = null;
  205. }
  206. protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
  207. {
  208. throw new NotImplementedException ();
  209. }
  210. protected override void OnEndClose (IAsyncResult result)
  211. {
  212. throw new NotImplementedException ();
  213. }
  214. // Open
  215. protected override void OnOpen (TimeSpan timeout)
  216. {
  217. }
  218. protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
  219. {
  220. throw new NotImplementedException ();
  221. }
  222. protected override void OnEndOpen (IAsyncResult result)
  223. {
  224. throw new NotImplementedException ();
  225. }
  226. class HttpChannelRequestAsyncResult : IAsyncResult
  227. {
  228. HttpRequestChannel channel;
  229. Message message;
  230. TimeSpan timeout;
  231. AsyncCallback callback;
  232. object state;
  233. AutoResetEvent wait;
  234. bool done, waiting;
  235. Message response;
  236. Exception error;
  237. public HttpChannelRequestAsyncResult (HttpRequestChannel channel, Message message, TimeSpan timeout, AsyncCallback callback, object state)
  238. {
  239. this.channel = channel;
  240. this.message = message;
  241. this.timeout = timeout;
  242. this.callback = callback;
  243. this.state = state;
  244. wait = new AutoResetEvent (false);
  245. Thread t = new Thread (delegate () {
  246. try {
  247. response = channel.ProcessRequest (message, timeout);
  248. if (callback != null)
  249. callback (this);
  250. } catch (Exception ex) {
  251. error = ex;
  252. } finally {
  253. done = true;
  254. wait.Set ();
  255. }
  256. });
  257. t.Start ();
  258. }
  259. public Message Response {
  260. get { return response; }
  261. }
  262. public WaitHandle AsyncWaitHandle {
  263. get { return wait; }
  264. }
  265. public object AsyncState {
  266. get { return state; }
  267. }
  268. public bool CompletedSynchronously {
  269. get { return done && !waiting; }
  270. }
  271. public bool IsCompleted {
  272. get { return done; }
  273. }
  274. public void WaitEnd ()
  275. {
  276. if (!done) {
  277. waiting = true;
  278. wait.WaitOne (timeout, true);
  279. }
  280. if (error != null)
  281. throw error;
  282. }
  283. }
  284. }
  285. }