HttpWebRequest.cs 48 KB

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