HttpWebResponse.cs 11 KB

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