HttpRequestChannel.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. web_request.Timeout = (int) timeout.TotalMilliseconds;
  81. // There is no SOAP Action/To header when AddressingVersion is None.
  82. if (message.Version.Addressing == AddressingVersion.None) {
  83. if (message.Headers.Action != null) {
  84. web_request.Headers ["SOAPAction"] = message.Headers.Action;
  85. message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
  86. if (message.Headers.Action != null) throw new Exception (message.Headers.Action);
  87. }
  88. }
  89. // apply HttpRequestMessageProperty if exists.
  90. bool suppressEntityBody = false;
  91. string pname = HttpRequestMessageProperty.Name;
  92. if (message.Properties.ContainsKey (pname)) {
  93. HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
  94. web_request.Headers.Add (hp.Headers);
  95. web_request.Method = hp.Method;
  96. // FIXME: do we have to handle hp.QueryString ?
  97. if (hp.SuppressEntityBody)
  98. suppressEntityBody = true;
  99. }
  100. if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
  101. MemoryStream buffer = new MemoryStream ();
  102. Encoder.WriteMessage (message, buffer);
  103. if (buffer.Length > int.MaxValue)
  104. throw new InvalidOperationException ("The argument message is too large.");
  105. web_request.ContentLength = (int) buffer.Length;
  106. Stream requestStream = web_request.GetRequestStream ();
  107. requestStream.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
  108. requestStream.Close ();
  109. }
  110. WebResponse res;
  111. try {
  112. res = web_request.GetResponse ();
  113. }
  114. catch (WebException we) {
  115. res = we.Response;
  116. }
  117. try {
  118. using (Stream responseStream = res.GetResponseStream ()) {
  119. MemoryStream ms = new MemoryStream ();
  120. byte [] b = new byte [65536];
  121. int n = 0;
  122. while (true) {
  123. n = responseStream.Read (b, 0, 65536);
  124. if (n == 0)
  125. break;
  126. ms.Write (b, 0, n);
  127. }
  128. ms.Seek (0, SeekOrigin.Begin);
  129. Message ret = Encoder.ReadMessage (
  130. //responseStream, MaxSizeOfHeaders);
  131. ms, MaxSizeOfHeaders, res.ContentType);
  132. /*
  133. MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
  134. ret = buf.CreateMessage ();
  135. System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
  136. w.Formatting = System.Xml.Formatting.Indented;
  137. buf.CreateMessage ().WriteMessage (w);
  138. w.Close ();
  139. */
  140. return ret;
  141. }
  142. } finally {
  143. res.Close ();
  144. }
  145. }
  146. public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
  147. {
  148. ThrowIfDisposedOrNotOpen ();
  149. return new HttpChannelRequestAsyncResult (this, message, timeout, callback, state);
  150. }
  151. public override Message EndRequest (IAsyncResult result)
  152. {
  153. if (result == null)
  154. throw new ArgumentNullException ("result");
  155. HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
  156. if (r == null)
  157. throw new InvalidOperationException ("Wrong IAsyncResult");
  158. r.WaitEnd ();
  159. return r.Response;
  160. }
  161. // Abort
  162. protected override void OnAbort ()
  163. {
  164. throw new NotImplementedException ();
  165. }
  166. // Close
  167. protected override void OnClose (TimeSpan timeout)
  168. {
  169. if (web_request != null)
  170. web_request.Abort ();
  171. web_request = null;
  172. }
  173. protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
  174. {
  175. throw new NotImplementedException ();
  176. }
  177. protected override void OnEndClose (IAsyncResult result)
  178. {
  179. throw new NotImplementedException ();
  180. }
  181. // Open
  182. protected override void OnOpen (TimeSpan timeout)
  183. {
  184. }
  185. protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
  186. {
  187. throw new NotImplementedException ();
  188. }
  189. protected override void OnEndOpen (IAsyncResult result)
  190. {
  191. throw new NotImplementedException ();
  192. }
  193. class HttpChannelRequestAsyncResult : IAsyncResult
  194. {
  195. HttpRequestChannel channel;
  196. Message message;
  197. TimeSpan timeout;
  198. AsyncCallback callback;
  199. object state;
  200. AutoResetEvent wait;
  201. bool done, waiting;
  202. Message response;
  203. Exception error;
  204. public HttpChannelRequestAsyncResult (HttpRequestChannel channel, Message message, TimeSpan timeout, AsyncCallback callback, object state)
  205. {
  206. this.channel = channel;
  207. this.message = message;
  208. this.timeout = timeout;
  209. this.callback = callback;
  210. this.state = state;
  211. wait = new AutoResetEvent (false);
  212. Thread t = new Thread (delegate () {
  213. try {
  214. response = channel.ProcessRequest (message, timeout);
  215. if (callback != null)
  216. callback (this);
  217. } catch (Exception ex) {
  218. error = ex;
  219. } finally {
  220. done = true;
  221. wait.Set ();
  222. }
  223. });
  224. t.Start ();
  225. }
  226. public Message Response {
  227. get { return response; }
  228. }
  229. public WaitHandle AsyncWaitHandle {
  230. get { return wait; }
  231. }
  232. public object AsyncState {
  233. get { return state; }
  234. }
  235. public bool CompletedSynchronously {
  236. get { return done && !waiting; }
  237. }
  238. public bool IsCompleted {
  239. get { return done; }
  240. }
  241. public void WaitEnd ()
  242. {
  243. if (!done) {
  244. waiting = true;
  245. wait.WaitOne (timeout, true);
  246. }
  247. if (error != null)
  248. throw error;
  249. }
  250. }
  251. }
  252. }