HttpWebResponse.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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 cookieContainer;
  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.cookieContainer = container;
  67. FillCookies ();
  68. } else if (webHeaders != null) {
  69. webHeaders.RemoveInternal ("Set-Cookie");
  70. webHeaders.RemoveInternal ("Set-Cookie2");
  71. }
  72. }
  73. protected HttpWebResponse (SerializationInfo serializationInfo, StreamingContext streamingContext)
  74. {
  75. SerializationInfo info = serializationInfo;
  76. uri = (Uri) info.GetValue ("uri", typeof (Uri));
  77. contentLength = info.GetInt64 ("contentLength");
  78. contentType = info.GetString ("contentType");
  79. method = info.GetString ("method");
  80. statusDescription = info.GetString ("statusDescription");
  81. cookieCollection = (CookieCollection) info.GetValue ("cookieCollection", typeof (CookieCollection));
  82. version = (Version) info.GetValue ("version", typeof (Version));
  83. statusCode = (HttpStatusCode) info.GetValue ("statusCode", typeof (HttpStatusCode));
  84. }
  85. // Properties
  86. public string CharacterSet {
  87. // Content-Type = "Content-Type" ":" media-type
  88. // media-type = type "/" subtype *( ";" parameter )
  89. // parameter = attribute "=" value
  90. // 3.7.1. default is ISO-8859-1
  91. get {
  92. CheckDisposed ();
  93. string contentType = ContentType;
  94. if (contentType == null)
  95. return "ISO-8859-1";
  96. string val = contentType.ToLower ();
  97. int pos = val.IndexOf ("charset=");
  98. if (pos == -1)
  99. return "ISO-8859-1";
  100. pos += 8;
  101. int pos2 = val.IndexOf (';', pos);
  102. return (pos2 == -1)
  103. ? contentType.Substring (pos)
  104. : contentType.Substring (pos, pos2 - pos);
  105. }
  106. }
  107. public string ContentEncoding {
  108. get {
  109. CheckDisposed ();
  110. return webHeaders ["Content-Encoding"];
  111. }
  112. }
  113. public override long ContentLength {
  114. get {
  115. CheckDisposed ();
  116. if (contentLength != -1)
  117. return contentLength;
  118. try {
  119. contentLength = (long) UInt64.Parse (webHeaders ["Content-Length"]);
  120. } catch (Exception) {
  121. return -1;
  122. }
  123. return contentLength;
  124. }
  125. }
  126. public override string ContentType {
  127. get {
  128. CheckDisposed ();
  129. if (contentType == null)
  130. contentType = webHeaders ["Content-Type"];
  131. return contentType;
  132. }
  133. }
  134. public CookieCollection Cookies {
  135. get {
  136. CheckDisposed ();
  137. if (cookieCollection == null)
  138. cookieCollection = new CookieCollection ();
  139. return cookieCollection;
  140. }
  141. set {
  142. CheckDisposed ();
  143. cookieCollection = value;
  144. }
  145. }
  146. public override WebHeaderCollection Headers {
  147. get {
  148. CheckDisposed ();
  149. return webHeaders;
  150. }
  151. }
  152. public DateTime LastModified {
  153. get {
  154. CheckDisposed ();
  155. try {
  156. string dtStr = webHeaders ["Last-Modified"];
  157. return MonoHttpDate.Parse (dtStr);
  158. } catch (Exception) {
  159. return DateTime.Now;
  160. }
  161. }
  162. }
  163. public string Method {
  164. get {
  165. CheckDisposed ();
  166. return method;
  167. }
  168. }
  169. public Version ProtocolVersion {
  170. get {
  171. CheckDisposed ();
  172. return version;
  173. }
  174. }
  175. public override Uri ResponseUri {
  176. get {
  177. CheckDisposed ();
  178. return uri;
  179. }
  180. }
  181. public string Server {
  182. get {
  183. CheckDisposed ();
  184. return webHeaders ["Server"];
  185. }
  186. }
  187. public HttpStatusCode StatusCode {
  188. get {
  189. CheckDisposed ();
  190. return statusCode;
  191. }
  192. }
  193. public string StatusDescription {
  194. get {
  195. CheckDisposed ();
  196. return statusDescription;
  197. }
  198. }
  199. // Methods
  200. public override int GetHashCode ()
  201. {
  202. CheckDisposed ();
  203. return base.GetHashCode ();
  204. }
  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. protected virtual void Dispose (bool disposing)
  253. {
  254. if (this.disposed)
  255. return;
  256. this.disposed = true;
  257. if (disposing) {
  258. // release managed resources
  259. uri = null;
  260. webHeaders = null;
  261. cookieCollection = null;
  262. method = null;
  263. version = null;
  264. statusDescription = null;
  265. }
  266. // release unmanaged resources
  267. Stream st = stream;
  268. stream = null;
  269. if (st != null)
  270. st.Close ();
  271. }
  272. private void CheckDisposed ()
  273. {
  274. if (disposed)
  275. throw new ObjectDisposedException (GetType ().FullName);
  276. }
  277. void FillCookies ()
  278. {
  279. if (webHeaders == null)
  280. return;
  281. string [] values = webHeaders.GetValues ("Set-Cookie");
  282. if (values != null) {
  283. foreach (string va in values)
  284. SetCookie (va);
  285. }
  286. values = webHeaders.GetValues ("Set-Cookie2");
  287. if (values != null) {
  288. foreach (string va in values)
  289. SetCookie2 (va);
  290. }
  291. }
  292. void SetCookie (string header)
  293. {
  294. string name, val;
  295. Cookie cookie = null;
  296. CookieParser parser = new CookieParser (header);
  297. while (parser.GetNextNameValue (out name, out val)) {
  298. if (name == null || name == "")
  299. continue;
  300. if (cookie == null) {
  301. cookie = new Cookie (name, val);
  302. continue;
  303. }
  304. name = name.ToUpper ();
  305. switch (name) {
  306. case "COMMENT":
  307. if (cookie.Comment == null)
  308. cookie.Comment = val;
  309. break;
  310. case "COMMENTURL":
  311. if (cookie.CommentUri == null)
  312. cookie.CommentUri = new Uri (val);
  313. break;
  314. case "DISCARD":
  315. cookie.Discard = true;
  316. break;
  317. case "DOMAIN":
  318. if (cookie.Domain == "")
  319. cookie.Domain = val;
  320. break;
  321. case "MAX-AGE": // RFC Style Set-Cookie2
  322. if (cookie.Expires == DateTime.MinValue)
  323. cookie.Expires = cookie.TimeStamp.AddSeconds (Int32.Parse (val));
  324. break;
  325. case "EXPIRES": // Netscape Style Set-Cookie
  326. if (cookie.Expires != DateTime.MinValue)
  327. break;
  328. try {
  329. cookie.Expires = DateTime.ParseExact (val, "r", CultureInfo.InvariantCulture);
  330. } catch {
  331. try {
  332. cookie.Expires = DateTime.ParseExact (val,
  333. "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'",
  334. CultureInfo.InvariantCulture);
  335. } catch {
  336. cookie.Expires = DateTime.Now.AddDays (1);
  337. }
  338. }
  339. break;
  340. case "PATH":
  341. cookie.Path = val;
  342. break;
  343. case "PORT":
  344. if (cookie.Port == null)
  345. cookie.Port = val;
  346. break;
  347. case "SECURE":
  348. cookie.Secure = true;
  349. break;
  350. case "VERSION":
  351. cookie.Version = Int32.Parse (val);
  352. break;
  353. }
  354. }
  355. if (cookieCollection == null)
  356. cookieCollection = new CookieCollection ();
  357. if (cookie.Domain == "")
  358. cookie.Domain = uri.Host;
  359. cookieCollection.Add (cookie);
  360. if (cookieContainer != null)
  361. cookieContainer.Add (uri, cookie);
  362. }
  363. void SetCookie2 (string cookies_str)
  364. {
  365. string [] cookies = cookies_str.Split (',');
  366. foreach (string cookie_str in cookies)
  367. SetCookie (cookie_str);
  368. }
  369. }
  370. class CookieParser {
  371. string header;
  372. int pos;
  373. int length;
  374. public CookieParser (string header) : this (header, 0)
  375. {
  376. }
  377. public CookieParser (string header, int position)
  378. {
  379. this.header = header;
  380. this.pos = position;
  381. this.length = header.Length;
  382. }
  383. public bool GetNextNameValue (out string name, out string val)
  384. {
  385. name = null;
  386. val = null;
  387. if (pos >= length)
  388. return false;
  389. name = GetCookieName ();
  390. if (header [pos] == '=') {
  391. pos++;
  392. val = GetCookieValue ();
  393. if (pos < length && header [pos] == ';')
  394. pos++;
  395. }
  396. return true;
  397. }
  398. string GetCookieName ()
  399. {
  400. int k = pos;
  401. while (k < length && Char.IsWhiteSpace (header [k]))
  402. k++;
  403. int begin = k;
  404. while (k < length && header [k] != ';' && header [k] != '=')
  405. k++;
  406. pos = k;
  407. return header.Substring (begin, k - begin).Trim ();
  408. }
  409. string GetCookieValue ()
  410. {
  411. if (pos >= length)
  412. return null;
  413. int k = pos;
  414. while (k < length && Char.IsWhiteSpace (header [k]))
  415. k++;
  416. int begin;
  417. if (header [k] == '"'){
  418. int j;
  419. begin = ++k;
  420. while (k < length && header [k] != '"')
  421. k++;
  422. for (j = k; j < length && header [j] != ';'; j++)
  423. ;
  424. pos = j;
  425. } else {
  426. begin = k;
  427. while (k < length && header [k] != ';')
  428. k++;
  429. pos = k;
  430. }
  431. return header.Substring (begin, k - begin).Trim ();
  432. }
  433. }
  434. }