5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2010 Novell, Inc. http://www.novell.com
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:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
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.
29 using System.Collections.Generic;
30 using System.Collections.Specialized;
31 using System.IdentityModel.Selectors;
32 using System.IdentityModel.Tokens;
35 using System.ServiceModel;
36 using System.ServiceModel.Security;
38 using System.Threading;
40 namespace System.ServiceModel.Channels.Http
42 internal class HttpReplyChannel : InternalReplyChannelBase
44 HttpChannelListener<IReplyChannel> source;
45 RequestContext reqctx;
46 SecurityTokenAuthenticator security_token_authenticator;
47 SecurityTokenResolver security_token_resolver;
49 public HttpReplyChannel (HttpChannelListener<IReplyChannel> listener)
52 this.source = listener;
54 if (listener.SecurityTokenManager != null) {
55 var str = new SecurityTokenRequirement () { TokenType = SecurityTokenTypes.UserName };
56 security_token_authenticator = listener.SecurityTokenManager.CreateSecurityTokenAuthenticator (str, out security_token_resolver);
60 public MessageEncoder Encoder {
61 get { return source.MessageEncoder; }
64 internal MessageVersion MessageVersion {
65 get { return source.MessageEncoder.MessageVersion; }
68 public override RequestContext ReceiveRequest (TimeSpan timeout)
71 if (!TryReceiveRequest (timeout, out ctx))
72 throw new TimeoutException ();
76 protected override void OnOpen (TimeSpan timeout)
80 protected override void OnAbort ()
82 AbortConnections (TimeSpan.Zero);
83 base.OnAbort (); // FIXME: remove it. The base is wrong. But it is somehow required to not block some tests.
86 public override bool CancelAsync (TimeSpan timeout)
88 AbortConnections (timeout);
89 // FIXME: this wait is sort of hack (because it should not be required), but without it some tests are blocked.
90 // This hack even had better be moved to base.CancelAsync().
91 if (CurrentAsyncResult != null)
92 CurrentAsyncResult.AsyncWaitHandle.WaitOne (TimeSpan.FromMilliseconds (300));
93 return base.CancelAsync (timeout);
96 void AbortConnections (TimeSpan timeout)
99 reqctx.Close (timeout);
104 protected override void OnClose (TimeSpan timeout)
108 close_started = true;
109 DateTime start = DateTime.Now;
111 // FIXME: consider timeout
112 AbortConnections (timeout - (DateTime.Now - start));
114 base.OnClose (timeout - (DateTime.Now - start));
117 protected string GetHeaderItem (string raw)
119 if (raw == null || raw.Length == 0)
124 if (raw [raw.Length - 1] == raw [0])
125 return raw.Substring (1, raw.Length - 2);
126 // FIXME: is it simply an error?
132 protected HttpRequestMessageProperty CreateRequestProperty (HttpContextInfo ctxi)
134 var query = ctxi.Request.Url.Query;
135 var prop = new HttpRequestMessageProperty ();
136 prop.Method = ctxi.Request.HttpMethod;
137 prop.QueryString = query.StartsWith ("?") ? query.Substring (1) : query;
138 // FIXME: prop.SuppressEntityBody
139 prop.Headers.Add (ctxi.Request.Headers);
143 public override bool TryReceiveRequest (TimeSpan timeout, out RequestContext context)
146 HttpContextInfo ctxi;
147 if (!source.ListenerManager.TryDequeueRequest (source.ChannelDispatcher, timeout, out ctxi))
150 return true; // returning true, yet context is null. This happens at closing phase.
152 if (source.Source.AuthenticationScheme != AuthenticationSchemes.Anonymous) {
153 if (security_token_authenticator != null)
154 // FIXME: use return value?
156 security_token_authenticator.ValidateToken (new UserNameSecurityToken (ctxi.User, ctxi.Password));
157 } catch (Exception) {
158 ctxi.ReturnUnauthorized ();
161 ctxi.ReturnUnauthorized ();
167 if (ctxi.Request.HttpMethod == "POST") {
168 msg = CreatePostMessage (ctxi);
171 } else if (ctxi.Request.HttpMethod == "GET")
172 msg = Message.CreateMessage (MessageVersion.None, null); // HTTP GET-based request
174 if (msg.Headers.To == null)
175 msg.Headers.To = ctxi.Request.Url;
176 msg.Properties.Add ("Via", LocalAddress.Uri);
177 msg.Properties.Add (HttpRequestMessageProperty.Name, CreateRequestProperty (ctxi));
179 Logger.LogMessage (MessageLogSourceKind.TransportReceive, ref msg, 0x10000); // FIXME: pass maxMessageSize.
181 context = new HttpRequestContext (this, ctxi, msg);
186 protected Message CreatePostMessage (HttpContextInfo ctxi)
188 if (ctxi.Response.StatusCode != 200) { // it's already invalid.
193 if (!Encoder.IsContentTypeSupported (ctxi.Request.ContentType)) {
194 ctxi.Response.StatusCode = (int) HttpStatusCode.UnsupportedMediaType;
195 ctxi.Response.StatusDescription = String.Format (
196 "Expected content-type '{0}' but got '{1}'", Encoder.ContentType, ctxi.Request.ContentType);
202 // FIXME: supply maxSizeOfHeaders.
203 int maxSizeOfHeaders = 0x10000;
205 #if false // FIXME: enable it, once duplex callback test gets passed.
206 Stream stream = ctxi.Request.InputStream;
207 if (source.Source.TransferMode == TransferMode.Buffered) {
208 if (ctxi.Request.ContentLength64 <= 0)
209 throw new ArgumentException ("This HTTP channel is configured to use buffered mode, and thus expects Content-Length sent to the listener");
211 var ms = new MemoryStream ();
212 var buf = new byte [0x1000];
213 while (size < ctxi.Request.ContentLength64) {
214 if ((size += stream.Read (buf, 0, 0x1000)) > source.Source.MaxBufferSize)
215 throw new QuotaExceededException ("Message quota exceeded");
216 ms.Write (buf, 0, (int) (size - ms.Length));
222 var msg = Encoder.ReadMessage (
223 stream, maxSizeOfHeaders, ctxi.Request.ContentType);
225 var msg = Encoder.ReadMessage (
226 ctxi.Request.InputStream, maxSizeOfHeaders, ctxi.Request.ContentType);
229 if (MessageVersion.Envelope.Equals (EnvelopeVersion.Soap11) ||
230 MessageVersion.Addressing.Equals (AddressingVersion.None)) {
231 string action = GetHeaderItem (ctxi.Request.Headers ["SOAPAction"]);
232 if (action != null) {
233 if (action.Length > 2 && action [0] == '"' && action [action.Length] == '"')
234 action = action.Substring (1, action.Length - 2);
235 msg.Headers.Action = action;
242 public override bool WaitForRequest (TimeSpan timeout)
244 throw new NotImplementedException ();