merged Sys.Web.Services 2.0 support in my branch:
[mono.git] / mcs / class / System / System.Net / HttpListenerResponse.cs
1 //
2 // System.Net.HttpListenerResponse
3 //
4 // Author:
5 //      Gonzalo Paniagua Javier (gonzalo@novell.com)
6 //
7 // Copyright (c) 2005 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
29 #if NET_2_0 && SECURITY_DEP
30
31 using System.Globalization;
32 using System.IO;
33 using System.Text;
34 namespace System.Net {
35         public sealed class HttpListenerResponse : IDisposable
36         {
37                 bool disposed;
38                 Encoding content_encoding;
39                 long content_length;
40                 bool cl_set;
41                 string content_type;
42                 CookieCollection cookies;
43                 WebHeaderCollection headers = new WebHeaderCollection ();
44                 bool keep_alive = true;
45                 ResponseStream output_stream;
46                 Version version = HttpVersion.Version11;
47                 string location;
48                 int status_code = 200;
49                 string status_description = "OK";
50                 bool chunked;
51                 HttpListenerContext context;
52                 internal bool HeadersSent;
53                 bool force_close_chunked;
54
55                 internal HttpListenerResponse (HttpListenerContext context)
56                 {
57                         this.context = context;
58                 }
59
60                 internal bool ForceCloseChunked {
61                         get { return force_close_chunked; }
62                 }
63
64                 public Encoding ContentEncoding {
65                         get {
66                                 if (content_encoding == null)
67                                         content_encoding = Encoding.Default;
68                                 return content_encoding;
69                         }
70                         set {
71                                 if (disposed)
72                                         throw new ObjectDisposedException (GetType ().ToString ());
73
74                                 //TODO: is null ok?
75                                 if (HeadersSent)
76                                         throw new InvalidOperationException ("Cannot be changed after headers are sent.");
77                                         
78                                 content_encoding = value;
79                         }
80                 }
81
82                 public long ContentLength64 {
83                         get { return content_length; }
84                         set {
85                                 if (disposed)
86                                         throw new ObjectDisposedException (GetType ().ToString ());
87
88                                 if (HeadersSent)
89                                         throw new InvalidOperationException ("Cannot be changed after headers are sent.");
90
91                                 if (value < 0)
92                                         throw new ArgumentOutOfRangeException ("Must be >= 0", "value");
93
94                                 cl_set = true;
95                                 content_length = value;
96                         }
97                 }
98                 
99                 public string ContentType {
100                         get { return content_type; }
101                         set {
102                                 // TODO: is null ok?
103                                 if (disposed)
104                                         throw new ObjectDisposedException (GetType ().ToString ());
105
106                                 if (HeadersSent)
107                                         throw new InvalidOperationException ("Cannot be changed after headers are sent.");
108
109                                 content_type = value;
110                         }
111                 }
112
113                 // RFC 2109, 2965 + the netscape specification at http://wp.netscape.com/newsref/std/cookie_spec.html
114                 public CookieCollection Cookies {
115                         get {
116                                 if (cookies == null)
117                                         cookies = new CookieCollection ();
118                                 return cookies;
119                         }
120                         set { cookies = value; } // null allowed?
121                 }
122
123                 public WebHeaderCollection Headers {
124                         get { return headers; }
125                         set {
126                 /**
127                  *      "If you attempt to set a Content-Length, Keep-Alive, Transfer-Encoding, or
128                  *      WWW-Authenticate header using the Headers property, an exception will be
129                  *      thrown. Use the KeepAlive or ContentLength64 properties to set these headers.
130                  *      You cannot set the Transfer-Encoding or WWW-Authenticate headers manually."
131                 */
132                 // TODO: check if this is marked readonly after headers are sent.
133                                 headers = value;
134                         }
135                 }
136
137                 public bool KeepAlive {
138                         get { return keep_alive; }
139                         set {
140                                 if (disposed)
141                                         throw new ObjectDisposedException (GetType ().ToString ());
142
143                                 if (HeadersSent)
144                                         throw new InvalidOperationException ("Cannot be changed after headers are sent.");
145                                         
146                                 keep_alive = value;
147                         }
148                 }
149
150                 public Stream OutputStream {
151                         get {
152                                 if (disposed)
153                                         throw new ObjectDisposedException (GetType ().ToString ());
154
155                                 if (output_stream == null)
156                                         output_stream = context.Connection.GetResponseStream ();
157                                 return output_stream;
158                         }
159                 }
160                 
161                 public Version ProtocolVersion {
162                         get { return version; }
163                         set {
164                                 if (disposed)
165                                         throw new ObjectDisposedException (GetType ().ToString ());
166
167                                 if (HeadersSent)
168                                         throw new InvalidOperationException ("Cannot be changed after headers are sent.");
169                                         
170                                 if (value == null)
171                                         throw new ArgumentNullException ("value");
172
173                                 if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
174                                         throw new ArgumentException ("Must be 1.0 or 1.1", "value");
175
176                                 if (disposed)
177                                         throw new ObjectDisposedException (GetType ().ToString ());
178
179                                 version = value;
180                         }
181                 }
182
183                 public string RedirectLocation {
184                         get { return location; }
185                         set {
186                                 if (disposed)
187                                         throw new ObjectDisposedException (GetType ().ToString ());
188
189                                 if (HeadersSent)
190                                         throw new InvalidOperationException ("Cannot be changed after headers are sent.");
191                                         
192                                 location = value;
193                         }
194                 }
195
196                 public bool SendChunked {
197                         get { return chunked; }
198                         set {
199                                 if (disposed)
200                                         throw new ObjectDisposedException (GetType ().ToString ());
201
202                                 if (HeadersSent)
203                                         throw new InvalidOperationException ("Cannot be changed after headers are sent.");
204                                         
205                                 chunked = value;
206                         }
207                 }
208
209                 public int StatusCode {
210                         get { return status_code; }
211                         set {
212                                 if (disposed)
213                                         throw new ObjectDisposedException (GetType ().ToString ());
214
215                                 if (HeadersSent)
216                                         throw new InvalidOperationException ("Cannot be changed after headers are sent.");
217                                         
218                                 if (value < 100 || value > 999)
219                                         throw new ProtocolViolationException ("StatusCode must be between 100 and 999.");
220                                 status_code = value;
221                                 status_description = GetStatusDescription (value);
222                         }
223                 }
224
225                 internal static string GetStatusDescription (int code)
226                 {
227                         switch (code){
228                         case 100: return "Continue";
229                         case 101: return "Switching Protocols";
230                         case 102: return "Processing";
231                         case 200: return "OK";
232                         case 201: return "Created";
233                         case 202: return "Accepted";
234                         case 203: return "Non-Authoritative Information";
235                         case 204: return "No Content";
236                         case 205: return "Reset Content";
237                         case 206: return "Partial Content";
238                         case 207: return "Multi-Status";
239                         case 300: return "Multiple Choices";
240                         case 301: return "Moved Permanently";
241                         case 302: return "Found";
242                         case 303: return "See Other";
243                         case 304: return "Not Modified";
244                         case 305: return "Use Proxy";
245                         case 307: return "Temporary Redirect";
246                         case 400: return "Bad Request";
247                         case 401: return "Unauthorized";
248                         case 402: return "Payment Required";
249                         case 403: return "Forbidden";
250                         case 404: return "Not Found";
251                         case 405: return "Method Not Allowed";
252                         case 406: return "Not Acceptable";
253                         case 407: return "Proxy Authentication Required";
254                         case 408: return "Request Timeout";
255                         case 409: return "Conflict";
256                         case 410: return "Gone";
257                         case 411: return "Length Required";
258                         case 412: return "Precondition Failed";
259                         case 413: return "Request Entity Too Large";
260                         case 414: return "Request-Uri Too Long";
261                         case 415: return "Unsupported Media Type";
262                         case 416: return "Requested Range Not Satisfiable";
263                         case 417: return "Expectation Failed";
264                         case 422: return "Unprocessable Entity";
265                         case 423: return "Locked";
266                         case 424: return "Failed Dependency";
267                         case 500: return "Internal Server Error";
268                         case 501: return "Not Implemented";
269                         case 502: return "Bad Gateway";
270                         case 503: return "Service Unavailable";
271                         case 504: return "Gateway Timeout";
272                         case 505: return "Http Version Not Supported";
273                         case 507: return "Insufficient Storage";
274                         }
275                         return "";
276                 }
277
278                 public string StatusDescription {
279                         get { return status_description; }
280                         set {
281                                 status_description = value;
282                         }
283                 }
284
285                 void IDisposable.Dispose ()
286                 {
287                         Close (true); //TODO: Abort or Close?
288                 }
289
290                 public void Abort ()
291                 {
292                         if (disposed)
293                                 return;
294
295                         Close (true);
296                 }
297
298                 public void AddHeader (string name, string value)
299                 {
300                         if (name == null)
301                                 throw new ArgumentNullException ("name");
302
303                         if (name == "")
304                                 throw new ArgumentException ("'name' cannot be empty", "name");
305                         
306                         //TODO: check for forbidden headers and invalid characters
307                         if (value.Length > 65535)
308                                 throw new ArgumentOutOfRangeException ("value");
309
310                         headers.Set (name, value);
311                 }
312
313                 public void AppendCookie (Cookie cookie)
314                 {
315                         if (cookie == null)
316                                 throw new ArgumentNullException ("cookie");
317                         
318                         cookies.Add (cookie);
319                 }
320
321                 public void AppendHeader (string name, string value)
322                 {
323                         if (name == null)
324                                 throw new ArgumentNullException ("name");
325
326                         if (name == "")
327                                 throw new ArgumentException ("'name' cannot be empty", "name");
328                         
329                         if (value.Length > 65535)
330                                 throw new ArgumentOutOfRangeException ("value");
331
332                         headers.Add (name, value);
333                 }
334
335                 void Close (bool force)
336                 {
337                         // TODO: use the 'force' argument
338                         context.Connection.Close ();
339                         disposed = true;
340                 }
341
342                 public void Close ()
343                 {
344                         if (disposed)
345                                 return;
346
347                         Close (false);
348                 }
349
350                 public void Close (byte [] responseEntity, bool willBlock)
351                 {
352                         if (disposed)
353                                 return;
354
355                         if (responseEntity == null)
356                                 throw new ArgumentNullException ("responseEntity");
357
358                         //TODO: if willBlock -> BeginWrite + Close ?
359                         ContentLength64 = responseEntity.Length;
360                         OutputStream.Write (responseEntity, 0, (int) content_length);
361                         Close (false);
362                 }
363
364                 public void CopyFrom (HttpListenerResponse templateResponse)
365                 {
366                         headers.Clear ();
367                         headers.Add (templateResponse.headers);
368                         content_length = templateResponse.content_length;
369                         status_code = templateResponse.status_code;
370                         status_description = templateResponse.status_description;
371                         keep_alive = templateResponse.keep_alive;
372                         version = templateResponse.version;
373                 }
374
375                 public void Redirect (string url)
376                 {
377                         StatusCode = 302; // Found
378                         location = url;
379                 }
380
381                 bool FindCookie (Cookie cookie)
382                 {
383                         string name = cookie.Name;
384                         string domain = cookie.Domain;
385                         string path = cookie.Path;
386                         foreach (Cookie c in cookies) {
387                                 if (name != c.Name)
388                                         continue;
389                                 if (domain != c.Domain)
390                                         continue;
391                                 if (path == c.Path)
392                                         return true;
393                         }
394
395                         return false;
396                 }
397
398                 internal void SendHeaders (bool closing)
399                 {
400                         //TODO: When do we send KeepAlive?
401                         //TODO: send cookies
402                         MemoryStream ms = new MemoryStream ();
403                         Encoding encoding = content_encoding;
404                         if (encoding == null)
405                                 encoding = Encoding.Default;
406
407                         if (content_type != null) {
408                                 if (content_encoding != null && content_type.IndexOf ("charset=") == -1) {
409                                         string enc_name = content_encoding.WebName;
410                                         headers.SetInternal ("Content-Type", content_type + "; charset=" + enc_name);
411                                 } else {
412                                         headers.SetInternal ("Content-Type", content_type);
413                                 }
414                         }
415
416                         if (headers ["Server"] == null)
417                                 headers.SetInternal ("Server", "Mono-HTTPAPI/1.0");
418
419                         CultureInfo inv = CultureInfo.InvariantCulture;
420                         if (headers ["Date"] == null)
421                                 headers.SetInternal ("Date", DateTime.UtcNow.ToString ("r", inv));
422
423                         if (!chunked) {
424                                 if (!cl_set && closing) {
425                                         cl_set = true;
426                                         content_length = 0;
427                                 }
428
429                                 if (cl_set)
430                                         headers.SetInternal ("Content-Length", content_length.ToString (inv));
431                         }
432
433                         Version v = context.Request.ProtocolVersion;
434                         if (!cl_set && !chunked && v >= HttpVersion.Version11)
435                                 chunked = true;
436                                 
437                         /* Apache forces closing the connection for these status codes:
438                          *      HttpStatusCode.BadRequest               400
439                          *      HttpStatusCode.RequestTimeout           408
440                          *      HttpStatusCode.LengthRequired           411
441                          *      HttpStatusCode.RequestEntityTooLarge    413
442                          *      HttpStatusCode.RequestUriTooLong        414
443                          *      HttpStatusCode.InternalServerError      500
444                          *      HttpStatusCode.ServiceUnavailable       503
445                          */
446                         bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
447                                         status_code == 413 || status_code == 414 || status_code == 500 ||
448                                         status_code == 503);
449
450                         if (conn_close == false)
451                                 conn_close = (context.Request.Headers ["connection"] == "close");
452
453                         // They sent both KeepAlive: true and Connection: close!?
454                         if (!chunked || conn_close)
455                                 headers.SetInternal ("Connection", "close");
456
457                         if (chunked)
458                                 headers.SetInternal ("Transfer-Encoding", "chunked");
459
460                         int chunked_uses = context.Connection.ChunkedUses;
461                         if (chunked_uses >= 100) {
462                                 force_close_chunked = true;
463                                 if (!conn_close)
464                                         headers.SetInternal ("Connection", "close");
465                         }
466
467                         if (location != null)
468                                 headers.SetInternal ("Location", location);
469
470                         StreamWriter writer = new StreamWriter (ms, encoding);
471                         writer.Write ("HTTP/{0} {1} {2}\r\n", version, status_code, status_description);
472                         string headers_str = headers.ToString ();
473                         writer.Write (headers_str);
474                         writer.Flush ();
475                         // Perf.: use TCP_CORK if we're writing more?
476                         int preamble = encoding.GetPreamble ().Length;
477                         if (output_stream == null)
478                                 output_stream = context.Connection.GetResponseStream ();
479
480                         output_stream.InternalWrite (ms.GetBuffer (), 0 + preamble, (int) ms.Length - preamble);
481                         HeadersSent = true;
482                 }
483
484                 public void SetCookie (Cookie cookie)
485                 {
486                         if (cookie == null)
487                                 throw new ArgumentNullException ("cookie");
488
489                         if (cookies != null) {
490                                 if (FindCookie (cookie))
491                                         throw new ArgumentException ("The cookie already exists.");
492                         } else {
493                                 cookies = new CookieCollection ();
494                         }
495
496                         cookies.Add (cookie);
497                 }
498         }
499 }
500 #endif
501