HttpReplyChannel.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. //
  2. // HttpReplyChannel.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2010 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.Collections.Specialized;
  31. using System.IdentityModel.Selectors;
  32. using System.IdentityModel.Tokens;
  33. using System.IO;
  34. using System.Net;
  35. using System.ServiceModel;
  36. using System.ServiceModel.Security;
  37. using System.Text;
  38. using System.Threading;
  39. namespace System.ServiceModel.Channels.Http
  40. {
  41. internal class HttpReplyChannel : InternalReplyChannelBase
  42. {
  43. HttpChannelListener<IReplyChannel> source;
  44. RequestContext reqctx;
  45. SecurityTokenAuthenticator security_token_authenticator;
  46. SecurityTokenResolver security_token_resolver;
  47. public HttpReplyChannel (HttpChannelListener<IReplyChannel> listener)
  48. : base (listener)
  49. {
  50. this.source = listener;
  51. if (listener.SecurityTokenManager != null) {
  52. var str = new SecurityTokenRequirement () { TokenType = SecurityTokenTypes.UserName };
  53. security_token_authenticator = listener.SecurityTokenManager.CreateSecurityTokenAuthenticator (str, out security_token_resolver);
  54. }
  55. }
  56. internal HttpChannelListener<IReplyChannel> Source {
  57. get { return source; }
  58. }
  59. public MessageEncoder Encoder {
  60. get { return source.MessageEncoder; }
  61. }
  62. internal MessageVersion MessageVersion {
  63. get { return source.MessageEncoder.MessageVersion; }
  64. }
  65. public override RequestContext ReceiveRequest (TimeSpan timeout)
  66. {
  67. RequestContext ctx;
  68. if (!TryReceiveRequest (timeout, out ctx))
  69. throw new TimeoutException ();
  70. return ctx;
  71. }
  72. protected override void OnOpen (TimeSpan timeout)
  73. {
  74. }
  75. protected override void OnAbort ()
  76. {
  77. AbortConnections (TimeSpan.Zero);
  78. base.OnAbort (); // FIXME: remove it. The base is wrong. But it is somehow required to not block some tests.
  79. }
  80. public override bool CancelAsync (TimeSpan timeout)
  81. {
  82. AbortConnections (timeout);
  83. // FIXME: this wait is sort of hack (because it should not be required), but without it some tests are blocked.
  84. // This hack even had better be moved to base.CancelAsync().
  85. if (CurrentAsyncResult != null)
  86. CurrentAsyncResult.AsyncWaitHandle.WaitOne (TimeSpan.FromMilliseconds (300));
  87. return base.CancelAsync (timeout);
  88. }
  89. void AbortConnections (TimeSpan timeout)
  90. {
  91. if (reqctx != null)
  92. reqctx.Close (timeout);
  93. }
  94. bool close_started;
  95. protected override void OnClose (TimeSpan timeout)
  96. {
  97. if (close_started)
  98. return;
  99. close_started = true;
  100. DateTime start = DateTime.Now;
  101. // FIXME: consider timeout
  102. AbortConnections (timeout - (DateTime.Now - start));
  103. base.OnClose (timeout - (DateTime.Now - start));
  104. }
  105. protected string GetHeaderItem (string raw)
  106. {
  107. if (raw == null || raw.Length == 0)
  108. return raw;
  109. switch (raw [0]) {
  110. case '\'':
  111. case '"':
  112. if (raw [raw.Length - 1] == raw [0])
  113. return raw.Substring (1, raw.Length - 2);
  114. // FIXME: is it simply an error?
  115. break;
  116. }
  117. return raw;
  118. }
  119. protected HttpRequestMessageProperty CreateRequestProperty (HttpContextInfo ctxi)
  120. {
  121. var query = ctxi.Request.Url.Query;
  122. var prop = new HttpRequestMessageProperty ();
  123. prop.Method = ctxi.Request.HttpMethod;
  124. prop.QueryString = query.StartsWith ("?") ? query.Substring (1) : query;
  125. // FIXME: prop.SuppressEntityBody
  126. prop.Headers.Add (ctxi.Request.Headers);
  127. return prop;
  128. }
  129. public override bool TryReceiveRequest (TimeSpan timeout, out RequestContext context)
  130. {
  131. context = null;
  132. HttpContextInfo ctxi;
  133. if (!source.ListenerManager.TryDequeueRequest (source.ChannelDispatcher, timeout, out ctxi))
  134. return false;
  135. if (ctxi == null)
  136. return true; // returning true, yet context is null. This happens at closing phase.
  137. if (source.Source.AuthenticationScheme != AuthenticationSchemes.Anonymous) {
  138. if (security_token_authenticator != null)
  139. // FIXME: use return value?
  140. try {
  141. security_token_authenticator.ValidateToken (new UserNameSecurityToken (ctxi.User, ctxi.Password));
  142. } catch (Exception) {
  143. ctxi.ReturnUnauthorized ();
  144. }
  145. else {
  146. ctxi.ReturnUnauthorized ();
  147. }
  148. }
  149. Message msg = null;
  150. if (ctxi.Request.HttpMethod == "POST")
  151. msg = CreatePostMessage (ctxi);
  152. else if (ctxi.Request.HttpMethod == "GET")
  153. msg = Message.CreateMessage (MessageVersion.None, null); // HTTP GET-based request
  154. if (msg == null)
  155. return false;
  156. if (msg.Headers.To == null)
  157. msg.Headers.To = ctxi.Request.Url;
  158. msg.Properties.Add ("Via", LocalAddress.Uri);
  159. msg.Properties.Add (HttpRequestMessageProperty.Name, CreateRequestProperty (ctxi));
  160. Logger.LogMessage (MessageLogSourceKind.TransportReceive, ref msg, source.Source.MaxReceivedMessageSize);
  161. context = new HttpRequestContext (this, ctxi, msg);
  162. reqctx = context;
  163. return true;
  164. }
  165. protected Message CreatePostMessage (HttpContextInfo ctxi)
  166. {
  167. if (ctxi.Response.StatusCode != 200) { // it's already invalid.
  168. ctxi.Close ();
  169. return null;
  170. }
  171. if (!Encoder.IsContentTypeSupported (ctxi.Request.ContentType)) {
  172. ctxi.Response.StatusCode = (int) HttpStatusCode.UnsupportedMediaType;
  173. ctxi.Response.StatusDescription = String.Format (
  174. "Expected content-type '{0}' but got '{1}'", Encoder.ContentType, ctxi.Request.ContentType);
  175. ctxi.Close ();
  176. return null;
  177. }
  178. // FIXME: supply maxSizeOfHeaders.
  179. int maxSizeOfHeaders = 0x10000;
  180. #if false // FIXME: enable it, once duplex callback test gets passed.
  181. Stream stream = ctxi.Request.InputStream;
  182. if (source.Source.TransferMode == TransferMode.Buffered) {
  183. if (ctxi.Request.ContentLength64 <= 0)
  184. throw new ArgumentException ("This HTTP channel is configured to use buffered mode, and thus expects Content-Length sent to the listener");
  185. long size = 0;
  186. var ms = new MemoryStream ();
  187. var buf = new byte [0x1000];
  188. while (size < ctxi.Request.ContentLength64) {
  189. if ((size += stream.Read (buf, 0, 0x1000)) > source.Source.MaxBufferSize)
  190. throw new QuotaExceededException ("Message quota exceeded");
  191. ms.Write (buf, 0, (int) (size - ms.Length));
  192. }
  193. ms.Position = 0;
  194. stream = ms;
  195. }
  196. var msg = Encoder.ReadMessage (
  197. stream, maxSizeOfHeaders, ctxi.Request.ContentType);
  198. #else
  199. var msg = Encoder.ReadMessage (
  200. ctxi.Request.InputStream, maxSizeOfHeaders, ctxi.Request.ContentType);
  201. #endif
  202. if (MessageVersion.Envelope.Equals (EnvelopeVersion.Soap11) ||
  203. MessageVersion.Addressing.Equals (AddressingVersion.None)) {
  204. string action = GetHeaderItem (ctxi.Request.Headers ["SOAPAction"]);
  205. if (action != null) {
  206. if (action.Length > 2 && action [0] == '"' && action [action.Length] == '"')
  207. action = action.Substring (1, action.Length - 2);
  208. msg.Headers.Action = action;
  209. }
  210. }
  211. msg.Properties.Add (RemoteEndpointMessageProperty.Name, new RemoteEndpointMessageProperty (ctxi.Request.ClientIPAddress, ctxi.Request.ClientPort));
  212. return msg;
  213. }
  214. public override bool WaitForRequest (TimeSpan timeout)
  215. {
  216. throw new NotImplementedException ();
  217. }
  218. }
  219. }