HttpWebRequest.cs 49 KB

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