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; }
60 public override T GetProperty<T> ()
62 if (typeof (T) == typeof (IHttpCookieContainerManager))
63 return source.GetProperty<T> ();
64 return base.GetProperty<T> ();
70 public override Message Request (Message message, TimeSpan timeout)
72 return EndRequest (BeginRequest (message, timeout, null, null));
75 void BeginProcessRequest (HttpChannelRequestAsyncResult result)
77 Message message = result.Message;
78 TimeSpan timeout = result.Timeout;
79 // FIXME: is distination really like this?
80 Uri destination = message.Headers.To;
81 if (destination == null) {
82 if (source.Transport.ManualAddressing)
83 throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address.");
85 destination = Via ?? RemoteAddress.Uri;
88 var web_request = (HttpWebRequest) HttpWebRequest.Create (destination);
89 web_requests.Add (web_request);
90 result.WebRequest = web_request;
91 web_request.Method = "POST";
92 web_request.ContentType = Encoder.ContentType;
93 #if NET_2_1 || NET_4_0
94 HttpWebRequest hwr = (web_request as HttpWebRequest);
95 var cmgr = source.GetProperty<IHttpCookieContainerManager> ();
97 hwr.CookieContainer = cmgr.CookieContainer;
100 // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
101 var httpbe = (HttpTransportBindingElement) source.Transport;
102 string authType = null;
103 switch (httpbe.AuthenticationScheme) {
104 // AuthenticationSchemes.Anonymous is the default, ignored.
105 case AuthenticationSchemes.Basic:
108 case AuthenticationSchemes.Digest:
111 case AuthenticationSchemes.Ntlm:
114 case AuthenticationSchemes.Negotiate:
115 authType = "Negotiate";
118 if (authType != null) {
119 var cred = source.ClientCredentials;
120 string user = cred != null ? cred.UserName.UserName : null;
121 string pwd = cred != null ? cred.UserName.Password : null;
122 if (String.IsNullOrEmpty (user))
123 throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
124 var nc = new NetworkCredential (user, pwd);
125 web_request.Credentials = nc;
126 // FIXME: it is said required in SL4, but it blocks full WCF.
127 //web_request.UseDefaultCredentials = false;
130 #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
131 web_request.Timeout = (int) timeout.TotalMilliseconds;
134 // There is no SOAP Action/To header when AddressingVersion is None.
135 if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
136 message.Version.Addressing.Equals (AddressingVersion.None)) {
137 if (message.Headers.Action != null) {
138 web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
139 message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
143 // apply HttpRequestMessageProperty if exists.
144 bool suppressEntityBody = false;
145 string pname = HttpRequestMessageProperty.Name;
146 if (message.Properties.ContainsKey (pname)) {
147 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
148 foreach (var key in hp.Headers.AllKeys) {
149 if (WebHeaderCollection.IsRestricted (key)) { // do not ignore this. WebHeaderCollection rejects restricted ones.
150 // FIXME: huh, there should be any better way to do such stupid conversion.
153 web_request.Accept = hp.Headers [key];
156 web_request.Connection = hp.Headers [key];
158 //case "ContentLength":
159 // web_request.ContentLength = hp.Headers [key];
162 web_request.ContentType = hp.Headers [key];
165 // web_request.Date = hp.Headers [key];
168 web_request.Expect = hp.Headers [key];
172 web_request.Host = hp.Headers [key];
175 //case "If-Modified-Since":
176 // web_request.IfModifiedSince = hp.Headers [key];
179 web_request.Referer = hp.Headers [key];
181 case "Transfer-Encoding":
182 web_request.TransferEncoding = hp.Headers [key];
185 web_request.UserAgent = hp.Headers [key];
190 web_request.Headers [key] = hp.Headers [key];
192 web_request.Method = hp.Method;
193 // FIXME: do we have to handle hp.QueryString ?
194 if (hp.SuppressEntityBody)
195 suppressEntityBody = true;
198 if (source.ClientCredentials != null) {
199 var cred = source.ClientCredentials;
200 if ((cred.ClientCertificate != null) && (cred.ClientCertificate.Certificate != null))
201 ((HttpWebRequest)web_request).ClientCertificates.Add (cred.ClientCertificate.Certificate);
205 if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
206 MemoryStream buffer = new MemoryStream ();
207 Encoder.WriteMessage (message, buffer);
209 if (buffer.Length > int.MaxValue)
210 throw new InvalidOperationException ("The argument message is too large.");
213 web_request.ContentLength = (int) buffer.Length;
216 web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
218 result.CompletedSynchronously &= r.CompletedSynchronously;
219 using (Stream s = web_request.EndGetRequestStream (r))
220 s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
221 web_request.BeginGetResponse (GotResponse, result);
222 } catch (WebException ex) {
225 case WebExceptionStatus.NameResolutionFailure:
227 case WebExceptionStatus.ConnectFailure:
228 result.Complete (new EndpointNotFoundException (new EndpointNotFoundException ().Message, ex));
231 result.Complete (ex);
234 } catch (Exception ex) {
235 result.Complete (ex);
239 web_request.BeginGetResponse (GotResponse, result);
243 void GotResponse (IAsyncResult result)
245 HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
246 channelResult.CompletedSynchronously &= result.CompletedSynchronously;
251 res = channelResult.WebRequest.EndGetResponse (result);
252 resstr = res.GetResponseStream ();
253 } catch (WebException we) {
256 channelResult.Complete (we);
261 var hrr2 = (HttpWebResponse) res;
263 if ((int) hrr2.StatusCode >= 400 && (int) hrr2.StatusCode < 500) {
264 Exception exception = new WebException (
265 String.Format ("There was an error on processing web request: Status code {0}({1}): {2}",
266 (int) hrr2.StatusCode, hrr2.StatusCode, hrr2.StatusDescription), null,
267 WebExceptionStatus.ProtocolError, hrr2);
269 if ((int) hrr2.StatusCode == 404) {
270 // Throw the same exception .NET does
271 exception = new EndpointNotFoundException (
272 "There was no endpoint listening at {0} that could accept the message. This is often caused by an incorrect address " +
273 "or SOAP action. See InnerException, if present, for more details.",
277 channelResult.Complete (exception);
283 // The response might contain SOAP fault. It might not.
284 resstr = res.GetResponseStream ();
285 } catch (WebException we2) {
286 channelResult.Complete (we2);
291 var hrr = (HttpWebResponse) res;
292 if ((int) hrr.StatusCode >= 400 && (int) hrr.StatusCode < 500) {
293 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)));
299 // TODO: unit test to make sure an empty response never throws
300 // an exception at this level
301 if (hrr.ContentLength == 0) {
302 ret = Message.CreateMessage (Encoder.MessageVersion, String.Empty);
305 using (var responseStream = resstr) {
306 MemoryStream ms = new MemoryStream ();
307 byte [] b = new byte [65536];
311 n = responseStream.Read (b, 0, 65536);
316 ms.Seek (0, SeekOrigin.Begin);
318 ret = Encoder.ReadMessage (
319 ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
323 var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
324 foreach (var key in hrr.Headers.AllKeys)
325 rp.Headers [key] = hrr.Headers [key];
326 ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
328 channelResult.Response = ret;
329 channelResult.Complete ();
330 } catch (Exception ex) {
331 channelResult.Complete (ex);
337 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
339 ThrowIfDisposedOrNotOpen ();
341 HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, this, callback, state);
342 BeginProcessRequest (result);
346 public override Message EndRequest (IAsyncResult result)
349 throw new ArgumentNullException ("result");
350 HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
352 throw new InvalidOperationException ("Wrong IAsyncResult");
359 protected override void OnAbort ()
361 foreach (var web_request in web_requests.ToArray ())
362 web_request.Abort ();
363 web_requests.Clear ();
368 protected override void OnClose (TimeSpan timeout)
373 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
376 return base.OnBeginClose (timeout, callback, state);
379 protected override void OnEndClose (IAsyncResult result)
381 base.OnEndClose (result);
386 protected override void OnOpen (TimeSpan timeout)
390 [MonoTODO ("find out what to do here")]
391 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
393 return base.OnBeginOpen (timeout, callback, state);
396 [MonoTODO ("find out what to do here")]
397 protected override void OnEndOpen (IAsyncResult result)
399 base.OnEndOpen (result);
402 class HttpChannelRequestAsyncResult : IAsyncResult, IDisposable
404 public Message Message {
408 public TimeSpan Timeout {
412 AsyncCallback callback;
413 ManualResetEvent wait;
415 object locker = new object ();
417 HttpRequestChannel owner;
419 public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, HttpRequestChannel owner, AsyncCallback callback, object state)
424 this.callback = callback;
428 public Message Response {
432 public WebRequest WebRequest { get; set; }
434 public WaitHandle AsyncWaitHandle {
438 wait = new ManualResetEvent (is_completed);
444 public object AsyncState {
448 public void Complete ()
453 public void Complete (Exception ex)
458 // If we've already stored an error, don't replace it
462 if (callback != null)
466 public bool CompletedSynchronously {
470 public bool IsCompleted {
471 get { return is_completed; }
473 is_completed = value;
475 if (is_completed && wait != null)
482 public void WaitEnd ()
485 // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
486 // Is the current request cancelled and an exception thrown? If so we need to pass the
487 // exception to the Complete () method and allow the result to complete 'normally'.
489 // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
490 bool result = AsyncWaitHandle.WaitOne (Timeout);
492 bool result = AsyncWaitHandle.WaitOne (Timeout, true);
495 throw new TimeoutException ();
501 public void Dispose ()
508 owner.web_requests.Remove (WebRequest);