HttpWebRequest.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823
  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 virtual bool AllowAutoRedirect {
  211. get { return allowAutoRedirect; }
  212. set { this.allowAutoRedirect = value; }
  213. }
  214. public virtual 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. [MonoTODO]
  789. public Stream GetRequestStream (out TransportContext context)
  790. {
  791. throw new NotImplementedException ();
  792. }
  793. bool CheckIfForceWrite (SimpleAsyncResult result)
  794. {
  795. if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
  796. return false;
  797. if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
  798. return false;
  799. if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
  800. InternalContentLength = writeStream.WriteBufferLength;
  801. // This will write the POST/PUT if the write stream already has the expected
  802. // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
  803. // contains data and it has been closed already (xamarin bug #1512).
  804. if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
  805. return writeStream.WriteRequestAsync (result);
  806. return false;
  807. }
  808. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  809. {
  810. if (Aborted)
  811. throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
  812. if (method == null)
  813. throw new ProtocolViolationException ("Method is null.");
  814. string transferEncoding = TransferEncoding;
  815. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  816. throw new ProtocolViolationException ("SendChunked should be true.");
  817. Monitor.Enter (locker);
  818. getResponseCalled = true;
  819. if (asyncRead != null && !haveResponse) {
  820. Monitor.Exit (locker);
  821. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  822. "method while a previous call is still in progress.");
  823. }
  824. asyncRead = new WebAsyncResult (this, callback, state);
  825. WebAsyncResult aread = asyncRead;
  826. initialMethod = method;
  827. SimpleAsyncResult.RunWithLock (locker, CheckIfForceWrite, inner => {
  828. var synch = inner.CompletedSynchronouslyPeek;
  829. if (inner.GotException) {
  830. aread.SetCompleted (synch, inner.Exception);
  831. aread.DoCallback ();
  832. return;
  833. }
  834. if (haveResponse) {
  835. Exception saved = saved_exc;
  836. if (webResponse != null) {
  837. if (saved == null) {
  838. aread.SetCompleted (synch, webResponse);
  839. } else {
  840. aread.SetCompleted (synch, saved);
  841. }
  842. aread.DoCallback ();
  843. return;
  844. } else if (saved != null) {
  845. aread.SetCompleted (synch, saved);
  846. aread.DoCallback ();
  847. return;
  848. }
  849. }
  850. if (requestSent)
  851. return;
  852. try {
  853. requestSent = true;
  854. redirects = 0;
  855. servicePoint = GetServicePoint ();
  856. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  857. } catch (Exception ex) {
  858. aread.SetCompleted (synch, ex);
  859. aread.DoCallback ();
  860. }
  861. });
  862. return aread;
  863. }
  864. public override WebResponse EndGetResponse (IAsyncResult asyncResult)
  865. {
  866. if (asyncResult == null)
  867. throw new ArgumentNullException ("asyncResult");
  868. WebAsyncResult result = asyncResult as WebAsyncResult;
  869. if (result == null)
  870. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  871. if (!result.WaitUntilComplete (timeout, false)) {
  872. Abort ();
  873. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  874. }
  875. if (result.GotException)
  876. throw result.Exception;
  877. return result.Response;
  878. }
  879. public Stream EndGetRequestStream (IAsyncResult asyncResult, out TransportContext transportContext)
  880. {
  881. transportContext = null;
  882. return EndGetRequestStream (asyncResult);
  883. }
  884. public override WebResponse GetResponse()
  885. {
  886. WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
  887. return EndGetResponse (result);
  888. }
  889. internal bool FinishedReading {
  890. get { return finished_reading; }
  891. set { finished_reading = value; }
  892. }
  893. internal bool Aborted {
  894. get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
  895. }
  896. public override void Abort ()
  897. {
  898. if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
  899. return;
  900. if (haveResponse && finished_reading)
  901. return;
  902. haveResponse = true;
  903. if (abortHandler != null) {
  904. try {
  905. abortHandler (this, EventArgs.Empty);
  906. } catch (Exception) {}
  907. abortHandler = null;
  908. }
  909. if (asyncWrite != null) {
  910. WebAsyncResult r = asyncWrite;
  911. if (!r.IsCompleted) {
  912. try {
  913. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  914. r.SetCompleted (false, wexc);
  915. r.DoCallback ();
  916. } catch {}
  917. }
  918. asyncWrite = null;
  919. }
  920. if (asyncRead != null) {
  921. WebAsyncResult r = asyncRead;
  922. if (!r.IsCompleted) {
  923. try {
  924. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  925. r.SetCompleted (false, wexc);
  926. r.DoCallback ();
  927. } catch {}
  928. }
  929. asyncRead = null;
  930. }
  931. if (writeStream != null) {
  932. try {
  933. writeStream.Close ();
  934. writeStream = null;
  935. } catch {}
  936. }
  937. if (webResponse != null) {
  938. try {
  939. webResponse.Close ();
  940. webResponse = null;
  941. } catch {}
  942. }
  943. }
  944. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  945. StreamingContext streamingContext)
  946. {
  947. GetObjectData (serializationInfo, streamingContext);
  948. }
  949. protected override void GetObjectData (SerializationInfo serializationInfo,
  950. StreamingContext streamingContext)
  951. {
  952. SerializationInfo info = serializationInfo;
  953. info.AddValue ("requestUri", requestUri, typeof (Uri));
  954. info.AddValue ("actualUri", actualUri, typeof (Uri));
  955. info.AddValue ("allowAutoRedirect", allowAutoRedirect);
  956. info.AddValue ("allowBuffering", allowBuffering);
  957. info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
  958. info.AddValue ("connectionGroup", connectionGroup);
  959. info.AddValue ("contentLength", contentLength);
  960. info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
  961. info.AddValue ("keepAlive", keepAlive);
  962. info.AddValue ("maxAutoRedirect", maxAutoRedirect);
  963. info.AddValue ("mediaType", mediaType);
  964. info.AddValue ("method", method);
  965. info.AddValue ("initialMethod", initialMethod);
  966. info.AddValue ("pipelined", pipelined);
  967. info.AddValue ("version", version, typeof (Version));
  968. info.AddValue ("proxy", proxy, typeof (IWebProxy));
  969. info.AddValue ("sendChunked", sendChunked);
  970. info.AddValue ("timeout", timeout);
  971. info.AddValue ("redirects", redirects);
  972. info.AddValue ("host", host);
  973. }
  974. void CheckRequestStarted ()
  975. {
  976. if (requestSent)
  977. throw new InvalidOperationException ("request started");
  978. }
  979. internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
  980. {
  981. if (continueDelegate != null)
  982. continueDelegate (statusCode, headers);
  983. }
  984. void RewriteRedirectToGet ()
  985. {
  986. method = "GET";
  987. webHeaders.RemoveInternal ("Transfer-Encoding");
  988. sendChunked = false;
  989. }
  990. bool Redirect (WebAsyncResult result, HttpStatusCode code, WebResponse response)
  991. {
  992. redirects++;
  993. Exception e = null;
  994. string uriString = null;
  995. switch (code) {
  996. case HttpStatusCode.Ambiguous: // 300
  997. e = new WebException ("Ambiguous redirect.");
  998. break;
  999. case HttpStatusCode.MovedPermanently: // 301
  1000. case HttpStatusCode.Redirect: // 302
  1001. if (method == "POST")
  1002. RewriteRedirectToGet ();
  1003. break;
  1004. case HttpStatusCode.TemporaryRedirect: // 307
  1005. break;
  1006. case HttpStatusCode.SeeOther: //303
  1007. RewriteRedirectToGet ();
  1008. break;
  1009. case HttpStatusCode.NotModified: // 304
  1010. return false;
  1011. case HttpStatusCode.UseProxy: // 305
  1012. e = new NotImplementedException ("Proxy support not available.");
  1013. break;
  1014. case HttpStatusCode.Unused: // 306
  1015. default:
  1016. e = new ProtocolViolationException ("Invalid status code: " + (int) code);
  1017. break;
  1018. }
  1019. if (method != "GET" && !InternalAllowBuffering && (writeStream.WriteBufferLength > 0 || contentLength > 0))
  1020. e = new WebException ("The request requires buffering data to succeed.", null, WebExceptionStatus.ProtocolError, webResponse);
  1021. if (e != null)
  1022. throw e;
  1023. if (AllowWriteStreamBuffering || method == "GET")
  1024. contentLength = -1;
  1025. uriString = webResponse.Headers ["Location"];
  1026. if (uriString == null)
  1027. throw new WebException ("No Location header found for " + (int) code,
  1028. WebExceptionStatus.ProtocolError);
  1029. Uri prev = actualUri;
  1030. try {
  1031. actualUri = new Uri (actualUri, uriString);
  1032. } catch (Exception) {
  1033. throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
  1034. uriString, (int) code),
  1035. WebExceptionStatus.ProtocolError);
  1036. }
  1037. hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
  1038. return true;
  1039. }
  1040. string GetHeaders ()
  1041. {
  1042. bool continue100 = false;
  1043. if (sendChunked) {
  1044. continue100 = true;
  1045. webHeaders.ChangeInternal ("Transfer-Encoding", "chunked");
  1046. webHeaders.RemoveInternal ("Content-Length");
  1047. } else if (contentLength != -1) {
  1048. if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
  1049. // We don't send any body with the NTLM Challenge request.
  1050. if (haveContentLength || gotRequestStream || contentLength > 0)
  1051. webHeaders.SetInternal ("Content-Length", "0");
  1052. else
  1053. webHeaders.RemoveInternal ("Content-Length");
  1054. } else {
  1055. if (contentLength > 0)
  1056. continue100 = true;
  1057. if (haveContentLength || gotRequestStream || contentLength > 0)
  1058. webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
  1059. }
  1060. webHeaders.RemoveInternal ("Transfer-Encoding");
  1061. } else {
  1062. webHeaders.RemoveInternal ("Content-Length");
  1063. }
  1064. if (actualVersion == HttpVersion.Version11 && continue100 &&
  1065. servicePoint.SendContinue) { // RFC2616 8.2.3
  1066. webHeaders.ChangeInternal ("Expect" , "100-continue");
  1067. expectContinue = true;
  1068. } else {
  1069. webHeaders.RemoveInternal ("Expect");
  1070. expectContinue = false;
  1071. }
  1072. bool proxy_query = ProxyQuery;
  1073. string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
  1074. webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
  1075. Version proto_version = servicePoint.ProtocolVersion;
  1076. bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
  1077. if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
  1078. if (webHeaders[connectionHeader] == null
  1079. || webHeaders[connectionHeader].IndexOf ("keep-alive", StringComparison.OrdinalIgnoreCase) == -1)
  1080. webHeaders.ChangeInternal (connectionHeader, "keep-alive");
  1081. } else if (!keepAlive && version == HttpVersion.Version11) {
  1082. webHeaders.ChangeInternal (connectionHeader, "close");
  1083. }
  1084. webHeaders.SetInternal ("Host", Host);
  1085. if (cookieContainer != null) {
  1086. string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
  1087. if (cookieHeader != "")
  1088. webHeaders.ChangeInternal ("Cookie", cookieHeader);
  1089. else
  1090. webHeaders.RemoveInternal ("Cookie");
  1091. }
  1092. string accept_encoding = null;
  1093. if ((auto_decomp & DecompressionMethods.GZip) != 0)
  1094. accept_encoding = "gzip";
  1095. if ((auto_decomp & DecompressionMethods.Deflate) != 0)
  1096. accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
  1097. if (accept_encoding != null)
  1098. webHeaders.ChangeInternal ("Accept-Encoding", accept_encoding);
  1099. if (!usedPreAuth && preAuthenticate)
  1100. DoPreAuthenticate ();
  1101. return webHeaders.ToString ();
  1102. }
  1103. void DoPreAuthenticate ()
  1104. {
  1105. bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
  1106. ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
  1107. Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
  1108. if (auth == null)
  1109. return;
  1110. webHeaders.RemoveInternal ("Proxy-Authorization");
  1111. webHeaders.RemoveInternal ("Authorization");
  1112. string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
  1113. webHeaders [authHeader] = auth.Message;
  1114. usedPreAuth = true;
  1115. }
  1116. internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
  1117. {
  1118. if (Aborted)
  1119. return;
  1120. WebAsyncResult r = asyncWrite;
  1121. if (r == null)
  1122. r = asyncRead;
  1123. if (r != null) {
  1124. string msg;
  1125. WebException wex;
  1126. if (exc == null) {
  1127. msg = "Error: " + status;
  1128. wex = new WebException (msg, status);
  1129. } else {
  1130. wex = exc as WebException;
  1131. if (wex == null) {
  1132. msg = String.Format ("Error: {0} ({1})", status, exc.Message);
  1133. wex = new WebException (msg, status, WebExceptionInternalStatus.RequestFatal, exc);
  1134. }
  1135. }
  1136. r.SetCompleted (false, wex);
  1137. r.DoCallback ();
  1138. }
  1139. }
  1140. internal byte[] GetRequestHeaders ()
  1141. {
  1142. StringBuilder req = new StringBuilder ();
  1143. string query;
  1144. if (!ProxyQuery) {
  1145. query = actualUri.PathAndQuery;
  1146. } else {
  1147. query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
  1148. Host,
  1149. actualUri.PathAndQuery);
  1150. }
  1151. if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
  1152. actualVersion = servicePoint.ProtocolVersion;
  1153. } else {
  1154. actualVersion = version;
  1155. }
  1156. req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
  1157. actualVersion.Major, actualVersion.Minor);
  1158. req.Append (GetHeaders ());
  1159. string reqstr = req.ToString ();
  1160. return Encoding.UTF8.GetBytes (reqstr);
  1161. }
  1162. internal void SetWriteStream (WebConnectionStream stream)
  1163. {
  1164. if (Aborted)
  1165. return;
  1166. writeStream = stream;
  1167. if (bodyBuffer != null) {
  1168. webHeaders.RemoveInternal ("Transfer-Encoding");
  1169. contentLength = bodyBufferLength;
  1170. writeStream.SendChunked = false;
  1171. }
  1172. writeStream.SetHeadersAsync (false, result => {
  1173. if (result.GotException) {
  1174. SetWriteStreamError (result.Exception);
  1175. return;
  1176. }
  1177. haveRequest = true;
  1178. SetWriteStreamInner (inner => {
  1179. if (inner.GotException) {
  1180. SetWriteStreamError (inner.Exception);
  1181. return;
  1182. }
  1183. if (asyncWrite != null) {
  1184. asyncWrite.SetCompleted (inner.CompletedSynchronouslyPeek, writeStream);
  1185. asyncWrite.DoCallback ();
  1186. asyncWrite = null;
  1187. }
  1188. });
  1189. });
  1190. }
  1191. void SetWriteStreamInner (SimpleAsyncCallback callback)
  1192. {
  1193. SimpleAsyncResult.Run (result => {
  1194. if (bodyBuffer != null) {
  1195. // The body has been written and buffered. The request "user"
  1196. // won't write it again, so we must do it.
  1197. if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
  1198. // FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
  1199. writeStream.Write (bodyBuffer, 0, bodyBufferLength);
  1200. bodyBuffer = null;
  1201. writeStream.Close ();
  1202. }
  1203. } else if (MethodWithBuffer) {
  1204. if (getResponseCalled && !writeStream.RequestWritten)
  1205. return writeStream.WriteRequestAsync (result);
  1206. }
  1207. return false;
  1208. }, callback);
  1209. }
  1210. void SetWriteStreamError (Exception exc)
  1211. {
  1212. WebException wexc = exc as WebException;
  1213. if (wexc != null)
  1214. SetWriteStreamError (wexc.Status, wexc);
  1215. else
  1216. SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
  1217. }
  1218. internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
  1219. {
  1220. if (Aborted)
  1221. return;
  1222. lock (locker) {
  1223. string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
  1224. WebAsyncResult r = asyncRead;
  1225. if (r == null)
  1226. r = asyncWrite;
  1227. WebException wexc;
  1228. if (e is WebException) {
  1229. wexc = (WebException) e;
  1230. } else {
  1231. wexc = new WebException (msg, e, status, null);
  1232. }
  1233. if (r != null) {
  1234. if (!r.IsCompleted) {
  1235. r.SetCompleted (false, wexc);
  1236. r.DoCallback ();
  1237. } else if (r == asyncWrite) {
  1238. saved_exc = wexc;
  1239. }
  1240. haveResponse = true;
  1241. asyncRead = null;
  1242. asyncWrite = null;
  1243. } else {
  1244. haveResponse = true;
  1245. saved_exc = wexc;
  1246. }
  1247. }
  1248. }
  1249. void CheckSendError (WebConnectionData data)
  1250. {
  1251. // Got here, but no one called GetResponse
  1252. int status = data.StatusCode;
  1253. if (status < 400 || status == 401 || status == 407)
  1254. return;
  1255. if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
  1256. // The request has not been completely sent and we got here!
  1257. // We should probably just close and cause an error in any case,
  1258. saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
  1259. if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
  1260. webResponse.ReadAll ();
  1261. } else {
  1262. writeStream.IgnoreIOErrors = true;
  1263. }
  1264. }
  1265. }
  1266. bool HandleNtlmAuth (WebAsyncResult r)
  1267. {
  1268. bool isProxy = webResponse.StatusCode == HttpStatusCode.ProxyAuthenticationRequired;
  1269. if ((isProxy ? proxy_auth_state.NtlmAuthState : auth_state.NtlmAuthState) == NtlmAuthState.None)
  1270. return false;
  1271. WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
  1272. if (wce != null) {
  1273. WebConnection cnc = wce.Connection;
  1274. cnc.PriorityRequest = this;
  1275. ICredentials creds = (!isProxy || proxy == null) ? credentials : proxy.Credentials;
  1276. if (creds != null) {
  1277. cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
  1278. cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
  1279. }
  1280. }
  1281. r.Reset ();
  1282. finished_reading = false;
  1283. haveResponse = false;
  1284. webResponse.ReadAll ();
  1285. webResponse = null;
  1286. return true;
  1287. }
  1288. internal void SetResponseData (WebConnectionData data)
  1289. {
  1290. lock (locker) {
  1291. if (Aborted) {
  1292. if (data.stream != null)
  1293. data.stream.Close ();
  1294. return;
  1295. }
  1296. WebException wexc = null;
  1297. try {
  1298. webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
  1299. } catch (Exception e) {
  1300. wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
  1301. if (data.stream != null)
  1302. data.stream.Close ();
  1303. }
  1304. if (wexc == null && (method == "POST" || method == "PUT")) {
  1305. CheckSendError (data);
  1306. if (saved_exc != null)
  1307. wexc = (WebException) saved_exc;
  1308. }
  1309. WebAsyncResult r = asyncRead;
  1310. bool forced = false;
  1311. if (r == null && webResponse != null) {
  1312. // This is a forced completion (302, 204)...
  1313. forced = true;
  1314. r = new WebAsyncResult (null, null);
  1315. r.SetCompleted (false, webResponse);
  1316. }
  1317. if (r != null) {
  1318. if (wexc != null) {
  1319. haveResponse = true;
  1320. if (!r.IsCompleted)
  1321. r.SetCompleted (false, wexc);
  1322. r.DoCallback ();
  1323. return;
  1324. }
  1325. bool isProxy = ProxyQuery && proxy != null && !proxy.IsBypassed (actualUri);
  1326. bool redirected;
  1327. try {
  1328. redirected = CheckFinalStatus (r);
  1329. if (!redirected) {
  1330. if ((isProxy ? proxy_auth_state.IsNtlmAuthenticated : auth_state.IsNtlmAuthenticated) &&
  1331. webResponse != null && (int)webResponse.StatusCode < 400) {
  1332. WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
  1333. if (wce != null) {
  1334. WebConnection cnc = wce.Connection;
  1335. cnc.NtlmAuthenticated = true;
  1336. }
  1337. }
  1338. // clear internal buffer so that it does not
  1339. // hold possible big buffer (bug #397627)
  1340. if (writeStream != null)
  1341. writeStream.KillBuffer ();
  1342. haveResponse = true;
  1343. r.SetCompleted (false, webResponse);
  1344. r.DoCallback ();
  1345. } else {
  1346. if (sendChunked) {
  1347. sendChunked = false;
  1348. webHeaders.RemoveInternal ("Transfer-Encoding");
  1349. }
  1350. if (webResponse != null) {
  1351. if (HandleNtlmAuth (r))
  1352. return;
  1353. webResponse.Close ();
  1354. }
  1355. finished_reading = false;
  1356. haveResponse = false;
  1357. webResponse = null;
  1358. r.Reset ();
  1359. servicePoint = GetServicePoint ();
  1360. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  1361. }
  1362. } catch (WebException wexc2) {
  1363. if (forced) {
  1364. saved_exc = wexc2;
  1365. haveResponse = true;
  1366. }
  1367. r.SetCompleted (false, wexc2);
  1368. r.DoCallback ();
  1369. return;
  1370. } catch (Exception ex) {
  1371. wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
  1372. if (forced) {
  1373. saved_exc = wexc;
  1374. haveResponse = true;
  1375. }
  1376. r.SetCompleted (false, wexc);
  1377. r.DoCallback ();
  1378. return;
  1379. }
  1380. }
  1381. }
  1382. }
  1383. struct AuthorizationState
  1384. {
  1385. readonly HttpWebRequest request;
  1386. readonly bool isProxy;
  1387. bool isCompleted;
  1388. NtlmAuthState ntlm_auth_state;
  1389. public bool IsCompleted {
  1390. get { return isCompleted; }
  1391. }
  1392. public NtlmAuthState NtlmAuthState {
  1393. get { return ntlm_auth_state; }
  1394. }
  1395. public bool IsNtlmAuthenticated {
  1396. get { return isCompleted && ntlm_auth_state != NtlmAuthState.None; }
  1397. }
  1398. public AuthorizationState (HttpWebRequest request, bool isProxy)
  1399. {
  1400. this.request = request;
  1401. this.isProxy = isProxy;
  1402. isCompleted = false;
  1403. ntlm_auth_state = NtlmAuthState.None;
  1404. }
  1405. public bool CheckAuthorization (WebResponse response, HttpStatusCode code)
  1406. {
  1407. isCompleted = false;
  1408. if (code == HttpStatusCode.Unauthorized && request.credentials == null)
  1409. return false;
  1410. // FIXME: This should never happen!
  1411. if (isProxy != (code == HttpStatusCode.ProxyAuthenticationRequired))
  1412. return false;
  1413. if (isProxy && (request.proxy == null || request.proxy.Credentials == null))
  1414. return false;
  1415. string [] authHeaders = response.Headers.GetValues (isProxy ? "Proxy-Authenticate" : "WWW-Authenticate");
  1416. if (authHeaders == null || authHeaders.Length == 0)
  1417. return false;
  1418. ICredentials creds = (!isProxy) ? request.credentials : request.proxy.Credentials;
  1419. Authorization auth = null;
  1420. foreach (string authHeader in authHeaders) {
  1421. auth = AuthenticationManager.Authenticate (authHeader, request, creds);
  1422. if (auth != null)
  1423. break;
  1424. }
  1425. if (auth == null)
  1426. return false;
  1427. request.webHeaders [isProxy ? "Proxy-Authorization" : "Authorization"] = auth.Message;
  1428. isCompleted = auth.Complete;
  1429. bool is_ntlm = (auth.ModuleAuthenticationType == "NTLM");
  1430. if (is_ntlm)
  1431. ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
  1432. return true;
  1433. }
  1434. public void Reset ()
  1435. {
  1436. isCompleted = false;
  1437. ntlm_auth_state = NtlmAuthState.None;
  1438. request.webHeaders.RemoveInternal (isProxy ? "Proxy-Authorization" : "Authorization");
  1439. }
  1440. public override string ToString ()
  1441. {
  1442. return string.Format ("{0}AuthState [{1}:{2}]", isProxy ? "Proxy" : "", isCompleted, ntlm_auth_state);
  1443. }
  1444. }
  1445. bool CheckAuthorization (WebResponse response, HttpStatusCode code)
  1446. {
  1447. bool isProxy = code == HttpStatusCode.ProxyAuthenticationRequired;
  1448. return isProxy ? proxy_auth_state.CheckAuthorization (response, code) : auth_state.CheckAuthorization (response, code);
  1449. }
  1450. // Returns true if redirected
  1451. bool CheckFinalStatus (WebAsyncResult result)
  1452. {
  1453. if (result.GotException) {
  1454. bodyBuffer = null;
  1455. throw result.Exception;
  1456. }
  1457. Exception throwMe = result.Exception;
  1458. HttpWebResponse resp = result.Response;
  1459. WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
  1460. HttpStatusCode code = 0;
  1461. if (throwMe == null && webResponse != null) {
  1462. code = webResponse.StatusCode;
  1463. if ((!auth_state.IsCompleted && code == HttpStatusCode.Unauthorized && credentials != null) ||
  1464. (ProxyQuery && !proxy_auth_state.IsCompleted && code == HttpStatusCode.ProxyAuthenticationRequired)) {
  1465. if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
  1466. // Keep the written body, so it can be rewritten in the retry
  1467. if (MethodWithBuffer) {
  1468. if (AllowWriteStreamBuffering) {
  1469. if (writeStream.WriteBufferLength > 0) {
  1470. bodyBuffer = writeStream.WriteBuffer;
  1471. bodyBufferLength = writeStream.WriteBufferLength;
  1472. }
  1473. return true;
  1474. }
  1475. //
  1476. // Buffering is not allowed but we have alternative way to get same content (we
  1477. // need to resent it due to NTLM Authentication).
  1478. //
  1479. if (ResendContentFactory != null) {
  1480. using (var ms = new MemoryStream ()) {
  1481. ResendContentFactory (ms);
  1482. bodyBuffer = ms.ToArray ();
  1483. bodyBufferLength = bodyBuffer.Length;
  1484. }
  1485. return true;
  1486. }
  1487. } else if (method != "PUT" && method != "POST") {
  1488. bodyBuffer = null;
  1489. return true;
  1490. }
  1491. if (!ThrowOnError)
  1492. return false;
  1493. writeStream.InternalClose ();
  1494. writeStream = null;
  1495. webResponse.Close ();
  1496. webResponse = null;
  1497. bodyBuffer = null;
  1498. throw new WebException ("This request requires buffering " +
  1499. "of data for authentication or " +
  1500. "redirection to be sucessful.");
  1501. }
  1502. }
  1503. bodyBuffer = null;
  1504. if ((int) code >= 400) {
  1505. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  1506. (int) code, webResponse.StatusDescription);
  1507. throwMe = new WebException (err, null, protoError, webResponse);
  1508. webResponse.ReadAll ();
  1509. } else if ((int) code == 304 && allowAutoRedirect) {
  1510. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  1511. (int) code, webResponse.StatusDescription);
  1512. throwMe = new WebException (err, null, protoError, webResponse);
  1513. } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
  1514. throwMe = new WebException ("Max. redirections exceeded.", null,
  1515. protoError, webResponse);
  1516. webResponse.ReadAll ();
  1517. }
  1518. }
  1519. bodyBuffer = null;
  1520. if (throwMe == null) {
  1521. bool b = false;
  1522. int c = (int) code;
  1523. if (allowAutoRedirect && c >= 300) {
  1524. b = Redirect (result, code, webResponse);
  1525. if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
  1526. bodyBuffer = writeStream.WriteBuffer;
  1527. bodyBufferLength = writeStream.WriteBufferLength;
  1528. }
  1529. if (b && !unsafe_auth_blah) {
  1530. auth_state.Reset ();
  1531. proxy_auth_state.Reset ();
  1532. }
  1533. }
  1534. if (resp != null && c >= 300 && c != 304)
  1535. resp.ReadAll ();
  1536. return b;
  1537. }
  1538. if (!ThrowOnError)
  1539. return false;
  1540. if (writeStream != null) {
  1541. writeStream.InternalClose ();
  1542. writeStream = null;
  1543. }
  1544. webResponse = null;
  1545. throw throwMe;
  1546. }
  1547. internal bool ReuseConnection {
  1548. get;
  1549. set;
  1550. }
  1551. internal WebConnection StoredConnection;
  1552. #region referencesource
  1553. internal static StringBuilder GenerateConnectionGroup(string connectionGroupName, bool unsafeConnectionGroup, bool isInternalGroup)
  1554. {
  1555. StringBuilder connectionLine = new StringBuilder(connectionGroupName);
  1556. connectionLine.Append(unsafeConnectionGroup ? "U>" : "S>");
  1557. if (isInternalGroup)
  1558. {
  1559. connectionLine.Append("I>");
  1560. }
  1561. return connectionLine;
  1562. }
  1563. #endregion
  1564. }
  1565. }