2 // System.Net.HttpListenerResponse
5 // Gonzalo Paniagua Javier (gonzalo@novell.com)
7 // Copyright (c) 2005 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.
31 using System.Globalization;
34 namespace System.Net {
35 public sealed class HttpListenerResponse : IDisposable
38 Encoding content_encoding;
42 CookieCollection cookies;
43 WebHeaderCollection headers = new WebHeaderCollection ();
44 bool keep_alive = true;
45 ResponseStream output_stream;
46 Version version = HttpVersion.Version11;
48 int status_code = 200;
49 string status_description = "OK";
51 HttpListenerContext context;
53 internal bool HeadersSent;
54 internal object headers_lock = new object ();
56 bool force_close_chunked;
58 internal HttpListenerResponse (HttpListenerContext context)
60 this.context = context;
63 internal bool ForceCloseChunked {
64 get { return force_close_chunked; }
67 public Encoding ContentEncoding {
69 if (content_encoding == null)
70 content_encoding = Encoding.Default;
71 return content_encoding;
75 throw new ObjectDisposedException (GetType ().ToString ());
79 throw new InvalidOperationException ("Cannot be changed after headers are sent.");
81 content_encoding = value;
85 public long ContentLength64 {
86 get { return content_length; }
89 throw new ObjectDisposedException (GetType ().ToString ());
92 throw new InvalidOperationException ("Cannot be changed after headers are sent.");
95 throw new ArgumentOutOfRangeException ("Must be >= 0", "value");
98 content_length = value;
102 public string ContentType {
103 get { return content_type; }
107 throw new ObjectDisposedException (GetType ().ToString ());
110 throw new InvalidOperationException ("Cannot be changed after headers are sent.");
112 content_type = value;
116 // RFC 2109, 2965 + the netscape specification at http://wp.netscape.com/newsref/std/cookie_spec.html
117 public CookieCollection Cookies {
120 cookies = new CookieCollection ();
123 set { cookies = value; } // null allowed?
126 public WebHeaderCollection Headers {
127 get { return headers; }
130 * "If you attempt to set a Content-Length, Keep-Alive, Transfer-Encoding, or
131 * WWW-Authenticate header using the Headers property, an exception will be
132 * thrown. Use the KeepAlive or ContentLength64 properties to set these headers.
133 * You cannot set the Transfer-Encoding or WWW-Authenticate headers manually."
135 // TODO: check if this is marked readonly after headers are sent.
140 public bool KeepAlive {
141 get { return keep_alive; }
144 throw new ObjectDisposedException (GetType ().ToString ());
147 throw new InvalidOperationException ("Cannot be changed after headers are sent.");
153 public Stream OutputStream {
155 if (output_stream == null)
156 output_stream = context.Connection.GetResponseStream ();
157 return output_stream;
161 public Version ProtocolVersion {
162 get { return version; }
165 throw new ObjectDisposedException (GetType ().ToString ());
168 throw new InvalidOperationException ("Cannot be changed after headers are sent.");
171 throw new ArgumentNullException ("value");
173 if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
174 throw new ArgumentException ("Must be 1.0 or 1.1", "value");
177 throw new ObjectDisposedException (GetType ().ToString ());
183 public string RedirectLocation {
184 get { return location; }
187 throw new ObjectDisposedException (GetType ().ToString ());
190 throw new InvalidOperationException ("Cannot be changed after headers are sent.");
196 public bool SendChunked {
197 get { return chunked; }
200 throw new ObjectDisposedException (GetType ().ToString ());
203 throw new InvalidOperationException ("Cannot be changed after headers are sent.");
209 public int StatusCode {
210 get { return status_code; }
213 throw new ObjectDisposedException (GetType ().ToString ());
216 throw new InvalidOperationException ("Cannot be changed after headers are sent.");
218 if (value < 100 || value > 999)
219 throw new ProtocolViolationException ("StatusCode must be between 100 and 999.");
221 status_description = GetStatusDescription (value);
225 internal static string GetStatusDescription (int 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";
278 public string StatusDescription {
279 get { return status_description; }
281 status_description = value;
285 void IDisposable.Dispose ()
287 Close (true); //TODO: Abort or Close?
298 public void AddHeader (string name, string value)
301 throw new ArgumentNullException ("name");
304 throw new ArgumentException ("'name' cannot be empty", "name");
306 //TODO: check for forbidden headers and invalid characters
307 if (value.Length > 65535)
308 throw new ArgumentOutOfRangeException ("value");
310 headers.Set (name, value);
313 public void AppendCookie (Cookie cookie)
316 throw new ArgumentNullException ("cookie");
318 Cookies.Add (cookie);
321 public void AppendHeader (string name, string value)
324 throw new ArgumentNullException ("name");
327 throw new ArgumentException ("'name' cannot be empty", "name");
329 if (value.Length > 65535)
330 throw new ArgumentOutOfRangeException ("value");
332 headers.Add (name, value);
335 void Close (bool force)
338 context.Connection.Close (force);
349 public void Close (byte [] responseEntity, bool willBlock)
354 if (responseEntity == null)
355 throw new ArgumentNullException ("responseEntity");
357 //TODO: if willBlock -> BeginWrite + Close ?
358 ContentLength64 = responseEntity.Length;
359 OutputStream.Write (responseEntity, 0, (int) content_length);
363 public void CopyFrom (HttpListenerResponse templateResponse)
366 headers.Add (templateResponse.headers);
367 content_length = templateResponse.content_length;
368 status_code = templateResponse.status_code;
369 status_description = templateResponse.status_description;
370 keep_alive = templateResponse.keep_alive;
371 version = templateResponse.version;
374 public void Redirect (string url)
376 StatusCode = 302; // Found
380 bool FindCookie (Cookie cookie)
382 string name = cookie.Name;
383 string domain = cookie.Domain;
384 string path = cookie.Path;
385 foreach (Cookie c in cookies) {
388 if (domain != c.Domain)
397 internal void SendHeaders (bool closing, MemoryStream ms)
399 Encoding encoding = content_encoding;
400 if (encoding == null)
401 encoding = Encoding.Default;
403 if (content_type != null) {
404 if (content_encoding != null && content_type.IndexOf ("charset=", StringComparison.Ordinal) == -1) {
405 string enc_name = content_encoding.WebName;
406 headers.SetInternal ("Content-Type", content_type + "; charset=" + enc_name);
408 headers.SetInternal ("Content-Type", content_type);
412 if (headers ["Server"] == null)
413 headers.SetInternal ("Server", "Mono-HTTPAPI/1.0");
415 CultureInfo inv = CultureInfo.InvariantCulture;
416 if (headers ["Date"] == null)
417 headers.SetInternal ("Date", DateTime.UtcNow.ToString ("r", inv));
420 if (!cl_set && closing) {
426 headers.SetInternal ("Content-Length", content_length.ToString (inv));
429 Version v = context.Request.ProtocolVersion;
430 if (!cl_set && !chunked && v >= HttpVersion.Version11)
433 /* Apache forces closing the connection for these status codes:
434 * HttpStatusCode.BadRequest 400
435 * HttpStatusCode.RequestTimeout 408
436 * HttpStatusCode.LengthRequired 411
437 * HttpStatusCode.RequestEntityTooLarge 413
438 * HttpStatusCode.RequestUriTooLong 414
439 * HttpStatusCode.InternalServerError 500
440 * HttpStatusCode.ServiceUnavailable 503
442 bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
443 status_code == 413 || status_code == 414 || status_code == 500 ||
446 if (conn_close == false)
447 conn_close = !context.Request.KeepAlive;
449 // They sent both KeepAlive: true and Connection: close!?
450 if (!keep_alive || conn_close) {
451 headers.SetInternal ("Connection", "close");
456 headers.SetInternal ("Transfer-Encoding", "chunked");
458 int reuses = context.Connection.Reuses;
460 force_close_chunked = true;
462 headers.SetInternal ("Connection", "close");
468 headers.SetInternal ("Keep-Alive", String.Format ("timeout=15,max={0}", 100 - reuses));
469 if (context.Request.ProtocolVersion <= HttpVersion.Version10)
470 headers.SetInternal ("Connection", "keep-alive");
473 if (location != null)
474 headers.SetInternal ("Location", location);
476 if (cookies != null) {
477 foreach (Cookie cookie in cookies)
478 headers.SetInternal ("Set-Cookie", cookie.ToClientString ());
481 StreamWriter writer = new StreamWriter (ms, encoding, 256);
482 writer.Write ("HTTP/{0} {1} {2}\r\n", version, status_code, status_description);
483 string headers_str = headers.ToStringMultiValue ();
484 writer.Write (headers_str);
486 int preamble = (encoding.CodePage == 65001) ? 3 : encoding.GetPreamble ().Length;
487 if (output_stream == null)
488 output_stream = context.Connection.GetResponseStream ();
490 /* Assumes that the ms was at position 0 */
491 ms.Position = preamble;
495 public void SetCookie (Cookie cookie)
498 throw new ArgumentNullException ("cookie");
500 if (cookies != null) {
501 if (FindCookie (cookie))
502 throw new ArgumentException ("The cookie already exists.");
504 cookies = new CookieCollection ();
507 cookies.Add (cookie);