HttpWebRequest.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  1. //
  2. // System.Net.HttpWebRequest
  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. // (c) 2004 Novell, Inc. (http://www.novell.com)
  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. using System;
  33. using System.Collections;
  34. using System.Configuration;
  35. using System.IO;
  36. using System.Net.Sockets;
  37. using System.Runtime.Remoting.Messaging;
  38. using System.Runtime.Serialization;
  39. using System.Security.Cryptography.X509Certificates;
  40. using System.Text;
  41. using System.Threading;
  42. #if NET_2_0
  43. using System.Net.Cache;
  44. #endif
  45. namespace System.Net
  46. {
  47. [Serializable]
  48. public class HttpWebRequest : WebRequest, ISerializable
  49. {
  50. Uri requestUri;
  51. Uri actualUri;
  52. bool hostChanged;
  53. bool allowAutoRedirect = true;
  54. bool allowBuffering = true;
  55. X509CertificateCollection certificates;
  56. string connectionGroup;
  57. long contentLength = -1;
  58. HttpContinueDelegate continueDelegate;
  59. CookieContainer cookieContainer;
  60. ICredentials credentials;
  61. bool haveResponse;
  62. bool haveRequest;
  63. bool requestSent;
  64. WebHeaderCollection webHeaders = new WebHeaderCollection (true);
  65. bool keepAlive = true;
  66. int maxAutoRedirect = 50;
  67. string mediaType = String.Empty;
  68. string method = "GET";
  69. string initialMethod = "GET";
  70. bool pipelined = true;
  71. bool preAuthenticate;
  72. bool usedPreAuth;
  73. Version version = HttpVersion.Version11;
  74. Version actualVersion;
  75. IWebProxy proxy;
  76. bool sendChunked;
  77. ServicePoint servicePoint;
  78. int timeout = 100000;
  79. WebConnectionStream writeStream;
  80. HttpWebResponse webResponse;
  81. WebAsyncResult asyncWrite;
  82. WebAsyncResult asyncRead;
  83. EventHandler abortHandler;
  84. bool aborted;
  85. bool gotRequestStream;
  86. int redirects;
  87. bool expectContinue;
  88. bool authCompleted;
  89. byte[] bodyBuffer;
  90. int bodyBufferLength;
  91. bool getResponseCalled;
  92. Exception saved_exc;
  93. object locker = new object ();
  94. bool is_ntlm_auth;
  95. bool finished_reading;
  96. #if NET_2_0
  97. DecompressionMethods auto_decomp;
  98. #endif
  99. #if NET_1_1
  100. int maxResponseHeadersLength;
  101. static int defaultMaxResponseHeadersLength;
  102. int readWriteTimeout = 300000; // ms
  103. // Constructors
  104. static HttpWebRequest ()
  105. {
  106. NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
  107. defaultMaxResponseHeadersLength = 64 * 1024;
  108. if (config != null) {
  109. int x = config.MaxResponseHeadersLength;
  110. if (x != -1)
  111. x *= 64;
  112. defaultMaxResponseHeadersLength = x;
  113. }
  114. }
  115. #endif
  116. #if NET_2_1
  117. public
  118. #else
  119. internal
  120. #endif
  121. HttpWebRequest (Uri uri)
  122. {
  123. this.requestUri = uri;
  124. this.actualUri = uri;
  125. this.proxy = GlobalProxySelection.Select;
  126. }
  127. #if NET_2_0
  128. [Obsolete ("Serialization is obsoleted for this type", false)]
  129. #endif
  130. protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
  131. {
  132. SerializationInfo info = serializationInfo;
  133. requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
  134. actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
  135. allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
  136. allowBuffering = info.GetBoolean ("allowBuffering");
  137. certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
  138. connectionGroup = info.GetString ("connectionGroup");
  139. contentLength = info.GetInt64 ("contentLength");
  140. webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
  141. keepAlive = info.GetBoolean ("keepAlive");
  142. maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
  143. mediaType = info.GetString ("mediaType");
  144. method = info.GetString ("method");
  145. initialMethod = info.GetString ("initialMethod");
  146. pipelined = info.GetBoolean ("pipelined");
  147. version = (Version) info.GetValue ("version", typeof (Version));
  148. proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
  149. sendChunked = info.GetBoolean ("sendChunked");
  150. timeout = info.GetInt32 ("timeout");
  151. redirects = info.GetInt32 ("redirects");
  152. }
  153. // Properties
  154. internal bool UsesNtlmAuthentication {
  155. get { return is_ntlm_auth; }
  156. }
  157. public string Accept {
  158. get { return webHeaders ["Accept"]; }
  159. set {
  160. CheckRequestStarted ();
  161. webHeaders.RemoveAndAdd ("Accept", value);
  162. }
  163. }
  164. public Uri Address {
  165. get { return actualUri; }
  166. }
  167. public bool AllowAutoRedirect {
  168. get { return allowAutoRedirect; }
  169. set { this.allowAutoRedirect = value; }
  170. }
  171. public bool AllowWriteStreamBuffering {
  172. get { return allowBuffering; }
  173. set { allowBuffering = value; }
  174. }
  175. #if NET_2_0
  176. static Exception GetMustImplement ()
  177. {
  178. return new NotImplementedException ();
  179. }
  180. public DecompressionMethods AutomaticDecompression
  181. {
  182. get {
  183. return auto_decomp;
  184. }
  185. set {
  186. CheckRequestStarted ();
  187. auto_decomp = value;
  188. }
  189. }
  190. #endif
  191. internal bool InternalAllowBuffering {
  192. get {
  193. return (allowBuffering && (method != "HEAD" && method != "GET" &&
  194. method != "MKCOL" && method != "CONNECT" &&
  195. method != "DELETE" && method != "TRACE"));
  196. }
  197. }
  198. public X509CertificateCollection ClientCertificates {
  199. get {
  200. if (certificates == null)
  201. certificates = new X509CertificateCollection ();
  202. return certificates;
  203. }
  204. #if NET_2_0
  205. [MonoTODO]
  206. set {
  207. throw GetMustImplement ();
  208. }
  209. #endif
  210. }
  211. public string Connection {
  212. get { return webHeaders ["Connection"]; }
  213. set {
  214. CheckRequestStarted ();
  215. string val = value;
  216. if (val != null)
  217. val = val.Trim ().ToLower ();
  218. if (val == null || val.Length == 0) {
  219. webHeaders.RemoveInternal ("Connection");
  220. return;
  221. }
  222. if (val == "keep-alive" || val == "close")
  223. throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
  224. if (keepAlive && val.IndexOf ("keep-alive") == -1)
  225. value = value + ", Keep-Alive";
  226. webHeaders.RemoveAndAdd ("Connection", value);
  227. }
  228. }
  229. public override string ConnectionGroupName {
  230. get { return connectionGroup; }
  231. set { connectionGroup = value; }
  232. }
  233. public override long ContentLength {
  234. get { return contentLength; }
  235. set {
  236. CheckRequestStarted ();
  237. if (value < 0)
  238. throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
  239. contentLength = value;
  240. }
  241. }
  242. internal long InternalContentLength {
  243. set { contentLength = value; }
  244. }
  245. public override string ContentType {
  246. get { return webHeaders ["Content-Type"]; }
  247. set {
  248. if (value == null || value.Trim().Length == 0) {
  249. webHeaders.RemoveInternal ("Content-Type");
  250. return;
  251. }
  252. webHeaders.RemoveAndAdd ("Content-Type", value);
  253. }
  254. }
  255. public HttpContinueDelegate ContinueDelegate {
  256. get { return continueDelegate; }
  257. set { continueDelegate = value; }
  258. }
  259. public CookieContainer CookieContainer {
  260. get { return cookieContainer; }
  261. set { cookieContainer = value; }
  262. }
  263. public override ICredentials Credentials {
  264. get { return credentials; }
  265. set { credentials = value; }
  266. }
  267. #if NET_2_0
  268. [MonoTODO]
  269. public static new RequestCachePolicy DefaultCachePolicy
  270. {
  271. get {
  272. throw GetMustImplement ();
  273. }
  274. set {
  275. throw GetMustImplement ();
  276. }
  277. }
  278. [MonoTODO]
  279. public static int DefaultMaximumErrorResponseLength
  280. {
  281. get {
  282. throw GetMustImplement ();
  283. }
  284. set {
  285. throw GetMustImplement ();
  286. }
  287. }
  288. #endif
  289. public string Expect {
  290. get { return webHeaders ["Expect"]; }
  291. set {
  292. CheckRequestStarted ();
  293. string val = value;
  294. if (val != null)
  295. val = val.Trim ().ToLower ();
  296. if (val == null || val.Length == 0) {
  297. webHeaders.RemoveInternal ("Expect");
  298. return;
  299. }
  300. if (val == "100-continue")
  301. throw new ArgumentException ("100-Continue cannot be set with this property.",
  302. "value");
  303. webHeaders.RemoveAndAdd ("Expect", value);
  304. }
  305. }
  306. public bool HaveResponse {
  307. get { return haveResponse; }
  308. }
  309. public override WebHeaderCollection Headers {
  310. get { return webHeaders; }
  311. set {
  312. CheckRequestStarted ();
  313. WebHeaderCollection newHeaders = new WebHeaderCollection (true);
  314. int count = value.Count;
  315. for (int i = 0; i < count; i++)
  316. newHeaders.Add (value.GetKey (i), value.Get (i));
  317. webHeaders = newHeaders;
  318. }
  319. }
  320. public DateTime IfModifiedSince {
  321. get {
  322. string str = webHeaders ["If-Modified-Since"];
  323. if (str == null)
  324. return DateTime.Now;
  325. try {
  326. return MonoHttpDate.Parse (str);
  327. } catch (Exception) {
  328. return DateTime.Now;
  329. }
  330. }
  331. set {
  332. CheckRequestStarted ();
  333. // rfc-1123 pattern
  334. webHeaders.SetInternal ("If-Modified-Since",
  335. value.ToUniversalTime ().ToString ("r", null));
  336. // TODO: check last param when using different locale
  337. }
  338. }
  339. public bool KeepAlive {
  340. get {
  341. return keepAlive;
  342. }
  343. set {
  344. keepAlive = value;
  345. }
  346. }
  347. public int MaximumAutomaticRedirections {
  348. get { return maxAutoRedirect; }
  349. set {
  350. if (value <= 0)
  351. throw new ArgumentException ("Must be > 0", "value");
  352. maxAutoRedirect = value;
  353. }
  354. }
  355. #if NET_1_1
  356. [MonoTODO ("Use this")]
  357. public int MaximumResponseHeadersLength {
  358. get { return maxResponseHeadersLength; }
  359. set { maxResponseHeadersLength = value; }
  360. }
  361. [MonoTODO ("Use this")]
  362. public static int DefaultMaximumResponseHeadersLength {
  363. get { return defaultMaxResponseHeadersLength; }
  364. set { defaultMaxResponseHeadersLength = value; }
  365. }
  366. public
  367. #else
  368. internal
  369. #endif
  370. int ReadWriteTimeout {
  371. get { return readWriteTimeout; }
  372. set {
  373. if (requestSent)
  374. throw new InvalidOperationException ("The request has already been sent.");
  375. if (value < -1)
  376. throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
  377. readWriteTimeout = value;
  378. }
  379. }
  380. public string MediaType {
  381. get { return mediaType; }
  382. set {
  383. mediaType = value;
  384. }
  385. }
  386. public override string Method {
  387. get { return this.method; }
  388. set {
  389. if (value == null || value.Trim () == "")
  390. throw new ArgumentException ("not a valid method");
  391. method = value;
  392. }
  393. }
  394. public bool Pipelined {
  395. get { return pipelined; }
  396. set { pipelined = value; }
  397. }
  398. public override bool PreAuthenticate {
  399. get { return preAuthenticate; }
  400. set { preAuthenticate = value; }
  401. }
  402. public Version ProtocolVersion {
  403. get { return version; }
  404. set {
  405. if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
  406. throw new ArgumentException ("value");
  407. version = value;
  408. }
  409. }
  410. public override IWebProxy Proxy {
  411. get { return proxy; }
  412. set {
  413. CheckRequestStarted ();
  414. #if ONLY_1_1
  415. if (value == null)
  416. throw new ArgumentNullException ("value");
  417. #endif
  418. proxy = value;
  419. servicePoint = null; // we may need a new one
  420. }
  421. }
  422. public string Referer {
  423. get { return webHeaders ["Referer"]; }
  424. set {
  425. CheckRequestStarted ();
  426. if (value == null || value.Trim().Length == 0) {
  427. webHeaders.RemoveInternal ("Referer");
  428. return;
  429. }
  430. webHeaders.SetInternal ("Referer", value);
  431. }
  432. }
  433. public override Uri RequestUri {
  434. get { return requestUri; }
  435. }
  436. public bool SendChunked {
  437. get { return sendChunked; }
  438. set {
  439. CheckRequestStarted ();
  440. sendChunked = value;
  441. }
  442. }
  443. public ServicePoint ServicePoint {
  444. get { return GetServicePoint (); }
  445. }
  446. public override int Timeout {
  447. get { return timeout; }
  448. set {
  449. if (value < -1)
  450. throw new ArgumentOutOfRangeException ("value");
  451. timeout = value;
  452. }
  453. }
  454. public string TransferEncoding {
  455. get { return webHeaders ["Transfer-Encoding"]; }
  456. set {
  457. CheckRequestStarted ();
  458. string val = value;
  459. if (val != null)
  460. val = val.Trim ().ToLower ();
  461. if (val == null || val.Length == 0) {
  462. webHeaders.RemoveInternal ("Transfer-Encoding");
  463. return;
  464. }
  465. if (val == "chunked")
  466. throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
  467. if (!sendChunked)
  468. throw new ArgumentException ("SendChunked must be True", "value");
  469. webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
  470. }
  471. }
  472. #if NET_2_0
  473. public override bool UseDefaultCredentials
  474. {
  475. get { return CredentialCache.DefaultCredentials == Credentials; }
  476. set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
  477. }
  478. #endif
  479. public string UserAgent {
  480. get { return webHeaders ["User-Agent"]; }
  481. set { webHeaders.SetInternal ("User-Agent", value); }
  482. }
  483. #if NET_1_1
  484. bool unsafe_auth_blah;
  485. public bool UnsafeAuthenticatedConnectionSharing
  486. {
  487. get { return unsafe_auth_blah; }
  488. set { unsafe_auth_blah = value; }
  489. }
  490. #endif
  491. internal bool GotRequestStream {
  492. get { return gotRequestStream; }
  493. }
  494. internal bool ExpectContinue {
  495. get { return expectContinue; }
  496. set { expectContinue = value; }
  497. }
  498. internal Uri AuthUri {
  499. get { return actualUri; }
  500. }
  501. internal bool ProxyQuery {
  502. get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
  503. }
  504. // Methods
  505. internal ServicePoint GetServicePoint ()
  506. {
  507. lock (locker) {
  508. if (hostChanged || servicePoint == null) {
  509. servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
  510. hostChanged = false;
  511. }
  512. }
  513. return servicePoint;
  514. }
  515. public void AddRange (int range)
  516. {
  517. AddRange ("bytes", range);
  518. }
  519. public void AddRange (int from, int to)
  520. {
  521. AddRange ("bytes", from, to);
  522. }
  523. public void AddRange (string rangeSpecifier, int range)
  524. {
  525. if (rangeSpecifier == null)
  526. throw new ArgumentNullException ("rangeSpecifier");
  527. string value = webHeaders ["Range"];
  528. if (value == null || value.Length == 0)
  529. value = rangeSpecifier + "=";
  530. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  531. value += ",";
  532. else
  533. throw new InvalidOperationException ("rangeSpecifier");
  534. webHeaders.RemoveAndAdd ("Range", value + range + "-");
  535. }
  536. public void AddRange (string rangeSpecifier, int from, int to)
  537. {
  538. if (rangeSpecifier == null)
  539. throw new ArgumentNullException ("rangeSpecifier");
  540. if (from < 0 || to < 0 || from > to)
  541. throw new ArgumentOutOfRangeException ();
  542. string value = webHeaders ["Range"];
  543. if (value == null || value.Length == 0)
  544. value = rangeSpecifier + "=";
  545. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  546. value += ",";
  547. else
  548. throw new InvalidOperationException ("rangeSpecifier");
  549. webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);
  550. }
  551. #if !NET_2_0
  552. public override int GetHashCode ()
  553. {
  554. return base.GetHashCode ();
  555. }
  556. #endif
  557. void CommonChecks (bool putpost)
  558. {
  559. if (method == null)
  560. throw new ProtocolViolationException ("Method is null.");
  561. if (putpost && contentLength == -1 && !sendChunked && !allowBuffering)
  562. throw new ProtocolViolationException ("Content-Length not set");
  563. string transferEncoding = TransferEncoding;
  564. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  565. throw new ProtocolViolationException ("SendChunked should be true.");
  566. }
  567. public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  568. {
  569. if (aborted)
  570. throw new WebException ("The request was previosly aborted.");
  571. bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
  572. method == "TRACE" || method == "DELETE");
  573. if (method == null || !send)
  574. throw new ProtocolViolationException ("Cannot send data when method is: " + method);
  575. CommonChecks (send);
  576. lock (locker)
  577. {
  578. if (asyncWrite != null) {
  579. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  580. "method while a previous call is still in progress.");
  581. }
  582. asyncWrite = new WebAsyncResult (this, callback, state);
  583. initialMethod = method;
  584. if (haveRequest) {
  585. if (writeStream != null) {
  586. asyncWrite.SetCompleted (true, writeStream);
  587. asyncWrite.DoCallback ();
  588. return asyncWrite;
  589. }
  590. }
  591. gotRequestStream = true;
  592. WebAsyncResult result = asyncWrite;
  593. if (!requestSent) {
  594. requestSent = true;
  595. redirects = 0;
  596. servicePoint = GetServicePoint ();
  597. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  598. }
  599. return result;
  600. }
  601. }
  602. public override Stream EndGetRequestStream (IAsyncResult asyncResult)
  603. {
  604. if (asyncResult == null)
  605. throw new ArgumentNullException ("asyncResult");
  606. WebAsyncResult result = asyncResult as WebAsyncResult;
  607. if (result == null)
  608. throw new ArgumentException ("Invalid IAsyncResult");
  609. asyncWrite = result;
  610. result.WaitUntilComplete ();
  611. Exception e = result.Exception;
  612. if (e != null)
  613. throw e;
  614. return result.WriteStream;
  615. }
  616. public override Stream GetRequestStream()
  617. {
  618. IAsyncResult asyncResult = asyncWrite;
  619. if (asyncResult == null) {
  620. asyncResult = BeginGetRequestStream (null, null);
  621. asyncWrite = (WebAsyncResult) asyncResult;
  622. }
  623. if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
  624. Abort ();
  625. throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
  626. }
  627. return EndGetRequestStream (asyncResult);
  628. }
  629. void CheckIfForceWrite ()
  630. {
  631. if (writeStream == null || writeStream.RequestWritten|| contentLength < 0 || !InternalAllowBuffering)
  632. return;
  633. // This will write the POST/PUT if the write stream already has the expected
  634. // amount of bytes in it (ContentLength) (bug #77753).
  635. if (writeStream.WriteBufferLength == contentLength)
  636. writeStream.WriteRequest ();
  637. }
  638. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  639. {
  640. bool send = (method == "PUT" || method == "POST");
  641. if (send) {
  642. if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
  643. throw new ProtocolViolationException ("Content-Length not set");
  644. }
  645. CommonChecks (send);
  646. Monitor.Enter (locker);
  647. getResponseCalled = true;
  648. if (asyncRead != null && !haveResponse) {
  649. Monitor.Exit (locker);
  650. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  651. "method while a previous call is still in progress.");
  652. }
  653. CheckIfForceWrite ();
  654. asyncRead = new WebAsyncResult (this, callback, state);
  655. WebAsyncResult aread = asyncRead;
  656. initialMethod = method;
  657. if (haveResponse) {
  658. Exception saved = saved_exc;
  659. if (webResponse != null) {
  660. Monitor.Exit (locker);
  661. if (saved == null) {
  662. aread.SetCompleted (true, webResponse);
  663. } else {
  664. aread.SetCompleted (true, saved);
  665. }
  666. aread.DoCallback ();
  667. return aread;
  668. } else if (saved != null) {
  669. Monitor.Exit (locker);
  670. aread.SetCompleted (true, saved);
  671. aread.DoCallback ();
  672. return aread;
  673. }
  674. }
  675. if (!requestSent) {
  676. requestSent = true;
  677. redirects = 0;
  678. servicePoint = GetServicePoint ();
  679. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  680. }
  681. Monitor.Exit (locker);
  682. return aread;
  683. }
  684. public override WebResponse EndGetResponse (IAsyncResult asyncResult)
  685. {
  686. if (asyncResult == null)
  687. throw new ArgumentNullException ("asyncResult");
  688. WebAsyncResult result = asyncResult as WebAsyncResult;
  689. if (result == null)
  690. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  691. if (!result.WaitUntilComplete (timeout, false)) {
  692. Abort ();
  693. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  694. }
  695. if (result.GotException)
  696. throw result.Exception;
  697. return result.Response;
  698. }
  699. public override WebResponse GetResponse()
  700. {
  701. WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
  702. return EndGetResponse (result);
  703. }
  704. internal bool FinishedReading {
  705. get { return finished_reading; }
  706. set { finished_reading = value; }
  707. }
  708. public override void Abort ()
  709. {
  710. if (aborted)
  711. return;
  712. aborted = true;
  713. if (haveResponse && finished_reading)
  714. return;
  715. haveResponse = true;
  716. if (asyncWrite != null) {
  717. WebAsyncResult r = asyncWrite;
  718. if (!r.IsCompleted) {
  719. try {
  720. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  721. r.SetCompleted (false, wexc);
  722. r.DoCallback ();
  723. } catch {}
  724. }
  725. asyncWrite = null;
  726. }
  727. if (asyncRead != null) {
  728. WebAsyncResult r = asyncRead;
  729. if (!r.IsCompleted) {
  730. try {
  731. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  732. r.SetCompleted (false, wexc);
  733. r.DoCallback ();
  734. } catch {}
  735. }
  736. asyncRead = null;
  737. }
  738. if (abortHandler != null) {
  739. try {
  740. abortHandler (this, EventArgs.Empty);
  741. } catch (Exception) {}
  742. abortHandler = null;
  743. }
  744. if (writeStream != null) {
  745. try {
  746. writeStream.Close ();
  747. writeStream = null;
  748. } catch {}
  749. }
  750. if (webResponse != null) {
  751. try {
  752. webResponse.Close ();
  753. webResponse = null;
  754. } catch {}
  755. }
  756. }
  757. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  758. StreamingContext streamingContext)
  759. {
  760. GetObjectData (serializationInfo, streamingContext);
  761. }
  762. #if NET_2_0
  763. protected override
  764. #endif
  765. void GetObjectData (SerializationInfo serializationInfo,
  766. StreamingContext streamingContext)
  767. {
  768. SerializationInfo info = serializationInfo;
  769. info.AddValue ("requestUri", requestUri, typeof (Uri));
  770. info.AddValue ("actualUri", actualUri, typeof (Uri));
  771. info.AddValue ("allowAutoRedirect", allowAutoRedirect);
  772. info.AddValue ("allowBuffering", allowBuffering);
  773. info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
  774. info.AddValue ("connectionGroup", connectionGroup);
  775. info.AddValue ("contentLength", contentLength);
  776. info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
  777. info.AddValue ("keepAlive", keepAlive);
  778. info.AddValue ("maxAutoRedirect", maxAutoRedirect);
  779. info.AddValue ("mediaType", mediaType);
  780. info.AddValue ("method", method);
  781. info.AddValue ("initialMethod", initialMethod);
  782. info.AddValue ("pipelined", pipelined);
  783. info.AddValue ("version", version, typeof (Version));
  784. info.AddValue ("proxy", proxy, typeof (IWebProxy));
  785. info.AddValue ("sendChunked", sendChunked);
  786. info.AddValue ("timeout", timeout);
  787. info.AddValue ("redirects", redirects);
  788. }
  789. void CheckRequestStarted ()
  790. {
  791. if (requestSent)
  792. throw new InvalidOperationException ("request started");
  793. }
  794. internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
  795. {
  796. if (continueDelegate != null)
  797. continueDelegate (statusCode, headers);
  798. }
  799. bool Redirect (WebAsyncResult result, HttpStatusCode code)
  800. {
  801. redirects++;
  802. Exception e = null;
  803. string uriString = null;
  804. switch (code) {
  805. case HttpStatusCode.Ambiguous: // 300
  806. e = new WebException ("Ambiguous redirect.");
  807. break;
  808. case HttpStatusCode.MovedPermanently: // 301
  809. case HttpStatusCode.Redirect: // 302
  810. case HttpStatusCode.TemporaryRedirect: // 307
  811. /* MS follows the redirect for POST too
  812. if (method != "GET" && method != "HEAD") // 10.3
  813. return false;
  814. */
  815. contentLength = 0;
  816. bodyBufferLength = 0;
  817. bodyBuffer = null;
  818. method = "GET";
  819. uriString = webResponse.Headers ["Location"];
  820. break;
  821. case HttpStatusCode.SeeOther: //303
  822. method = "GET";
  823. uriString = webResponse.Headers ["Location"];
  824. break;
  825. case HttpStatusCode.NotModified: // 304
  826. return false;
  827. case HttpStatusCode.UseProxy: // 305
  828. e = new NotImplementedException ("Proxy support not available.");
  829. break;
  830. case HttpStatusCode.Unused: // 306
  831. default:
  832. e = new ProtocolViolationException ("Invalid status code: " + (int) code);
  833. break;
  834. }
  835. if (e != null)
  836. throw e;
  837. if (uriString == null)
  838. throw new WebException ("No Location header found for " + (int) code,
  839. WebExceptionStatus.ProtocolError);
  840. Uri prev = actualUri;
  841. try {
  842. actualUri = new Uri (actualUri, uriString);
  843. } catch (Exception) {
  844. throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
  845. uriString, (int) code),
  846. WebExceptionStatus.ProtocolError);
  847. }
  848. hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host ||
  849. actualUri.Port != prev.Port);
  850. return true;
  851. }
  852. string GetHeaders ()
  853. {
  854. bool continue100 = false;
  855. if (contentLength != -1) {
  856. if (contentLength > 0)
  857. continue100 = true;
  858. webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
  859. webHeaders.RemoveInternal ("Transfer-Encoding");
  860. } else if (sendChunked) {
  861. continue100 = true;
  862. webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
  863. webHeaders.RemoveInternal ("Content-Length");
  864. }
  865. if (actualVersion == HttpVersion.Version11 && continue100 &&
  866. servicePoint.SendContinue) { // RFC2616 8.2.3
  867. webHeaders.RemoveAndAdd ("Expect" , "100-continue");
  868. expectContinue = true;
  869. } else {
  870. webHeaders.RemoveInternal ("Expect");
  871. expectContinue = false;
  872. }
  873. bool proxy_query = ProxyQuery;
  874. string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
  875. webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
  876. Version proto_version = servicePoint.ProtocolVersion;
  877. bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
  878. if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
  879. webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
  880. } else if (!keepAlive && version == HttpVersion.Version11) {
  881. webHeaders.RemoveAndAdd (connectionHeader, "close");
  882. }
  883. webHeaders.SetInternal ("Host", actualUri.Authority);
  884. if (cookieContainer != null) {
  885. string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
  886. if (cookieHeader != "")
  887. webHeaders.SetInternal ("Cookie", cookieHeader);
  888. }
  889. #if NET_2_0
  890. string accept_encoding = null;
  891. if ((auto_decomp & DecompressionMethods.GZip) != 0)
  892. accept_encoding = "gzip";
  893. if ((auto_decomp & DecompressionMethods.Deflate) != 0)
  894. accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
  895. if (accept_encoding != null)
  896. webHeaders.SetInternal ("Accept-Encoding", accept_encoding);
  897. #endif
  898. if (!usedPreAuth && preAuthenticate)
  899. DoPreAuthenticate ();
  900. return webHeaders.ToString ();
  901. }
  902. void DoPreAuthenticate ()
  903. {
  904. webHeaders.RemoveInternal ("Proxy-Authorization");
  905. webHeaders.RemoveInternal ("Authorization");
  906. bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
  907. ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
  908. Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
  909. if (auth == null)
  910. return;
  911. string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
  912. webHeaders [authHeader] = auth.Message;
  913. usedPreAuth = true;
  914. }
  915. internal void SetWriteStreamError (WebExceptionStatus status)
  916. {
  917. SetWriteStreamError (status, null);
  918. }
  919. internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
  920. {
  921. if (aborted)
  922. return;
  923. WebAsyncResult r = asyncWrite;
  924. if (r == null)
  925. r = asyncRead;
  926. if (r != null) {
  927. string msg;
  928. if (exc == null)
  929. msg = "Error: " + status;
  930. else
  931. msg = String.Format ("Error: {0} ({1})", status, exc.Message);
  932. r.SetCompleted (false, new WebException (msg, status));
  933. r.DoCallback ();
  934. }
  935. }
  936. internal void SendRequestHeaders ()
  937. {
  938. StringBuilder req = new StringBuilder ();
  939. string query;
  940. if (!ProxyQuery) {
  941. query = actualUri.PathAndQuery;
  942. } else if (actualUri.IsDefaultPort) {
  943. query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
  944. actualUri.Host,
  945. actualUri.PathAndQuery);
  946. } else {
  947. query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
  948. actualUri.Host,
  949. actualUri.Port,
  950. actualUri.PathAndQuery);
  951. }
  952. if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
  953. actualVersion = servicePoint.ProtocolVersion;
  954. } else {
  955. actualVersion = version;
  956. }
  957. req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
  958. actualVersion.Major, actualVersion.Minor);
  959. req.Append (GetHeaders ());
  960. string reqstr = req.ToString ();
  961. byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
  962. try {
  963. writeStream.SetHeaders (bytes, 0, bytes.Length);
  964. } catch (WebException wexc) {
  965. SetWriteStreamError (wexc.Status);
  966. } catch (Exception) {
  967. SetWriteStreamError (WebExceptionStatus.SendFailure);
  968. }
  969. }
  970. internal void SetWriteStream (WebConnectionStream stream)
  971. {
  972. if (aborted)
  973. return;
  974. writeStream = stream;
  975. if (bodyBuffer != null) {
  976. webHeaders.RemoveInternal ("Transfer-Encoding");
  977. contentLength = bodyBufferLength;
  978. writeStream.SendChunked = false;
  979. }
  980. SendRequestHeaders ();
  981. haveRequest = true;
  982. if (bodyBuffer != null) {
  983. // The body has been written and buffered. The request "user"
  984. // won't write it again, so we must do it.
  985. writeStream.Write (bodyBuffer, 0, bodyBufferLength);
  986. bodyBuffer = null;
  987. writeStream.Close ();
  988. } else if (method == "PUT" || method == "POST" || method == "OPTIONS") {
  989. if (getResponseCalled && !writeStream.RequestWritten)
  990. writeStream.WriteRequest ();
  991. }
  992. if (asyncWrite != null) {
  993. asyncWrite.SetCompleted (false, stream);
  994. asyncWrite.DoCallback ();
  995. asyncWrite = null;
  996. }
  997. }
  998. internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
  999. {
  1000. if (aborted)
  1001. return;
  1002. lock (locker) {
  1003. string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
  1004. WebAsyncResult r = asyncRead;
  1005. if (r == null)
  1006. r = asyncWrite;
  1007. WebException wexc;
  1008. if (e is WebException) {
  1009. wexc = (WebException) e;
  1010. } else {
  1011. wexc = new WebException (msg, e, status, null);
  1012. }
  1013. if (r != null) {
  1014. if (!r.IsCompleted) {
  1015. r.SetCompleted (false, wexc);
  1016. r.DoCallback ();
  1017. } else if (r == asyncWrite) {
  1018. saved_exc = wexc;
  1019. }
  1020. haveResponse = true;
  1021. asyncRead = null;
  1022. asyncWrite = null;
  1023. } else {
  1024. haveResponse = true;
  1025. saved_exc = wexc;
  1026. }
  1027. }
  1028. }
  1029. void CheckSendError (WebConnectionData data)
  1030. {
  1031. // Got here, but no one called GetResponse
  1032. int status = data.StatusCode;
  1033. if (status < 400 || status == 401 || status == 407)
  1034. return;
  1035. if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
  1036. // The request has not been completely sent and we got here!
  1037. // We should probably just close and cause an error in any case,
  1038. saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
  1039. webResponse.ReadAll ();
  1040. }
  1041. }
  1042. void HandleNtlmAuth (WebAsyncResult r)
  1043. {
  1044. WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
  1045. if (wce != null) {
  1046. WebConnection cnc = wce.Connection;
  1047. cnc.PriorityRequest = this;
  1048. bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
  1049. ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
  1050. if (creds != null) {
  1051. cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
  1052. #if NET_1_1
  1053. cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
  1054. #endif
  1055. }
  1056. }
  1057. r.Reset ();
  1058. haveResponse = false;
  1059. webResponse.ReadAll ();
  1060. webResponse = null;
  1061. }
  1062. internal void SetResponseData (WebConnectionData data)
  1063. {
  1064. lock (locker) {
  1065. if (aborted) {
  1066. if (data.stream != null)
  1067. data.stream.Close ();
  1068. return;
  1069. }
  1070. WebException wexc = null;
  1071. try {
  1072. webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
  1073. } catch (Exception e) {
  1074. wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
  1075. if (data.stream != null)
  1076. data.stream.Close ();
  1077. }
  1078. if (wexc == null && (method == "POST" || method == "PUT")) {
  1079. lock (locker) {
  1080. CheckSendError (data);
  1081. if (saved_exc != null)
  1082. wexc = (WebException) saved_exc;
  1083. }
  1084. }
  1085. WebAsyncResult r = asyncRead;
  1086. bool forced = false;
  1087. if (r == null && webResponse != null) {
  1088. // This is a forced completion (302, 204)...
  1089. forced = true;
  1090. r = new WebAsyncResult (null, null);
  1091. r.SetCompleted (false, webResponse);
  1092. }
  1093. if (r != null) {
  1094. if (wexc != null) {
  1095. r.SetCompleted (false, wexc);
  1096. r.DoCallback ();
  1097. return;
  1098. }
  1099. bool redirected;
  1100. try {
  1101. redirected = CheckFinalStatus (r);
  1102. if (!redirected) {
  1103. if (is_ntlm_auth && authCompleted && webResponse != null
  1104. && (int)webResponse.StatusCode < 400) {
  1105. WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
  1106. if (wce != null) {
  1107. WebConnection cnc = wce.Connection;
  1108. cnc.NtlmAuthenticated = true;
  1109. }
  1110. }
  1111. // clear internal buffer so that it does not
  1112. // hold possible big buffer (bug #397627)
  1113. if (writeStream != null)
  1114. writeStream.KillBuffer ();
  1115. haveResponse = true;
  1116. r.SetCompleted (false, webResponse);
  1117. r.DoCallback ();
  1118. } else {
  1119. if (webResponse != null) {
  1120. if (is_ntlm_auth) {
  1121. HandleNtlmAuth (r);
  1122. return;
  1123. }
  1124. webResponse.Close ();
  1125. }
  1126. haveResponse = false;
  1127. webResponse = null;
  1128. r.Reset ();
  1129. servicePoint = GetServicePoint ();
  1130. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  1131. }
  1132. } catch (WebException wexc2) {
  1133. if (forced) {
  1134. saved_exc = wexc2;
  1135. haveResponse = true;
  1136. }
  1137. r.SetCompleted (false, wexc2);
  1138. r.DoCallback ();
  1139. return;
  1140. } catch (Exception ex) {
  1141. wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
  1142. if (forced) {
  1143. saved_exc = wexc;
  1144. haveResponse = true;
  1145. }
  1146. r.SetCompleted (false, wexc);
  1147. r.DoCallback ();
  1148. return;
  1149. }
  1150. }
  1151. }
  1152. }
  1153. bool CheckAuthorization (WebResponse response, HttpStatusCode code)
  1154. {
  1155. authCompleted = false;
  1156. if (code == HttpStatusCode.Unauthorized && credentials == null)
  1157. return false;
  1158. bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
  1159. if (isProxy && (proxy == null || proxy.Credentials == null))
  1160. return false;
  1161. string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
  1162. if (authHeader == null)
  1163. return false;
  1164. ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
  1165. Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
  1166. if (auth == null)
  1167. return false;
  1168. webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
  1169. authCompleted = auth.Complete;
  1170. is_ntlm_auth = (auth.Module.AuthenticationType == "NTLM");
  1171. return true;
  1172. }
  1173. // Returns true if redirected
  1174. bool CheckFinalStatus (WebAsyncResult result)
  1175. {
  1176. if (result.GotException)
  1177. throw result.Exception;
  1178. Exception throwMe = result.Exception;
  1179. bodyBuffer = null;
  1180. HttpWebResponse resp = result.Response;
  1181. WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
  1182. HttpStatusCode code = 0;
  1183. if (throwMe == null && webResponse != null) {
  1184. code = webResponse.StatusCode;
  1185. if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
  1186. (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
  1187. if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
  1188. // Keep the written body, so it can be rewritten in the retry
  1189. if (InternalAllowBuffering) {
  1190. bodyBuffer = writeStream.WriteBuffer;
  1191. bodyBufferLength = writeStream.WriteBufferLength;
  1192. return true;
  1193. } else if (method != "PUT" && method != "POST") {
  1194. return true;
  1195. }
  1196. writeStream.InternalClose ();
  1197. writeStream = null;
  1198. webResponse.Close ();
  1199. webResponse = null;
  1200. throw new WebException ("This request requires buffering " +
  1201. "of data for authentication or " +
  1202. "redirection to be sucessful.");
  1203. }
  1204. }
  1205. if ((int) code >= 400) {
  1206. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  1207. (int) code, webResponse.StatusDescription);
  1208. throwMe = new WebException (err, null, protoError, webResponse);
  1209. webResponse.ReadAll ();
  1210. } else if ((int) code == 304 && allowAutoRedirect) {
  1211. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  1212. (int) code, webResponse.StatusDescription);
  1213. throwMe = new WebException (err, null, protoError, webResponse);
  1214. } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
  1215. throwMe = new WebException ("Max. redirections exceeded.", null,
  1216. protoError, webResponse);
  1217. webResponse.ReadAll ();
  1218. }
  1219. }
  1220. if (throwMe == null) {
  1221. bool b = false;
  1222. int c = (int) code;
  1223. if (allowAutoRedirect && c >= 300) {
  1224. if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
  1225. bodyBuffer = writeStream.WriteBuffer;
  1226. bodyBufferLength = writeStream.WriteBufferLength;
  1227. }
  1228. b = Redirect (result, code);
  1229. }
  1230. if (resp != null && c >= 300 && c != 304)
  1231. resp.ReadAll ();
  1232. return b;
  1233. }
  1234. if (writeStream != null) {
  1235. writeStream.InternalClose ();
  1236. writeStream = null;
  1237. }
  1238. webResponse = null;
  1239. throw throwMe;
  1240. }
  1241. }
  1242. }