HttpWebRequest.cs 39 KB

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