HttpWebRequest.cs 42 KB

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