HttpReplyChannel.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. object close_lock = new object ();
  96. protected override void OnClose (TimeSpan timeout)
  97. {
  98. lock (close_lock) {
  99. if (close_started)
  100. return;
  101. close_started = true;
  102. }
  103. DateTime start = DateTime.Now;
  104. // FIXME: consider timeout
  105. AbortConnections (timeout - (DateTime.Now - start));
  106. base.OnClose (timeout - (DateTime.Now - start));
  107. }
  108. protected string GetHeaderItem (string raw)
  109. {
  110. if (raw == null || raw.Length == 0)
  111. return raw;
  112. switch (raw [0]) {
  113. case '\'':
  114. case '"':
  115. if (raw [raw.Length - 1] == raw [0])
  116. return raw.Substring (1, raw.Length - 2);
  117. // FIXME: is it simply an error?
  118. break;
  119. }
  120. return raw;
  121. }
  122. protected HttpRequestMessageProperty CreateRequestProperty (HttpContextInfo ctxi)
  123. {
  124. var query = ctxi.Request.Url.Query;
  125. var prop = new HttpRequestMessageProperty ();
  126. prop.Method = ctxi.Request.HttpMethod;
  127. prop.QueryString = query.StartsWith ("?") ? query.Substring (1) : query;
  128. // FIXME: prop.SuppressEntityBody
  129. prop.Headers.Add (ctxi.Request.Headers);
  130. return prop;
  131. }
  132. public override bool TryReceiveRequest (TimeSpan timeout, out RequestContext context)
  133. {
  134. context = null;
  135. HttpContextInfo ctxi;
  136. if (!source.ListenerManager.TryDequeueRequest (source.ChannelDispatcher, timeout, out ctxi))
  137. return false;
  138. if (ctxi == null)
  139. return true; // returning true, yet context is null. This happens at closing phase.
  140. if (source.Source.AuthenticationScheme != AuthenticationSchemes.Anonymous) {
  141. if (security_token_authenticator != null)
  142. // FIXME: use return value?
  143. try {
  144. security_token_authenticator.ValidateToken (new UserNameSecurityToken (ctxi.User, ctxi.Password));
  145. } catch (Exception) {
  146. ctxi.ReturnUnauthorized ();
  147. }
  148. else {
  149. ctxi.ReturnUnauthorized ();
  150. }
  151. }
  152. Message msg = null;
  153. if (ctxi.Request.HttpMethod == "POST")
  154. msg = CreatePostMessage (ctxi);
  155. else if (ctxi.Request.HttpMethod == "GET")
  156. msg = Message.CreateMessage (MessageVersion.None, null); // HTTP GET-based request
  157. if (msg == null)
  158. return false;
  159. if (msg.Headers.To == null)
  160. msg.Headers.To = ctxi.Request.Url;
  161. msg.Properties.Add ("Via", LocalAddress.Uri);
  162. msg.Properties.Add (HttpRequestMessageProperty.Name, CreateRequestProperty (ctxi));
  163. Logger.LogMessage (MessageLogSourceKind.TransportReceive, ref msg, source.Source.MaxReceivedMessageSize);
  164. context = new HttpRequestContext (this, ctxi, msg);
  165. reqctx = context;
  166. return true;
  167. }
  168. protected Message CreatePostMessage (HttpContextInfo ctxi)
  169. {
  170. if (ctxi.Response.StatusCode != 200) { // it's already invalid.
  171. ctxi.Close ();
  172. return null;
  173. }
  174. if (!Encoder.IsContentTypeSupported (ctxi.Request.ContentType)) {
  175. ctxi.Response.StatusCode = (int) HttpStatusCode.UnsupportedMediaType;
  176. ctxi.Response.StatusDescription = String.Format (
  177. "Expected content-type '{0}' but got '{1}'", Encoder.ContentType, ctxi.Request.ContentType);
  178. ctxi.Close ();
  179. return null;
  180. }
  181. // FIXME: supply maxSizeOfHeaders.
  182. int maxSizeOfHeaders = 0x10000;
  183. #if false // FIXME: enable it, once duplex callback test gets passed.
  184. Stream stream = ctxi.Request.InputStream;
  185. if (source.Source.TransferMode == TransferMode.Buffered) {
  186. if (ctxi.Request.ContentLength64 <= 0)
  187. throw new ArgumentException ("This HTTP channel is configured to use buffered mode, and thus expects Content-Length sent to the listener");
  188. long size = 0;
  189. var ms = new MemoryStream ();
  190. var buf = new byte [0x1000];
  191. while (size < ctxi.Request.ContentLength64) {
  192. if ((size += stream.Read (buf, 0, 0x1000)) > source.Source.MaxBufferSize)
  193. throw new QuotaExceededException ("Message quota exceeded");
  194. ms.Write (buf, 0, (int) (size - ms.Length));
  195. }
  196. ms.Position = 0;
  197. stream = ms;
  198. }
  199. var msg = Encoder.ReadMessage (
  200. stream, maxSizeOfHeaders, ctxi.Request.ContentType);
  201. #else
  202. var msg = Encoder.ReadMessage (
  203. ctxi.Request.InputStream, maxSizeOfHeaders, ctxi.Request.ContentType);
  204. #endif
  205. if (MessageVersion.Envelope.Equals (EnvelopeVersion.Soap11) ||
  206. MessageVersion.Addressing.Equals (AddressingVersion.None)) {
  207. string action = GetHeaderItem (ctxi.Request.Headers ["SOAPAction"]);
  208. if (action != null) {
  209. if (action.Length > 2 && action [0] == '"' && action [action.Length] == '"')
  210. action = action.Substring (1, action.Length - 2);
  211. msg.Headers.Action = action;
  212. }
  213. }
  214. msg.Properties.Add (RemoteEndpointMessageProperty.Name, new RemoteEndpointMessageProperty (ctxi.Request.ClientIPAddress, ctxi.Request.ClientPort));
  215. return msg;
  216. }
  217. public override bool WaitForRequest (TimeSpan timeout)
  218. {
  219. throw new NotImplementedException ();
  220. }
  221. }
  222. }