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;
46 // FIXME: supply maxSizeOfHeaders.
47 int max_headers = 0x10000;
51 public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
52 EndpointAddress address, Uri via)
53 : base (factory, address, via)
55 this.source = factory;
58 public int MaxSizeOfHeaders {
59 get { return max_headers; }
62 public MessageEncoder Encoder {
63 get { return source.MessageEncoder; }
68 public override Message Request (Message message, TimeSpan timeout)
70 return EndRequest (BeginRequest (message, timeout, null, null));
73 void BeginProcessRequest (HttpChannelRequestAsyncResult result)
75 Message message = result.Message;
76 TimeSpan timeout = result.Timeout;
77 // FIXME: is distination really like this?
78 Uri destination = message.Headers.To;
79 if (destination == null) {
80 if (source.Source.ManualAddressing)
81 throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address.");
83 destination = Via ?? RemoteAddress.Uri;
86 web_request = HttpWebRequest.Create (destination);
87 web_request.Method = "POST";
88 web_request.ContentType = Encoder.ContentType;
90 #if !NET_2_1 // until we support NetworkCredential like SL4 will do.
91 // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
92 var httpbe = (HttpTransportBindingElement) source.Source;
93 string authType = null;
94 switch (httpbe.AuthenticationScheme) {
95 // AuthenticationSchemes.Anonymous is the default, ignored.
96 case AuthenticationSchemes.Basic:
99 case AuthenticationSchemes.Digest:
102 case AuthenticationSchemes.Ntlm:
105 case AuthenticationSchemes.Negotiate:
106 authType = "Negotiate";
109 if (authType != null) {
110 var cred = source.ClientCredentials;
111 string user = cred != null ? cred.UserName.UserName : null;
112 string pwd = cred != null ? cred.UserName.Password : null;
113 if (String.IsNullOrEmpty (user))
114 throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
115 var nc = new NetworkCredential (user, pwd);
116 web_request.Credentials = nc;
117 // FIXME: it is said required in SL4, but it blocks full WCF.
118 //web_request.UseDefaultCredentials = false;
122 #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
123 web_request.Timeout = (int) timeout.TotalMilliseconds;
126 // There is no SOAP Action/To header when AddressingVersion is None.
127 if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
128 message.Version.Addressing.Equals (AddressingVersion.None)) {
129 if (message.Headers.Action != null) {
130 web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
131 message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
135 // apply HttpRequestMessageProperty if exists.
136 bool suppressEntityBody = false;
138 string pname = HttpRequestMessageProperty.Name;
139 if (message.Properties.ContainsKey (pname)) {
140 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
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) {
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)));
206 using (var responseStream = resstr) {
207 MemoryStream ms = new MemoryStream ();
208 byte [] b = new byte [65536];
212 n = responseStream.Read (b, 0, 65536);
217 ms.Seek (0, SeekOrigin.Begin);
219 channelResult.Response = Encoder.ReadMessage (
220 //responseStream, MaxSizeOfHeaders);
221 ms, MaxSizeOfHeaders, res.ContentType);
223 MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
224 ret = buf.CreateMessage ();
225 System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
226 w.Formatting = System.Xml.Formatting.Indented;
227 buf.CreateMessage ().WriteMessage (w);
230 channelResult.Complete ();
232 } catch (Exception ex) {
233 channelResult.Complete (ex);
239 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
241 ThrowIfDisposedOrNotOpen ();
243 HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, callback, state);
244 BeginProcessRequest (result);
248 public override Message EndRequest (IAsyncResult result)
251 throw new ArgumentNullException ("result");
252 HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
254 throw new InvalidOperationException ("Wrong IAsyncResult");
261 protected override void OnAbort ()
263 if (web_request != null)
264 web_request.Abort ();
270 protected override void OnClose (TimeSpan timeout)
272 if (web_request != null)
273 web_request.Abort ();
277 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
279 throw new NotImplementedException ();
282 protected override void OnEndClose (IAsyncResult result)
284 throw new NotImplementedException ();
289 protected override void OnOpen (TimeSpan timeout)
293 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
295 throw new NotImplementedException ();
298 protected override void OnEndOpen (IAsyncResult result)
300 throw new NotImplementedException ();
303 class HttpChannelRequestAsyncResult : IAsyncResult
305 public Message Message {
309 public TimeSpan Timeout {
313 AsyncCallback callback;
314 ManualResetEvent wait;
317 public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
319 CompletedSynchronously = true;
322 this.callback = callback;
325 wait = new ManualResetEvent (false);
328 public Message Response {
332 public WaitHandle AsyncWaitHandle {
336 public object AsyncState {
340 public void Complete ()
345 public void Complete (Exception ex)
350 // If we've already stored an error, don't replace it
355 if (callback != null)
359 public bool CompletedSynchronously {
363 public bool IsCompleted {
367 public void WaitEnd ()
370 // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
371 // Is the current request cancelled and an exception thrown? If so we need to pass the
372 // exception to the Complete () method and allow the result to complete 'normally'.
373 #if NET_2_1 || MONOTOUCH
374 // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
375 bool result = wait.WaitOne (Timeout);
377 bool result = wait.WaitOne (Timeout, true);
380 throw new TimeoutException ();