HttpWebRequest.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  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. if (!result.IsCompleted && !result.AsyncWaitHandle.WaitOne (timeout, false)) {
  784. Abort ();
  785. throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
  786. }
  787. return EndGetResponse (result);
  788. }
  789. internal bool FinishedReading {
  790. get { return finished_reading; }
  791. set { finished_reading = value; }
  792. }
  793. internal bool Aborted {
  794. get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
  795. }
  796. public override void Abort ()
  797. {
  798. if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
  799. return;
  800. if (haveResponse && finished_reading)
  801. return;
  802. haveResponse = true;
  803. if (abortHandler != null) {
  804. try {
  805. abortHandler (this, EventArgs.Empty);
  806. } catch (Exception) {}
  807. abortHandler = null;
  808. }
  809. if (asyncWrite != null) {
  810. WebAsyncResult r = asyncWrite;
  811. if (!r.IsCompleted) {
  812. try {
  813. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  814. r.SetCompleted (false, wexc);
  815. r.DoCallback ();
  816. } catch {}
  817. }
  818. asyncWrite = null;
  819. }
  820. if (asyncRead != null) {
  821. WebAsyncResult r = asyncRead;
  822. if (!r.IsCompleted) {
  823. try {
  824. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  825. r.SetCompleted (false, wexc);
  826. r.DoCallback ();
  827. } catch {}
  828. }
  829. asyncRead = null;
  830. }
  831. if (writeStream != null) {
  832. try {
  833. writeStream.Close ();
  834. writeStream = null;
  835. } catch {}
  836. }
  837. if (webResponse != null) {
  838. try {
  839. webResponse.Close ();
  840. webResponse = null;
  841. } catch {}
  842. }
  843. }
  844. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  845. StreamingContext streamingContext)
  846. {
  847. GetObjectData (serializationInfo, streamingContext);
  848. }
  849. protected override void GetObjectData (SerializationInfo serializationInfo,
  850. StreamingContext streamingContext)
  851. {
  852. SerializationInfo info = serializationInfo;
  853. info.AddValue ("requestUri", requestUri, typeof (Uri));
  854. info.AddValue ("actualUri", actualUri, typeof (Uri));
  855. info.AddValue ("allowAutoRedirect", allowAutoRedirect);
  856. info.AddValue ("allowBuffering", allowBuffering);
  857. info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
  858. info.AddValue ("connectionGroup", connectionGroup);
  859. info.AddValue ("contentLength", contentLength);
  860. info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
  861. info.AddValue ("keepAlive", keepAlive);
  862. info.AddValue ("maxAutoRedirect", maxAutoRedirect);
  863. info.AddValue ("mediaType", mediaType);
  864. info.AddValue ("method", method);
  865. info.AddValue ("initialMethod", initialMethod);
  866. info.AddValue ("pipelined", pipelined);
  867. info.AddValue ("version", version, typeof (Version));
  868. info.AddValue ("proxy", proxy, typeof (IWebProxy));
  869. info.AddValue ("sendChunked", sendChunked);
  870. info.AddValue ("timeout", timeout);
  871. info.AddValue ("redirects", redirects);
  872. info.AddValue ("host", host);
  873. }
  874. void CheckRequestStarted ()
  875. {
  876. if (requestSent)
  877. throw new InvalidOperationException ("request started");
  878. }
  879. internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
  880. {
  881. if (continueDelegate != null)
  882. continueDelegate (statusCode, headers);
  883. }
  884. bool Redirect (WebAsyncResult result, HttpStatusCode code)
  885. {
  886. redirects++;
  887. Exception e = null;
  888. string uriString = null;
  889. switch (code) {
  890. case HttpStatusCode.Ambiguous: // 300
  891. e = new WebException ("Ambiguous redirect.");
  892. break;
  893. case HttpStatusCode.MovedPermanently: // 301
  894. case HttpStatusCode.Redirect: // 302
  895. case HttpStatusCode.TemporaryRedirect: // 307
  896. /* MS follows the redirect for POST too
  897. if (method != "GET" && method != "HEAD") // 10.3
  898. return false;
  899. */
  900. contentLength = -1;
  901. bodyBufferLength = 0;
  902. bodyBuffer = null;
  903. if (code != HttpStatusCode.TemporaryRedirect)
  904. method = "GET";
  905. uriString = webResponse.Headers ["Location"];
  906. break;
  907. case HttpStatusCode.SeeOther: //303
  908. method = "GET";
  909. uriString = webResponse.Headers ["Location"];
  910. break;
  911. case HttpStatusCode.NotModified: // 304
  912. return false;
  913. case HttpStatusCode.UseProxy: // 305
  914. e = new NotImplementedException ("Proxy support not available.");
  915. break;
  916. case HttpStatusCode.Unused: // 306
  917. default:
  918. e = new ProtocolViolationException ("Invalid status code: " + (int) code);
  919. break;
  920. }
  921. if (e != null)
  922. throw e;
  923. if (uriString == null)
  924. throw new WebException ("No Location header found for " + (int) code,
  925. WebExceptionStatus.ProtocolError);
  926. Uri prev = actualUri;
  927. try {
  928. actualUri = new Uri (actualUri, uriString);
  929. } catch (Exception) {
  930. throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
  931. uriString, (int) code),
  932. WebExceptionStatus.ProtocolError);
  933. }
  934. hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
  935. return true;
  936. }
  937. string GetHeaders ()
  938. {
  939. bool continue100 = false;
  940. if (sendChunked) {
  941. continue100 = true;
  942. webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
  943. webHeaders.RemoveInternal ("Content-Length");
  944. } else if (contentLength != -1) {
  945. if (ntlm_auth_state != NtlmAuthState.Challenge) {
  946. if (contentLength > 0)
  947. continue100 = true;
  948. webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
  949. } else {
  950. webHeaders.SetInternal ("Content-Length", "0");
  951. }
  952. webHeaders.RemoveInternal ("Transfer-Encoding");
  953. } else {
  954. webHeaders.RemoveInternal ("Content-Length");
  955. }
  956. if (actualVersion == HttpVersion.Version11 && continue100 &&
  957. servicePoint.SendContinue) { // RFC2616 8.2.3
  958. webHeaders.RemoveAndAdd ("Expect" , "100-continue");
  959. expectContinue = true;
  960. } else {
  961. webHeaders.RemoveInternal ("Expect");
  962. expectContinue = false;
  963. }
  964. bool proxy_query = ProxyQuery;
  965. string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
  966. webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
  967. Version proto_version = servicePoint.ProtocolVersion;
  968. bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
  969. if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
  970. webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
  971. } else if (!keepAlive && version == HttpVersion.Version11) {
  972. webHeaders.RemoveAndAdd (connectionHeader, "close");
  973. }
  974. webHeaders.SetInternal ("Host", Host);
  975. if (cookieContainer != null) {
  976. string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
  977. if (cookieHeader != "")
  978. webHeaders.SetInternal ("Cookie", cookieHeader);
  979. }
  980. string accept_encoding = null;
  981. if ((auto_decomp & DecompressionMethods.GZip) != 0)
  982. accept_encoding = "gzip";
  983. if ((auto_decomp & DecompressionMethods.Deflate) != 0)
  984. accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
  985. if (accept_encoding != null)
  986. webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
  987. if (!usedPreAuth && preAuthenticate)
  988. DoPreAuthenticate ();
  989. return webHeaders.ToString ();
  990. }
  991. void DoPreAuthenticate ()
  992. {
  993. bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
  994. ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
  995. Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
  996. if (auth == null)
  997. return;
  998. webHeaders.RemoveInternal ("Proxy-Authorization");
  999. webHeaders.RemoveInternal ("Authorization");
  1000. string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
  1001. webHeaders [authHeader] = auth.Message;
  1002. usedPreAuth = true;
  1003. }
  1004. internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
  1005. {
  1006. if (Aborted)
  1007. return;
  1008. WebAsyncResult r = asyncWrite;
  1009. if (r == null)
  1010. r = asyncRead;
  1011. if (r != null) {
  1012. string msg;
  1013. WebException wex;
  1014. if (exc == null) {
  1015. msg = "Error: " + status;
  1016. wex = new WebException (msg, status);
  1017. } else {
  1018. msg = String.Format ("Error: {0} ({1})", status, exc.Message);
  1019. wex = new WebException (msg, exc, status);
  1020. }
  1021. r.SetCompleted (false, wex);
  1022. r.DoCallback ();
  1023. }
  1024. }
  1025. internal void SendRequestHeaders (bool propagate_error)
  1026. {
  1027. StringBuilder req = new StringBuilder ();
  1028. string query;
  1029. if (!ProxyQuery) {
  1030. query = actualUri.PathAndQuery;
  1031. } else {
  1032. query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
  1033. Host,
  1034. actualUri.PathAndQuery);
  1035. }
  1036. if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
  1037. actualVersion = servicePoint.ProtocolVersion;
  1038. } else {
  1039. actualVersion = version;
  1040. }
  1041. req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
  1042. actualVersion.Major, actualVersion.Minor);
  1043. req.Append (GetHeaders ());
  1044. string reqstr = req.ToString ();
  1045. byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
  1046. try {
  1047. writeStream.SetHeaders (bytes);
  1048. } catch (WebException wexc) {
  1049. SetWriteStreamError (wexc.Status, wexc);
  1050. if (propagate_error)
  1051. throw;
  1052. } catch (Exception exc) {
  1053. SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
  1054. if (propagate_error)
  1055. throw;
  1056. }
  1057. }
  1058. internal void SetWriteStream (WebConnectionStream stream)
  1059. {
  1060. if (Aborted)
  1061. return;
  1062. writeStream = stream;
  1063. if (bodyBuffer != null) {
  1064. webHeaders.RemoveInternal ("Transfer-Encoding");
  1065. contentLength = bodyBufferLength;
  1066. writeStream.SendChunked = false;
  1067. }
  1068. SendRequestHeaders (false);
  1069. haveRequest = true;
  1070. if (bodyBuffer != null) {
  1071. // The body has been written and buffered. The request "user"
  1072. // won't write it again, so we must do it.
  1073. if (ntlm_auth_state != NtlmAuthState.Challenge) {
  1074. writeStream.Write (bodyBuffer, 0, bodyBufferLength);
  1075. bodyBuffer = null;
  1076. writeStream.Close ();
  1077. }
  1078. } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
  1079. method != "TRACE") {
  1080. if (getResponseCalled && !writeStream.RequestWritten)
  1081. writeStream.WriteRequest ();
  1082. }
  1083. if (asyncWrite != null) {
  1084. asyncWrite.SetCompleted (false, stream);
  1085. asyncWrite.DoCallback ();
  1086. asyncWrite = null;
  1087. }
  1088. }
  1089. internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
  1090. {
  1091. if (Aborted)
  1092. return;
  1093. lock (locker) {
  1094. string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
  1095. WebAsyncResult r = asyncRead;
  1096. if (r == null)
  1097. r = asyncWrite;
  1098. WebException wexc;
  1099. if (e is WebException) {
  1100. wexc = (WebException) e;
  1101. } else {
  1102. wexc = new WebException (msg, e, status, null);
  1103. }
  1104. if (r != null) {
  1105. if (!r.IsCompleted) {
  1106. r.SetCompleted (false, wexc);
  1107. r.DoCallback ();
  1108. } else if (r == asyncWrite) {
  1109. saved_exc = wexc;
  1110. }
  1111. haveResponse = true;
  1112. asyncRead = null;
  1113. asyncWrite = null;
  1114. } else {
  1115. haveResponse = true;
  1116. saved_exc = wexc;
  1117. }
  1118. }
  1119. }
  1120. void CheckSendError (WebConnectionData data)
  1121. {
  1122. // Got here, but no one called GetResponse
  1123. int status = data.StatusCode;
  1124. if (status < 400 || status == 401 || status == 407)
  1125. return;
  1126. if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
  1127. // The request has not been completely sent and we got here!
  1128. // We should probably just close and cause an error in any case,
  1129. saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
  1130. if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
  1131. webResponse.ReadAll ();
  1132. } else {
  1133. writeStream.IgnoreIOErrors = true;
  1134. }
  1135. }
  1136. }
  1137. void HandleNtlmAuth (WebAsyncResult r)
  1138. {
  1139. WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
  1140. if (wce != null) {
  1141. WebConnection cnc = wce.Connection;
  1142. cnc.PriorityRequest = this;
  1143. bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
  1144. ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
  1145. if (creds != null) {
  1146. cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
  1147. cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
  1148. }
  1149. }
  1150. r.Reset ();
  1151. finished_reading = false;
  1152. haveResponse = false;
  1153. webResponse.ReadAll ();
  1154. webResponse = null;
  1155. }
  1156. internal void SetResponseData (WebConnectionData data)
  1157. {
  1158. lock (locker) {
  1159. if (Aborted) {
  1160. if (data.stream != null)
  1161. data.stream.Close ();
  1162. return;
  1163. }
  1164. WebException wexc = null;
  1165. try {
  1166. webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
  1167. } catch (Exception e) {
  1168. wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
  1169. if (data.stream != null)
  1170. data.stream.Close ();
  1171. }
  1172. if (wexc == null && (method == "POST" || method == "PUT")) {
  1173. CheckSendError (data);
  1174. if (saved_exc != null)
  1175. wexc = (WebException) saved_exc;
  1176. }
  1177. WebAsyncResult r = asyncRead;
  1178. bool forced = false;
  1179. if (r == null && webResponse != null) {
  1180. // This is a forced completion (302, 204)...
  1181. forced = true;
  1182. r = new WebAsyncResult (null, null);
  1183. r.SetCompleted (false, webResponse);
  1184. }
  1185. if (r != null) {
  1186. if (wexc != null) {
  1187. haveResponse = true;
  1188. if (!r.IsCompleted)
  1189. r.SetCompleted (false, wexc);
  1190. r.DoCallback ();
  1191. return;
  1192. }
  1193. bool redirected;
  1194. try {
  1195. redirected = CheckFinalStatus (r);
  1196. if (!redirected) {
  1197. if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null
  1198. && (int)webResponse.StatusCode < 400) {
  1199. WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
  1200. if (wce != null) {
  1201. WebConnection cnc = wce.Connection;
  1202. cnc.NtlmAuthenticated = true;
  1203. }
  1204. }
  1205. // clear internal buffer so that it does not
  1206. // hold possible big buffer (bug #397627)
  1207. if (writeStream != null)
  1208. writeStream.KillBuffer ();
  1209. haveResponse = true;
  1210. r.SetCompleted (false, webResponse);
  1211. r.DoCallback ();
  1212. } else {
  1213. if (webResponse != null) {
  1214. if (ntlm_auth_state != NtlmAuthState.None) {
  1215. HandleNtlmAuth (r);
  1216. return;
  1217. }
  1218. webResponse.Close ();
  1219. }
  1220. finished_reading = false;
  1221. haveResponse = false;
  1222. webResponse = null;
  1223. r.Reset ();
  1224. servicePoint = GetServicePoint ();
  1225. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  1226. }
  1227. } catch (WebException wexc2) {
  1228. if (forced) {
  1229. saved_exc = wexc2;
  1230. haveResponse = true;
  1231. }
  1232. r.SetCompleted (false, wexc2);
  1233. r.DoCallback ();
  1234. return;
  1235. } catch (Exception ex) {
  1236. wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
  1237. if (forced) {
  1238. saved_exc = wexc;
  1239. haveResponse = true;
  1240. }
  1241. r.SetCompleted (false, wexc);
  1242. r.DoCallback ();
  1243. return;
  1244. }
  1245. }
  1246. }
  1247. }
  1248. bool CheckAuthorization (WebResponse response, HttpStatusCode code)
  1249. {
  1250. authCompleted = false;
  1251. if (code == HttpStatusCode.Unauthorized && credentials == null)
  1252. return false;
  1253. bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
  1254. if (isProxy && (proxy == null || proxy.Credentials == null))
  1255. return false;
  1256. string [] authHeaders = response.Headers.GetValues ( (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate");
  1257. if (authHeaders == null || authHeaders.Length == 0)
  1258. return false;
  1259. ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
  1260. Authorization auth = null;
  1261. foreach (string authHeader in authHeaders) {
  1262. auth = AuthenticationManager.Authenticate (authHeader, this, creds);
  1263. if (auth != null)
  1264. break;
  1265. }
  1266. if (auth == null)
  1267. return false;
  1268. webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
  1269. authCompleted = auth.Complete;
  1270. bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
  1271. if (is_ntlm)
  1272. ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
  1273. return true;
  1274. }
  1275. // Returns true if redirected
  1276. bool CheckFinalStatus (WebAsyncResult result)
  1277. {
  1278. if (result.GotException) {
  1279. bodyBuffer = null;
  1280. throw result.Exception;
  1281. }
  1282. Exception throwMe = result.Exception;
  1283. HttpWebResponse resp = result.Response;
  1284. WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
  1285. HttpStatusCode code = 0;
  1286. if (throwMe == null && webResponse != null) {
  1287. code = webResponse.StatusCode;
  1288. if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
  1289. (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
  1290. if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
  1291. // Keep the written body, so it can be rewritten in the retry
  1292. if (InternalAllowBuffering) {
  1293. // NTLM: This is to avoid sending data in the 'challenge' request
  1294. // We save it in the first request (first 401), don't send anything
  1295. // in the challenge request and send it in the response request along
  1296. // with the buffers kept form the first request.
  1297. if (ntlm_auth_state != NtlmAuthState.Response) {
  1298. bodyBuffer = writeStream.WriteBuffer;
  1299. bodyBufferLength = writeStream.WriteBufferLength;
  1300. }
  1301. return true;
  1302. } else if (method != "PUT" && method != "POST") {
  1303. bodyBuffer = null;
  1304. return true;
  1305. }
  1306. writeStream.InternalClose ();
  1307. writeStream = null;
  1308. webResponse.Close ();
  1309. webResponse = null;
  1310. bodyBuffer = null;
  1311. throw new WebException ("This request requires buffering " +
  1312. "of data for authentication or " +
  1313. "redirection to be sucessful.");
  1314. }
  1315. }
  1316. bodyBuffer = null;
  1317. if ((int) code >= 400) {
  1318. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  1319. (int) code, webResponse.StatusDescription);
  1320. throwMe = new WebException (err, null, protoError, webResponse);
  1321. webResponse.ReadAll ();
  1322. } else if ((int) code == 304 && allowAutoRedirect) {
  1323. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  1324. (int) code, webResponse.StatusDescription);
  1325. throwMe = new WebException (err, null, protoError, webResponse);
  1326. } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
  1327. throwMe = new WebException ("Max. redirections exceeded.", null,
  1328. protoError, webResponse);
  1329. webResponse.ReadAll ();
  1330. }
  1331. }
  1332. bodyBuffer = null;
  1333. if (throwMe == null) {
  1334. bool b = false;
  1335. int c = (int) code;
  1336. if (allowAutoRedirect && c >= 300) {
  1337. if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
  1338. bodyBuffer = writeStream.WriteBuffer;
  1339. bodyBufferLength = writeStream.WriteBufferLength;
  1340. }
  1341. b = Redirect (result, code);
  1342. }
  1343. if (resp != null && c >= 300 && c != 304)
  1344. resp.ReadAll ();
  1345. return b;
  1346. }
  1347. if (writeStream != null) {
  1348. writeStream.InternalClose ();
  1349. writeStream = null;
  1350. }
  1351. webResponse = null;
  1352. throw throwMe;
  1353. }
  1354. }
  1355. }