2 // HttpRequestChannel.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2006 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;
32 using System.Net.Security;
33 using System.ServiceModel;
34 using System.ServiceModel.Description;
35 using System.ServiceModel.Security;
36 using System.Threading;
38 namespace System.ServiceModel.Channels
40 internal class HttpRequestChannel : RequestChannelBase
42 HttpChannelFactory<IRequestChannel> source;
44 WebRequest web_request;
48 public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
49 EndpointAddress address, Uri via)
50 : base (factory, address, via)
52 this.source = factory;
55 public MessageEncoder Encoder {
56 get { return source.MessageEncoder; }
61 public override Message Request (Message message, TimeSpan timeout)
63 return EndRequest (BeginRequest (message, timeout, null, null));
66 void BeginProcessRequest (HttpChannelRequestAsyncResult result)
68 Message message = result.Message;
69 TimeSpan timeout = result.Timeout;
70 // FIXME: is distination really like this?
71 Uri destination = message.Headers.To;
72 if (destination == null) {
73 if (source.Transport.ManualAddressing)
74 throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address.");
76 destination = Via ?? RemoteAddress.Uri;
79 web_request = HttpWebRequest.Create (destination);
80 web_request.Method = "POST";
81 web_request.ContentType = Encoder.ContentType;
84 var cmgr = source.GetProperty<IHttpCookieContainerManager> ();
86 ((HttpWebRequest) web_request).CookieContainer = cmgr.CookieContainer;
89 #if !MOONLIGHT // until we support NetworkCredential like SL4 will do.
90 // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
91 var httpbe = (HttpTransportBindingElement) source.Transport;
92 string authType = null;
93 switch (httpbe.AuthenticationScheme) {
94 // AuthenticationSchemes.Anonymous is the default, ignored.
95 case AuthenticationSchemes.Basic:
98 case AuthenticationSchemes.Digest:
101 case AuthenticationSchemes.Ntlm:
104 case AuthenticationSchemes.Negotiate:
105 authType = "Negotiate";
108 if (authType != null) {
109 var cred = source.ClientCredentials;
110 string user = cred != null ? cred.UserName.UserName : null;
111 string pwd = cred != null ? cred.UserName.Password : null;
112 if (String.IsNullOrEmpty (user))
113 throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
114 var nc = new NetworkCredential (user, pwd);
115 web_request.Credentials = nc;
116 // FIXME: it is said required in SL4, but it blocks full WCF.
117 //web_request.UseDefaultCredentials = false;
121 #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
122 web_request.Timeout = (int) timeout.TotalMilliseconds;
125 // There is no SOAP Action/To header when AddressingVersion is None.
126 if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
127 message.Version.Addressing.Equals (AddressingVersion.None)) {
128 if (message.Headers.Action != null) {
129 web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
130 message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
134 // apply HttpRequestMessageProperty if exists.
135 bool suppressEntityBody = false;
137 string pname = HttpRequestMessageProperty.Name;
138 if (message.Properties.ContainsKey (pname)) {
139 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
140 web_request.Headers.Clear ();
141 web_request.Headers.Add (hp.Headers);
142 web_request.Method = hp.Method;
143 // FIXME: do we have to handle hp.QueryString ?
144 if (hp.SuppressEntityBody)
145 suppressEntityBody = true;
149 if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
150 MemoryStream buffer = new MemoryStream ();
151 Encoder.WriteMessage (message, buffer);
153 if (buffer.Length > int.MaxValue)
154 throw new InvalidOperationException ("The argument message is too large.");
157 web_request.ContentLength = (int) buffer.Length;
160 web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
162 result.CompletedSynchronously &= r.CompletedSynchronously;
163 using (Stream s = web_request.EndGetRequestStream (r))
164 s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
165 web_request.BeginGetResponse (GotResponse, result);
166 } catch (Exception ex) {
167 result.Complete (ex);
171 web_request.BeginGetResponse (GotResponse, result);
175 void GotResponse (IAsyncResult result)
177 HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
178 channelResult.CompletedSynchronously &= result.CompletedSynchronously;
183 res = web_request.EndGetResponse (result);
184 resstr = res.GetResponseStream ();
185 } catch (WebException we) {
188 channelResult.Complete (we);
192 // The response might contain SOAP fault. It might not.
193 resstr = res.GetResponseStream ();
194 } catch (WebException we2) {
195 channelResult.Complete (we2);
200 var hrr = (HttpWebResponse) res;
201 if ((int) hrr.StatusCode >= 400 && (int) hrr.StatusCode < 500) {
202 channelResult.Complete (new WebException (String.Format ("There was an error on processing web request: Status code {0}({1}): {2}", (int) hrr.StatusCode, hrr.StatusCode, hrr.StatusDescription)));
208 // TODO: unit test to make sure an empty response never throws
209 // an exception at this level
210 if (hrr.ContentLength == 0) {
211 ret = Message.CreateMessage (MessageVersion.Default, String.Empty);
214 using (var responseStream = resstr) {
215 MemoryStream ms = new MemoryStream ();
216 byte [] b = new byte [65536];
220 n = responseStream.Read (b, 0, 65536);
225 ms.Seek (0, SeekOrigin.Begin);
227 ret = Encoder.ReadMessage (
228 ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
232 var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
233 foreach (var key in hrr.Headers.AllKeys)
234 rp.Headers [key] = hrr.Headers [key];
235 ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
237 channelResult.Response = ret;
238 channelResult.Complete ();
239 } catch (Exception ex) {
240 channelResult.Complete (ex);
246 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
248 ThrowIfDisposedOrNotOpen ();
250 HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, callback, state);
251 BeginProcessRequest (result);
255 public override Message EndRequest (IAsyncResult result)
258 throw new ArgumentNullException ("result");
259 HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
261 throw new InvalidOperationException ("Wrong IAsyncResult");
268 protected override void OnAbort ()
270 if (web_request != null)
271 web_request.Abort ();
277 protected override void OnClose (TimeSpan timeout)
279 if (web_request != null)
280 web_request.Abort ();
284 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
286 if (web_request != null)
287 web_request.Abort ();
289 return base.OnBeginClose (timeout, callback, state);
292 protected override void OnEndClose (IAsyncResult result)
294 base.OnEndClose (result);
299 protected override void OnOpen (TimeSpan timeout)
303 [MonoTODO ("find out what to do here")]
304 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
306 return base.OnBeginOpen (timeout, callback, state);
309 [MonoTODO ("find out what to do here")]
310 protected override void OnEndOpen (IAsyncResult result)
312 base.OnEndOpen (result);
315 class HttpChannelRequestAsyncResult : IAsyncResult
317 public Message Message {
321 public TimeSpan Timeout {
325 AsyncCallback callback;
326 ManualResetEvent wait;
328 object locker = new object ();
331 public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
335 this.callback = callback;
339 public Message Response {
343 public WaitHandle AsyncWaitHandle {
347 wait = new ManualResetEvent (is_completed);
353 public object AsyncState {
357 public void Complete ()
362 public void Complete (Exception ex)
367 // If we've already stored an error, don't replace it
371 if (callback != null)
375 public bool CompletedSynchronously {
379 public bool IsCompleted {
380 get { return is_completed; }
382 is_completed = value;
384 if (is_completed && wait != null)
390 public void WaitEnd ()
393 // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
394 // Is the current request cancelled and an exception thrown? If so we need to pass the
395 // exception to the Complete () method and allow the result to complete 'normally'.
397 // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
398 bool result = AsyncWaitHandle.WaitOne (Timeout);
400 bool result = AsyncWaitHandle.WaitOne (Timeout, true);
403 throw new TimeoutException ();