2004-11-01 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / class / System / System.Net / HttpWebResponse.cs
1 //
2 // System.Net.HttpWebResponse
3 //
4 // Authors:
5 //      Lawrence Pit (loz@cable.a2000.nl)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
8 // (c) 2002 Lawrence Pit
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
10 //
11
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32
33 using System;
34 using System.Globalization;
35 using System.IO;
36 using System.Net.Sockets;
37 using System.Runtime.Serialization;
38 using System.Text;
39
40 namespace System.Net 
41 {
42         [Serializable]
43         public class HttpWebResponse : WebResponse, ISerializable, IDisposable
44         {
45                 Uri uri;
46                 WebHeaderCollection webHeaders;
47                 CookieCollection cookieCollection;
48                 string method;
49                 Version version;
50                 HttpStatusCode statusCode;
51                 string statusDescription;
52                 long contentLength = -1;
53                 string contentType;
54
55                 bool disposed = false;
56                 Stream stream;
57                 
58                 // Constructors
59                 
60                 internal HttpWebResponse (Uri uri, string method, WebConnectionData data, bool cookiesSet)
61                 {
62                         this.uri = uri;
63                         this.method = method;
64                         webHeaders = data.Headers;
65                         version = data.Version;
66                         statusCode = (HttpStatusCode) data.StatusCode;
67                         statusDescription = data.StatusDescription;
68                         stream = data.stream;
69                         if (cookiesSet) {
70                                 FillCookies ();
71                         } else if (webHeaders != null) {
72                                 webHeaders.RemoveInternal ("Set-Cookie");
73                                 webHeaders.RemoveInternal ("Set-Cookie2");
74                         }
75                 }
76
77                 protected HttpWebResponse (SerializationInfo serializationInfo, StreamingContext streamingContext)
78                 {
79                         SerializationInfo info = serializationInfo;
80
81                         uri = (Uri) info.GetValue ("uri", typeof (Uri));
82                         contentLength = info.GetInt64 ("contentLength");
83                         contentType = info.GetString ("contentType");
84                         method = info.GetString ("method");
85                         statusDescription = info.GetString ("statusDescription");
86                         cookieCollection = (CookieCollection) info.GetValue ("cookieCollection", typeof (CookieCollection));
87                         version = (Version) info.GetValue ("version", typeof (Version));
88                         statusCode = (HttpStatusCode) info.GetValue ("statusCode", typeof (HttpStatusCode));
89                 }
90                 
91                 // Properties
92                 
93                 public string CharacterSet {
94                         // Content-Type   = "Content-Type" ":" media-type
95                         // media-type     = type "/" subtype *( ";" parameter )
96                         // parameter      = attribute "=" value
97                         // 3.7.1. default is ISO-8859-1
98                         get { 
99                                 CheckDisposed ();
100                                 string contentType = ContentType;
101                                 if (contentType == null)
102                                         return "ISO-8859-1";
103                                 string val = contentType.ToLower ();                                    
104                                 int pos = val.IndexOf ("charset=");
105                                 if (pos == -1)
106                                         return "ISO-8859-1";
107                                 pos += 8;
108                                 int pos2 = val.IndexOf (';', pos);
109                                 return (pos2 == -1)
110                                      ? contentType.Substring (pos) 
111                                      : contentType.Substring (pos, pos2 - pos);
112                         }
113                 }
114                 
115                 public string ContentEncoding {
116                         get { 
117                                 CheckDisposed ();
118                                 return webHeaders ["Content-Encoding"];
119                         }
120                 }
121                 
122                 public override long ContentLength {            
123                         get {
124                                 CheckDisposed ();
125                                 if (contentLength != -1)
126                                         return contentLength;
127
128                                 try {
129                                         contentLength = (long) UInt64.Parse (webHeaders ["Content-Length"]); 
130                                 } catch (Exception) {
131                                         return -1;
132                                 }
133
134                                 return contentLength;
135                         }
136                 }
137                 
138                 public override string ContentType {            
139                         get {
140                                 CheckDisposed ();
141                                 if (contentType == null)
142                                         contentType = webHeaders ["Content-Type"];
143
144                                 return contentType;
145                         }
146                 }
147                 
148                 public CookieCollection Cookies {
149                         get { 
150                                 CheckDisposed ();
151                                 
152                                 if (cookieCollection == null)
153                                         cookieCollection = new CookieCollection ();
154                                 return cookieCollection;
155                         }
156                         set {
157                                 CheckDisposed ();
158                                 cookieCollection = value;
159                         }
160                 }
161                 
162                 public override WebHeaderCollection Headers {           
163                         get { 
164                                 CheckDisposed ();
165                                 return webHeaders; 
166                         }
167                 }
168                 
169                 public DateTime LastModified {
170                         get {
171                                 CheckDisposed ();
172                                 try {
173                                         string dtStr = webHeaders ["Last-Modified"];
174                                         return MonoHttpDate.Parse (dtStr);
175                                 } catch (Exception) {
176                                         return DateTime.Now;    
177                                 }
178                         }
179                 }
180                 
181                 public string Method {
182                         get { 
183                                 CheckDisposed ();
184                                 return method; 
185                         }
186                 }
187                 
188                 public Version ProtocolVersion {
189                         get { 
190                                 CheckDisposed ();
191                                 return version; 
192                         }
193                 }
194                 
195                 public override Uri ResponseUri {               
196                         get { 
197                                 CheckDisposed ();
198                                 return uri; 
199                         }
200                 }               
201                 
202                 public string Server {
203                         get { 
204                                 CheckDisposed ();
205                                 return webHeaders ["Server"]; 
206                         }
207                 }
208                 
209                 public HttpStatusCode StatusCode {
210                         get { 
211                                 CheckDisposed ();
212                                 return statusCode; 
213                         }
214                 }
215                 
216                 public string StatusDescription {
217                         get { 
218                                 CheckDisposed ();
219                                 return statusDescription; 
220                         }
221                 }
222
223                 // Methods
224                 
225                 public override int GetHashCode ()
226                 {
227                         CheckDisposed ();
228                         return base.GetHashCode ();
229                 }
230                 
231                 public string GetResponseHeader (string headerName)
232                 {
233                         CheckDisposed ();
234                         string value = webHeaders [headerName];
235                         return (value != null) ? value : "";
236                 }
237                 
238                 public override Stream GetResponseStream ()
239                 {
240                         CheckDisposed ();
241                         if (stream == null)
242                                 return Stream.Null;  
243                         if (0 == String.Compare (method, "HEAD", true)) // see par 4.3 & 9.4
244                                 return Stream.Null;  
245
246                         return stream;
247                 }
248                 
249                 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
250                                                   StreamingContext streamingContext)
251                 {
252                         SerializationInfo info = serializationInfo;
253
254                         info.AddValue ("uri", uri);
255                         info.AddValue ("contentLength", contentLength);
256                         info.AddValue ("contentType", contentType);
257                         info.AddValue ("method", method);
258                         info.AddValue ("statusDescription", statusDescription);
259                         info.AddValue ("cookieCollection", cookieCollection);
260                         info.AddValue ("version", version);
261                         info.AddValue ("statusCode", statusCode);
262                 }               
263
264
265                 // Cleaning up stuff
266
267                 public override void Close ()
268                 {
269                         ((IDisposable) this).Dispose ();
270                 }
271                 
272                 void IDisposable.Dispose ()
273                 {
274                         Dispose (true);
275                         GC.SuppressFinalize (this);  
276                 }
277                 
278                 protected virtual void Dispose (bool disposing) 
279                 {
280                         if (this.disposed)
281                                 return;
282                         this.disposed = true;
283                         
284                         if (disposing) {
285                                 // release managed resources
286                                 uri = null;
287                                 webHeaders = null;
288                                 cookieCollection = null;
289                                 method = null;
290                                 version = null;
291                                 statusDescription = null;
292                         }
293                         
294                         // release unmanaged resources
295                         Stream st = stream;
296                         stream = null;
297                         if (st != null) {
298                                 WebConnectionStream wce = st as WebConnectionStream;
299                                 if (wce != null) {
300                                         try {
301                                                 wce.ReadAll ();
302                                         } catch {}
303                                 }
304                                 st.Close ();
305                         }
306                 }
307                 
308                 private void CheckDisposed () 
309                 {
310                         if (disposed)
311                                 throw new ObjectDisposedException (GetType ().FullName);
312                 }
313
314                 void FillCookies ()
315                 {
316                         if (webHeaders == null)
317                                 return;
318
319                         string [] values = webHeaders.GetValues ("Set-Cookie");
320                         if (values != null) {
321                                 foreach (string va in values)
322                                         SetCookie (va);
323                         }
324
325                         values = webHeaders.GetValues ("Set-Cookie2");
326                         if (values != null) {
327                                 foreach (string va in values)
328                                         SetCookie2 (va);
329                         }
330                 }
331                 
332                 void SetCookie (string header)
333                 {
334                         string [] name_values = header.Trim ().Split (';');
335                         int length = name_values.Length;
336                         Cookie cookie = null;
337                         int pos;
338                         for (int i = 0; i < length; i++) {
339                                 pos = 0;
340                                 string name_value = name_values [i].Trim ();
341                                 if (name_value == "")
342                                         continue;
343
344                                 string name = GetCookieName (name_value, name_value.Length, ref pos);
345                                 string value = GetCookieValue (name_value, name_value.Length, ref pos);
346                                 if (cookie == null) {
347                                         cookie = new Cookie (name, value);
348                                         continue;
349                                 }
350
351                                 name = name.ToUpper ();
352                                 switch (name) {
353                                 case "COMMENT":
354                                         if (cookie.Comment == null)
355                                                 cookie.Comment = value;
356                                         break;
357                                 case "COMMENTURL":
358                                         if (cookie.CommentUri == null)
359                                                 cookie.CommentUri = new Uri (value);
360                                         break;
361                                 case "DISCARD":
362                                         cookie.Discard = true;
363                                         break;
364                                 case "DOMAIN":
365                                         if (cookie.Domain == "")
366                                                 cookie.Domain = value;
367                                         break;
368                                 case "MAX-AGE": // RFC Style Set-Cookie2
369                                         if (cookie.Expires == DateTime.MinValue)
370                                                 cookie.Expires = cookie.TimeStamp.AddSeconds (Int32.Parse (value));
371                                         break;
372                                 case "EXPIRES": // Netscape Style Set-Cookie
373                                         if (cookie.Expires != DateTime.MinValue)
374                                                 break;
375                                         try {
376                                                 cookie.Expires = DateTime.ParseExact (value, "r", CultureInfo.InvariantCulture);
377                                         } catch {
378                                                 try { 
379                                                 cookie.Expires = DateTime.ParseExact (value,
380                                                                 "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'",
381                                                                 CultureInfo.InvariantCulture);
382                                                 } catch {
383                                                         cookie.Expires = DateTime.Now.AddDays (1);
384                                                 }
385                                         }
386                                         break;
387                                 case "PATH":
388                                         cookie.Path = value;
389                                         break;
390                                 case "PORT":
391                                         if (cookie.Port == null)
392                                                 cookie.Port = value;
393                                         break;
394                                 case "SECURE":
395                                         cookie.Secure = true;
396                                         break;
397                                 case "VERSION":
398                                         cookie.Version = Int32.Parse (value);
399                                         break;
400                                 }
401                         }
402
403                         if (cookieCollection == null)
404                                 cookieCollection = new CookieCollection ();
405
406                         if (cookie.Domain == "")
407                                 cookie.Domain = uri.Host;
408
409                         cookieCollection.Add (cookie);
410                 }
411
412                 void SetCookie2 (string cookies_str)
413                 {
414                         string [] cookies = cookies_str.Split (',');
415         
416                         foreach (string cookie_str in cookies)
417                                 SetCookie (cookie_str);
418                 }
419
420                 static string GetCookieValue (string str, int length, ref int i)
421                 {
422                         if (i >= length)
423                                 return null;
424
425                         int k = i;
426                         while (k < length && Char.IsWhiteSpace (str [k]))
427                                 k++;
428
429                         int begin = k;
430                         while (k < length && str [k] != ';')
431                                 k++;
432
433                         i = k;
434                         return str.Substring (begin, i - begin).Trim ();
435                 }
436
437                 static string GetCookieName (string str, int length, ref int i)
438                 {
439                         if (i >= length)
440                                 return null;
441
442                         int k = i;
443                         while (k < length && Char.IsWhiteSpace (str [k]))
444                                 k++;
445
446                         int begin = k;
447                         while (k < length && str [k] != ';' &&  str [k] != '=')
448                                 k++;
449
450                         i = k + 1;
451                         return str.Substring (begin, k - begin).Trim ();
452                 }
453         }       
454 }
455