HttpWebRequest.cs 42 KB

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