Merge branch 'master' of github.com:mono/mono
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel.Channels.Http / HttpReplyChannel.cs
1 //
2 // HttpReplyChannel.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2010 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.Http
38 {
39         internal class HttpReplyChannel : InternalReplyChannelBase
40         {
41                 HttpChannelListener<IReplyChannel> source;
42                 RequestContext reqctx;
43
44                 public HttpReplyChannel (HttpChannelListener<IReplyChannel> listener)
45                         : base (listener)
46                 {
47                         this.source = listener;
48                 }
49
50                 public MessageEncoder Encoder {
51                         get { return source.MessageEncoder; }
52                 }
53
54                 internal MessageVersion MessageVersion {
55                         get { return source.MessageEncoder.MessageVersion; }
56                 }
57
58                 public override RequestContext ReceiveRequest (TimeSpan timeout)
59                 {
60                         RequestContext ctx;
61                         if (!TryReceiveRequest (timeout, out ctx))
62                                 throw new TimeoutException ();
63                         return ctx;
64                 }
65
66                 protected override void OnOpen (TimeSpan timeout)
67                 {
68                 }
69
70                 protected override void OnAbort ()
71                 {
72                         AbortConnections (TimeSpan.Zero);
73                         base.OnAbort (); // FIXME: remove it. The base is wrong. But it is somehow required to not block some tests.
74                 }
75
76                 public override bool CancelAsync (TimeSpan timeout)
77                 {
78                         AbortConnections (timeout);
79                         // FIXME: this wait is sort of hack (because it should not be required), but without it some tests are blocked.
80                         // This hack even had better be moved to base.CancelAsync().
81                         if (CurrentAsyncResult != null)
82                                 CurrentAsyncResult.AsyncWaitHandle.WaitOne (TimeSpan.FromMilliseconds (300));
83                         return base.CancelAsync (timeout);
84                 }
85
86                 void AbortConnections (TimeSpan timeout)
87                 {
88                         if (reqctx != null)
89                                 reqctx.Close (timeout);
90                 }
91
92                 bool close_started;
93
94                 protected override void OnClose (TimeSpan timeout)
95                 {
96                         if (close_started)
97                                 return;
98                         close_started = true;
99                         DateTime start = DateTime.Now;
100
101                         // FIXME: consider timeout
102                         AbortConnections (timeout - (DateTime.Now - start));
103
104                         base.OnClose (timeout - (DateTime.Now - start));
105                 }
106
107                 protected string GetHeaderItem (string raw)
108                 {
109                         if (raw == null || raw.Length == 0)
110                                 return raw;
111                         switch (raw [0]) {
112                         case '\'':
113                         case '"':
114                                 if (raw [raw.Length - 1] == raw [0])
115                                         return raw.Substring (1, raw.Length - 2);
116                                 // FIXME: is it simply an error?
117                                 break;
118                         }
119                         return raw;
120                 }
121
122                 protected HttpRequestMessageProperty CreateRequestProperty (HttpContextInfo ctxi)
123                 {
124                         var query = ctxi.Request.Url.Query;
125                         var prop = new HttpRequestMessageProperty ();
126                         prop.Method = ctxi.Request.HttpMethod;
127                         prop.QueryString = query.StartsWith ("?") ? query.Substring (1) : query;
128                         // FIXME: prop.SuppressEntityBody
129                         prop.Headers.Add (ctxi.Request.Headers);
130                         return prop;
131                 }
132
133                 public override bool TryReceiveRequest (TimeSpan timeout, out RequestContext context)
134                 {
135                         context = null;
136                         HttpContextInfo ctxi;
137                         if (!source.ListenerManager.TryDequeueRequest (source.ChannelDispatcher, timeout, out ctxi))
138                                 return false;
139                         if (ctxi == null)
140                                 return true; // returning true, yet context is null. This happens at closing phase.
141
142                         Message msg = null;
143
144                         if (ctxi.Request.HttpMethod == "POST") {
145                                 msg = CreatePostMessage (ctxi);
146                                 if (msg == null)
147                                         return false;
148                         } else if (ctxi.Request.HttpMethod == "GET")
149                                 msg = Message.CreateMessage (MessageVersion.None, null); // HTTP GET-based request
150
151                         if (msg.Headers.To == null)
152                                 msg.Headers.To = ctxi.Request.Url;
153                         msg.Properties.Add ("Via", LocalAddress.Uri);
154                         msg.Properties.Add (HttpRequestMessageProperty.Name, CreateRequestProperty (ctxi));
155
156                         context = new HttpRequestContext (this, ctxi, msg);
157                         reqctx = context;
158                         return true;
159                 }
160
161                 protected Message CreatePostMessage (HttpContextInfo ctxi)
162                 {
163                         if (ctxi.Response.StatusCode != 200) { // it's already invalid.
164                                 ctxi.Close ();
165                                 return null;
166                         }
167
168                         if (!Encoder.IsContentTypeSupported (ctxi.Request.ContentType)) {
169                                 ctxi.Response.StatusCode = (int) HttpStatusCode.UnsupportedMediaType;
170                                 ctxi.Response.StatusDescription = String.Format (
171                                                 "Expected content-type '{0}' but got '{1}'", Encoder.ContentType, ctxi.Request.ContentType);
172                                 ctxi.Close ();
173
174                                 return null;
175                         }
176
177                         // FIXME: supply maxSizeOfHeaders.
178                         int maxSizeOfHeaders = 0x10000;
179
180 #if false // FIXME: enable it, once duplex callback test gets passed.
181                         Stream stream = ctxi.Request.InputStream;
182                         if (source.Source.TransferMode == TransferMode.Buffered) {
183                                 if (ctxi.Request.ContentLength64 <= 0)
184                                         throw new ArgumentException ("This HTTP channel is configured to use buffered mode, and thus expects Content-Length sent to the listener");
185                                 long size = 0;
186                                 var ms = new MemoryStream ();
187                                 var buf = new byte [0x1000];
188                                 while (size < ctxi.Request.ContentLength64) {
189                                         if ((size += stream.Read (buf, 0, 0x1000)) > source.Source.MaxBufferSize)
190                                                 throw new QuotaExceededException ("Message quota exceeded");
191                                         ms.Write (buf, 0, (int) (size - ms.Length));
192                                 }
193                                 ms.Position = 0;
194                                 stream = ms;
195                         }
196
197                         var msg = Encoder.ReadMessage (
198                                 stream, maxSizeOfHeaders, ctxi.Request.ContentType);
199 #else
200                         var msg = Encoder.ReadMessage (
201                                 ctxi.Request.InputStream, maxSizeOfHeaders, ctxi.Request.ContentType);
202 #endif
203
204                         if (MessageVersion.Envelope.Equals (EnvelopeVersion.Soap11) ||
205                             MessageVersion.Addressing.Equals (AddressingVersion.None)) {
206                                 string action = GetHeaderItem (ctxi.Request.Headers ["SOAPAction"]);
207                                 if (action != null) {
208                                         if (action.Length > 2 && action [0] == '"' && action [action.Length] == '"')
209                                                 action = action.Substring (1, action.Length - 2);
210                                         msg.Headers.Action = action;
211                                 }
212                         }
213
214                         return msg;
215                 }
216
217                 public override bool WaitForRequest (TimeSpan timeout)
218                 {
219                         throw new NotImplementedException ();
220                 }
221         }
222 }