HttpWebRequest.cs 47 KB

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