HttpReplyChannel.cs 7.7 KB

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