HttpRequestChannel.cs 8.0 KB

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