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;
86 var cmgr = source.GetProperty<IHttpCookieContainerManager> ();
88 ((HttpWebRequest) web_request).CookieContainer = cmgr.CookieContainer;
91 #if !MOONLIGHT // until we support NetworkCredential like SL4 will do.
92 // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
93 var httpbe = (HttpTransportBindingElement) source.Transport;
94 string authType = null;
95 switch (httpbe.AuthenticationScheme) {
96 // AuthenticationSchemes.Anonymous is the default, ignored.
97 case AuthenticationSchemes.Basic:
100 case AuthenticationSchemes.Digest:
103 case AuthenticationSchemes.Ntlm:
106 case AuthenticationSchemes.Negotiate:
107 authType = "Negotiate";
110 if (authType != null) {
111 var cred = source.ClientCredentials;
112 string user = cred != null ? cred.UserName.UserName : null;
113 string pwd = cred != null ? cred.UserName.Password : null;
114 if (String.IsNullOrEmpty (user))
115 throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
116 var nc = new NetworkCredential (user, pwd);
117 web_request.Credentials = nc;
118 // FIXME: it is said required in SL4, but it blocks full WCF.
119 //web_request.UseDefaultCredentials = false;
123 #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
124 web_request.Timeout = (int) timeout.TotalMilliseconds;
127 // There is no SOAP Action/To header when AddressingVersion is None.
128 if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
129 message.Version.Addressing.Equals (AddressingVersion.None)) {
130 if (message.Headers.Action != null) {
131 web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
132 message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
136 // apply HttpRequestMessageProperty if exists.
137 bool suppressEntityBody = false;
139 string pname = HttpRequestMessageProperty.Name;
140 if (message.Properties.ContainsKey (pname)) {
141 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
142 web_request.Headers.Clear ();
143 web_request.Headers.Add (hp.Headers);
144 web_request.Method = hp.Method;
145 // FIXME: do we have to handle hp.QueryString ?
146 if (hp.SuppressEntityBody)
147 suppressEntityBody = true;
151 if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
152 MemoryStream buffer = new MemoryStream ();
153 Encoder.WriteMessage (message, buffer);
155 if (buffer.Length > int.MaxValue)
156 throw new InvalidOperationException ("The argument message is too large.");
159 web_request.ContentLength = (int) buffer.Length;
162 web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
164 result.CompletedSynchronously &= r.CompletedSynchronously;
165 using (Stream s = web_request.EndGetRequestStream (r))
166 s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
167 web_request.BeginGetResponse (GotResponse, result);
168 } catch (WebException ex) {
171 case WebExceptionStatus.NameResolutionFailure:
173 case WebExceptionStatus.ConnectFailure:
174 result.Complete (new EndpointNotFoundException (new EndpointNotFoundException ().Message, ex));
177 result.Complete (ex);
180 } catch (Exception ex) {
181 result.Complete (ex);
185 web_request.BeginGetResponse (GotResponse, result);
189 void GotResponse (IAsyncResult result)
191 HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
192 channelResult.CompletedSynchronously &= result.CompletedSynchronously;
197 res = channelResult.WebRequest.EndGetResponse (result);
198 resstr = res.GetResponseStream ();
199 } catch (WebException we) {
202 channelResult.Complete (we);
206 // The response might contain SOAP fault. It might not.
207 resstr = res.GetResponseStream ();
208 } catch (WebException we2) {
209 channelResult.Complete (we2);
214 var hrr = (HttpWebResponse) res;
215 if ((int) hrr.StatusCode >= 400 && (int) hrr.StatusCode < 500) {
216 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)));
222 // TODO: unit test to make sure an empty response never throws
223 // an exception at this level
224 if (hrr.ContentLength == 0) {
225 ret = Message.CreateMessage (MessageVersion.Default, String.Empty);
228 using (var responseStream = resstr) {
229 MemoryStream ms = new MemoryStream ();
230 byte [] b = new byte [65536];
234 n = responseStream.Read (b, 0, 65536);
239 ms.Seek (0, SeekOrigin.Begin);
241 ret = Encoder.ReadMessage (
242 ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
246 var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
248 if (hrr.SupportsHeaders) {
249 foreach (string key in hrr.Headers)
250 rp.Headers [key] = hrr.Headers [key];
253 foreach (var key in hrr.Headers.AllKeys)
254 rp.Headers [key] = hrr.Headers [key];
256 ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
258 channelResult.Response = ret;
259 channelResult.Complete ();
260 } catch (Exception ex) {
261 channelResult.Complete (ex);
267 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
269 ThrowIfDisposedOrNotOpen ();
271 HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, this, callback, state);
272 BeginProcessRequest (result);
276 public override Message EndRequest (IAsyncResult result)
279 throw new ArgumentNullException ("result");
280 HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
282 throw new InvalidOperationException ("Wrong IAsyncResult");
289 protected override void OnAbort ()
291 foreach (var web_request in web_requests)
292 web_request.Abort ();
293 web_requests.Clear ();
298 protected override void OnClose (TimeSpan timeout)
303 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
306 return base.OnBeginClose (timeout, callback, state);
309 protected override void OnEndClose (IAsyncResult result)
311 base.OnEndClose (result);
316 protected override void OnOpen (TimeSpan timeout)
320 [MonoTODO ("find out what to do here")]
321 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
323 return base.OnBeginOpen (timeout, callback, state);
326 [MonoTODO ("find out what to do here")]
327 protected override void OnEndOpen (IAsyncResult result)
329 base.OnEndOpen (result);
332 class HttpChannelRequestAsyncResult : IAsyncResult, IDisposable
334 public Message Message {
338 public TimeSpan Timeout {
342 AsyncCallback callback;
343 ManualResetEvent wait;
345 object locker = new object ();
347 HttpRequestChannel owner;
349 public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, HttpRequestChannel owner, AsyncCallback callback, object state)
354 this.callback = callback;
358 public Message Response {
362 public WebRequest WebRequest { get; set; }
364 public WaitHandle AsyncWaitHandle {
368 wait = new ManualResetEvent (is_completed);
374 public object AsyncState {
378 public void Complete ()
383 public void Complete (Exception ex)
388 // If we've already stored an error, don't replace it
392 if (callback != null)
396 public bool CompletedSynchronously {
400 public bool IsCompleted {
401 get { return is_completed; }
403 is_completed = value;
405 if (is_completed && wait != null)
412 public void WaitEnd ()
415 // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
416 // Is the current request cancelled and an exception thrown? If so we need to pass the
417 // exception to the Complete () method and allow the result to complete 'normally'.
419 // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
420 bool result = AsyncWaitHandle.WaitOne (Timeout);
422 bool result = AsyncWaitHandle.WaitOne (Timeout, true);
425 throw new TimeoutException ();
431 public void Dispose ()
438 owner.web_requests.Remove (WebRequest);