HttpWebRequest.cs 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  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. public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  558. {
  559. if (aborted)
  560. throw new WebException ("The request was previosly aborted.");
  561. bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
  562. method == "TRACE" || method == "DELETE");
  563. if (method == null || !send)
  564. throw new ProtocolViolationException ("Cannot send data when method is: " + method);
  565. if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
  566. throw new ProtocolViolationException ("Content-Length not set");
  567. string transferEncoding = TransferEncoding;
  568. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  569. throw new ProtocolViolationException ("SendChunked should be true.");
  570. lock (locker)
  571. {
  572. if (asyncWrite != null) {
  573. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  574. "method while a previous call is still in progress.");
  575. }
  576. asyncWrite = new WebAsyncResult (this, callback, state);
  577. initialMethod = method;
  578. if (haveRequest) {
  579. if (writeStream != null) {
  580. asyncWrite.SetCompleted (true, writeStream);
  581. asyncWrite.DoCallback ();
  582. return asyncWrite;
  583. }
  584. }
  585. gotRequestStream = true;
  586. WebAsyncResult result = asyncWrite;
  587. if (!requestSent) {
  588. requestSent = true;
  589. redirects = 0;
  590. servicePoint = GetServicePoint ();
  591. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  592. }
  593. return result;
  594. }
  595. }
  596. public override Stream EndGetRequestStream (IAsyncResult asyncResult)
  597. {
  598. if (asyncResult == null)
  599. throw new ArgumentNullException ("asyncResult");
  600. WebAsyncResult result = asyncResult as WebAsyncResult;
  601. if (result == null)
  602. throw new ArgumentException ("Invalid IAsyncResult");
  603. asyncWrite = result;
  604. result.WaitUntilComplete ();
  605. Exception e = result.Exception;
  606. if (e != null)
  607. throw e;
  608. return result.WriteStream;
  609. }
  610. public override Stream GetRequestStream()
  611. {
  612. IAsyncResult asyncResult = asyncWrite;
  613. if (asyncResult == null) {
  614. asyncResult = BeginGetRequestStream (null, null);
  615. asyncWrite = (WebAsyncResult) asyncResult;
  616. }
  617. if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
  618. Abort ();
  619. throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
  620. }
  621. return EndGetRequestStream (asyncResult);
  622. }
  623. void CheckIfForceWrite ()
  624. {
  625. if (writeStream == null || writeStream.RequestWritten|| contentLength < 0 || !InternalAllowBuffering)
  626. return;
  627. // This will write the POST/PUT if the write stream already has the expected
  628. // amount of bytes in it (ContentLength) (bug #77753).
  629. if (writeStream.WriteBufferLength == contentLength)
  630. writeStream.WriteRequest ();
  631. }
  632. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  633. {
  634. if (method == null)
  635. throw new ProtocolViolationException ("Method is null.");
  636. #if !NET_2_0
  637. bool send = (method == "PUT" || method == "POST");
  638. if (send && contentLength < 0 && !sendChunked && !allowBuffering && KeepAlive)
  639. throw new ProtocolViolationException ("Buffering is disabled, ContentLength is negative and SendChunked is disabled.");
  640. if (!send && (contentLength > -1 || sendChunked))
  641. throw new ProtocolViolationException ("ContentLength can't be set for non-write operations.");
  642. #endif
  643. string transferEncoding = TransferEncoding;
  644. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  645. throw new ProtocolViolationException ("SendChunked should be true.");
  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. }