HttpWebRequest.cs 41 KB

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