HttpWebRequest.cs 44 KB

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