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 List<WebRequest> web_requests = new List<WebRequest> ();
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 var web_request = HttpWebRequest.Create (destination);
80 web_requests.Add (web_request);
81 result.WebRequest = web_request;
82 web_request.Method = "POST";
83 web_request.ContentType = Encoder.ContentType;
85 HttpWebRequest hwr = (web_request as HttpWebRequest);
87 if (hwr.SupportsCookieContainer) {
89 var cmgr = source.GetProperty<IHttpCookieContainerManager> ();
91 hwr.CookieContainer = cmgr.CookieContainer;
97 #if !MOONLIGHT // until we support NetworkCredential like SL4 will do.
98 // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
99 var httpbe = (HttpTransportBindingElement) source.Transport;
100 string authType = null;
101 switch (httpbe.AuthenticationScheme) {
102 // AuthenticationSchemes.Anonymous is the default, ignored.
103 case AuthenticationSchemes.Basic:
106 case AuthenticationSchemes.Digest:
109 case AuthenticationSchemes.Ntlm:
112 case AuthenticationSchemes.Negotiate:
113 authType = "Negotiate";
116 if (authType != null) {
117 var cred = source.ClientCredentials;
118 string user = cred != null ? cred.UserName.UserName : null;
119 string pwd = cred != null ? cred.UserName.Password : null;
120 if (String.IsNullOrEmpty (user))
121 throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
122 var nc = new NetworkCredential (user, pwd);
123 web_request.Credentials = nc;
124 // FIXME: it is said required in SL4, but it blocks full WCF.
125 //web_request.UseDefaultCredentials = false;
129 #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
130 web_request.Timeout = (int) timeout.TotalMilliseconds;
133 // There is no SOAP Action/To header when AddressingVersion is None.
134 if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
135 message.Version.Addressing.Equals (AddressingVersion.None)) {
136 if (message.Headers.Action != null) {
137 web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
138 message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
142 // apply HttpRequestMessageProperty if exists.
143 bool suppressEntityBody = false;
145 string pname = HttpRequestMessageProperty.Name;
146 if (message.Properties.ContainsKey (pname)) {
147 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
148 web_request.Headers.Clear ();
149 web_request.Headers.Add (hp.Headers);
150 web_request.Method = hp.Method;
151 // FIXME: do we have to handle hp.QueryString ?
152 if (hp.SuppressEntityBody)
153 suppressEntityBody = true;
157 if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
158 MemoryStream buffer = new MemoryStream ();
159 Encoder.WriteMessage (message, buffer);
161 if (buffer.Length > int.MaxValue)
162 throw new InvalidOperationException ("The argument message is too large.");
165 web_request.ContentLength = (int) buffer.Length;
168 web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
170 result.CompletedSynchronously &= r.CompletedSynchronously;
171 using (Stream s = web_request.EndGetRequestStream (r))
172 s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
173 web_request.BeginGetResponse (GotResponse, result);
174 } catch (WebException ex) {
177 case WebExceptionStatus.NameResolutionFailure:
179 case WebExceptionStatus.ConnectFailure:
180 result.Complete (new EndpointNotFoundException (new EndpointNotFoundException ().Message, ex));
183 result.Complete (ex);
186 } catch (Exception ex) {
187 result.Complete (ex);
191 web_request.BeginGetResponse (GotResponse, result);
195 void GotResponse (IAsyncResult result)
197 HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
198 channelResult.CompletedSynchronously &= result.CompletedSynchronously;
203 res = channelResult.WebRequest.EndGetResponse (result);
204 resstr = res.GetResponseStream ();
205 } catch (WebException we) {
208 channelResult.Complete (we);
212 // The response might contain SOAP fault. It might not.
213 resstr = res.GetResponseStream ();
214 } catch (WebException we2) {
215 channelResult.Complete (we2);
220 var hrr = (HttpWebResponse) res;
221 if ((int) hrr.StatusCode >= 400 && (int) hrr.StatusCode < 500) {
222 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)));
228 // TODO: unit test to make sure an empty response never throws
229 // an exception at this level
230 if (hrr.ContentLength == 0) {
231 ret = Message.CreateMessage (MessageVersion.Default, String.Empty);
234 using (var responseStream = resstr) {
235 MemoryStream ms = new MemoryStream ();
236 byte [] b = new byte [65536];
240 n = responseStream.Read (b, 0, 65536);
245 ms.Seek (0, SeekOrigin.Begin);
247 ret = Encoder.ReadMessage (
248 ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
252 var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
254 if (hrr.SupportsHeaders) {
255 foreach (string key in hrr.Headers)
256 rp.Headers [key] = hrr.Headers [key];
259 foreach (var key in hrr.Headers.AllKeys)
260 rp.Headers [key] = hrr.Headers [key];
262 ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
264 channelResult.Response = ret;
265 channelResult.Complete ();
266 } catch (Exception ex) {
267 channelResult.Complete (ex);
273 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
275 ThrowIfDisposedOrNotOpen ();
277 HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, this, callback, state);
278 BeginProcessRequest (result);
282 public override Message EndRequest (IAsyncResult result)
285 throw new ArgumentNullException ("result");
286 HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
288 throw new InvalidOperationException ("Wrong IAsyncResult");
295 protected override void OnAbort ()
297 foreach (var web_request in web_requests.ToArray ())
298 web_request.Abort ();
299 web_requests.Clear ();
304 protected override void OnClose (TimeSpan timeout)
309 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
312 return base.OnBeginClose (timeout, callback, state);
315 protected override void OnEndClose (IAsyncResult result)
317 base.OnEndClose (result);
322 protected override void OnOpen (TimeSpan timeout)
326 [MonoTODO ("find out what to do here")]
327 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
329 return base.OnBeginOpen (timeout, callback, state);
332 [MonoTODO ("find out what to do here")]
333 protected override void OnEndOpen (IAsyncResult result)
335 base.OnEndOpen (result);
338 class HttpChannelRequestAsyncResult : IAsyncResult, IDisposable
340 public Message Message {
344 public TimeSpan Timeout {
348 AsyncCallback callback;
349 ManualResetEvent wait;
351 object locker = new object ();
353 HttpRequestChannel owner;
355 public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, HttpRequestChannel owner, AsyncCallback callback, object state)
360 this.callback = callback;
364 public Message Response {
368 public WebRequest WebRequest { get; set; }
370 public WaitHandle AsyncWaitHandle {
374 wait = new ManualResetEvent (is_completed);
380 public object AsyncState {
384 public void Complete ()
389 public void Complete (Exception ex)
394 // If we've already stored an error, don't replace it
398 if (callback != null)
402 public bool CompletedSynchronously {
406 public bool IsCompleted {
407 get { return is_completed; }
409 is_completed = value;
411 if (is_completed && wait != null)
418 public void WaitEnd ()
421 // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
422 // Is the current request cancelled and an exception thrown? If so we need to pass the
423 // exception to the Complete () method and allow the result to complete 'normally'.
425 // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
426 bool result = AsyncWaitHandle.WaitOne (Timeout);
428 bool result = AsyncWaitHandle.WaitOne (Timeout, true);
431 throw new TimeoutException ();
437 public void Dispose ()
444 owner.web_requests.Remove (WebRequest);