Wed Feb 24 15:47:16 CET 2010 Paolo Molaro <lupus@ximian.com>
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel.Channels / HttpReplyChannel.cs
1 //
2 // HttpReplyChannel.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2006 Novell, Inc.  http://www.novell.com
8 //
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:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
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.
27 //
28 using System;
29 using System.Collections.Generic;
30 using System.Collections.Specialized;
31 using System.IO;
32 using System.Net;
33 using System.ServiceModel;
34 using System.Text;
35 using System.Threading;
36
37 namespace System.ServiceModel.Channels
38 {
39         internal class HttpSimpleReplyChannel : HttpReplyChannel
40         {
41                 HttpSimpleChannelListener<IReplyChannel> source;
42                 List<HttpListenerContext> waiting = new List<HttpListenerContext> ();
43                 RequestContext reqctx;
44
45                 public HttpSimpleReplyChannel (HttpSimpleChannelListener<IReplyChannel> listener)
46                         : base (listener)
47                 {
48                         this.source = listener;
49                 }
50
51                 protected override void OnAbort ()
52                 {
53                         AbortConnections (TimeSpan.Zero);
54                         base.OnAbort (); // FIXME: remove it. The base is wrong. But it is somehow required to not block some tests.
55                 }
56
57                 public override bool CancelAsync (TimeSpan timeout)
58                 {
59                         AbortConnections (timeout);
60                         // FIXME: this wait is sort of hack (because it should not be required), but without it some tests are blocked.
61                         // This hack even had better be moved to base.CancelAsync().
62                         if (CurrentAsyncResult != null)
63                                 CurrentAsyncResult.AsyncWaitHandle.WaitOne (TimeSpan.FromMilliseconds (300));
64                         return base.CancelAsync (timeout);
65                 }
66
67                 void SignalAsyncWait ()
68                 {
69                         if (wait == null)
70                                 return;
71                         var wait_ = wait;
72                         wait = null;
73                         wait_.Set ();
74                 }
75
76                 void AbortConnections (TimeSpan timeout)
77                 {
78                         // FIXME: use timeout
79                         lock (waiting)
80                                 foreach (var ctx in waiting)
81                                         ctx.Response.Close ();
82                         if (wait != null)
83                                 source.ListenerManager.CancelGetHttpContextAsync ();
84                 }
85
86                 protected override void OnClose (TimeSpan timeout)
87                 {
88                         DateTime start = DateTime.Now;
89                         if (reqctx != null)
90                                 reqctx.Close (timeout);
91
92                         // FIXME: consider timeout
93                         AbortConnections (timeout - (DateTime.Now - start));
94
95                         base.OnClose (timeout - (DateTime.Now - start));
96                 }
97
98                 public override bool TryReceiveRequest (TimeSpan timeout, out RequestContext context)
99                 {
100                         context = null;
101                         if (waiting.Count == 0 && !WaitForRequest (timeout))
102                                 return false;
103                         HttpListenerContext ctx = null;
104                         lock (waiting) {
105                                 if (waiting.Count > 0) {
106                                         ctx = waiting [0];
107                                         waiting.RemoveAt (0);
108                                 }
109                         }
110                         if (ctx == null) 
111                                 // Though as long as this instance is used
112                                 // synchronously, it should not happen.
113                                 return false;
114
115                         // FIXME: supply maxSizeOfHeaders.
116                         int maxSizeOfHeaders = 0x10000;
117
118                         Message msg = null;
119
120                         // FIXME: our HttpConnection (under HttpListener) 
121                         // somehow breaks when the underlying connection is
122                         // reused. Remove it when it gets fixed.
123                         ctx.Response.KeepAlive = false;
124
125                         if (ctx.Request.HttpMethod == "POST") {
126                                 if (!Encoder.IsContentTypeSupported (ctx.Request.ContentType)) {
127                                         ctx.Response.StatusCode = (int) HttpStatusCode.UnsupportedMediaType;
128                                         ctx.Response.StatusDescription = String.Format (
129                                                         "Expected content-type '{0}' but got '{1}'", Encoder.ContentType, ctx.Request.ContentType);
130                                         ctx.Response.Close ();
131
132                                         return false;
133                                 }
134
135                                 msg = Encoder.ReadMessage (
136                                         ctx.Request.InputStream, maxSizeOfHeaders);
137
138                                 if (MessageVersion.Envelope.Equals (EnvelopeVersion.Soap11) ||
139                                     MessageVersion.Addressing.Equals (AddressingVersion.None)) {
140                                         string action = GetHeaderItem (ctx.Request.Headers ["SOAPAction"]);
141                                         if (action != null) {
142                                                 if (action.Length > 2 && action [0] == '"' && action [action.Length] == '"')
143                                                         action = action.Substring (1, action.Length - 2);
144                                                 msg.Headers.Action = action;
145                                         }
146                                 }
147                         } else if (ctx.Request.HttpMethod == "GET") {
148                                 msg = Message.CreateMessage (MessageVersion, null);
149                         }
150                         msg.Headers.To = ctx.Request.Url;
151                         msg.Properties.Add ("Via", LocalAddress.Uri);
152                         msg.Properties.Add (HttpRequestMessageProperty.Name, CreateRequestProperty (ctx.Request.HttpMethod, ctx.Request.Url.Query, ctx.Request.Headers));
153 /*
154 MessageBuffer buf = msg.CreateBufferedCopy (0x10000);
155 msg = buf.CreateMessage ();
156 System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
157 w.Formatting = System.Xml.Formatting.Indented;
158 buf.CreateMessage ().WriteMessage (w);
159 w.Close ();
160 */
161                         context = new HttpRequestContext (this, msg, ctx);
162                         reqctx = context;
163                         return true;
164                 }
165
166                 AutoResetEvent wait;
167
168                 public override bool WaitForRequest (TimeSpan timeout)
169                 {
170                         if (wait != null)
171                                 throw new InvalidOperationException ("Another wait operation is in progress");
172                         try {
173                                 wait = new AutoResetEvent (false);
174                                 source.ListenerManager.GetHttpContextAsync (timeout, HttpContextAcquired);
175                                 if (wait != null) // in case callback is done before WaitOne() here.
176                                         return wait.WaitOne (timeout, false);
177                                 return waiting.Count > 0;
178                         } catch (HttpListenerException e) {
179                                 // FIXME: does this make sense? I doubt.
180                                 if ((uint) e.ErrorCode == 0x80004005) // invalid handle. Happens during shutdown.
181                                         while (true) Thread.Sleep (1000); // thread is about to be terminated.
182                                 throw;
183                         } catch (ObjectDisposedException) {
184                                 return false;
185                         } finally {
186                                 wait = null;
187                         }
188                 }
189
190                 void HttpContextAcquired (HttpContextInfo ctx)
191                 {
192                         if (wait == null)
193                                 throw new InvalidOperationException ("WaitForRequest operation has not started");
194                         var sctx = (HttpListenerContextInfo) ctx;
195                         if (State == CommunicationState.Opened && ctx != null)
196                                 waiting.Add (sctx.Source);
197                         SignalAsyncWait ();
198                 }
199         }
200
201         internal abstract class HttpReplyChannel : InternalReplyChannelBase
202         {
203                 HttpChannelListenerBase<IReplyChannel> source;
204
205                 public HttpReplyChannel (HttpChannelListenerBase<IReplyChannel> listener)
206                         : base (listener)
207                 {
208                         this.source = listener;
209                 }
210
211                 public MessageEncoder Encoder {
212                         get { return source.MessageEncoder; }
213                 }
214
215                 internal MessageVersion MessageVersion {
216                         get { return source.MessageEncoder.MessageVersion; }
217                 }
218
219                 public override RequestContext ReceiveRequest (TimeSpan timeout)
220                 {
221                         RequestContext ctx;
222                         TryReceiveRequest (timeout, out ctx);
223                         return ctx;
224                 }
225
226                 protected override void OnOpen (TimeSpan timeout)
227                 {
228                 }
229
230                 protected string GetHeaderItem (string raw)
231                 {
232                         if (raw == null || raw.Length == 0)
233                                 return raw;
234                         switch (raw [0]) {
235                         case '\'':
236                         case '"':
237                                 if (raw [raw.Length - 1] == raw [0])
238                                         return raw.Substring (1, raw.Length - 2);
239                                 // FIXME: is it simply an error?
240                                 break;
241                         }
242                         return raw;
243                 }
244
245                 protected HttpRequestMessageProperty CreateRequestProperty (string method, string query, NameValueCollection headers)
246                 {
247                         var prop = new HttpRequestMessageProperty ();
248                         prop.Method = method;
249                         prop.QueryString = query.StartsWith ("?") ? query.Substring (1) : query;
250                         // FIXME: prop.SuppressEntityBody
251                         prop.Headers.Add (headers);
252                         return prop;
253                 }
254         }
255 }