HttpWebRequest.cs 43 KB

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