HttpWebRequest.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. //
  2. // System.Net.HttpWebRequest
  3. //
  4. // Authors:
  5. // Lawrence Pit ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. //
  8. // (c) 2002 Lawrence Pit
  9. // (c) 2003 Ximian, Inc. (http://www.ximian.com)
  10. // (c) 2004 Novell, Inc. (http://www.novell.com)
  11. //
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System;
  33. using System.Collections;
  34. using System.Configuration;
  35. using System.IO;
  36. using System.Net.Sockets;
  37. using System.Runtime.Remoting.Messaging;
  38. using System.Runtime.Serialization;
  39. using System.Security.Cryptography.X509Certificates;
  40. using System.Text;
  41. using System.Threading;
  42. #if NET_2_0
  43. using System.Net.Cache;
  44. #endif
  45. namespace System.Net
  46. {
  47. [Serializable]
  48. public class HttpWebRequest : WebRequest, ISerializable
  49. {
  50. Uri requestUri;
  51. Uri actualUri;
  52. bool hostChanged;
  53. bool allowAutoRedirect = true;
  54. bool allowBuffering = true;
  55. X509CertificateCollection certificates;
  56. string connectionGroup;
  57. long contentLength = -1;
  58. HttpContinueDelegate continueDelegate;
  59. CookieContainer cookieContainer;
  60. ICredentials credentials;
  61. bool haveResponse;
  62. bool haveRequest;
  63. bool requestSent;
  64. WebHeaderCollection webHeaders = new WebHeaderCollection (true);
  65. bool keepAlive = true;
  66. int maxAutoRedirect = 50;
  67. string mediaType = String.Empty;
  68. string method = "GET";
  69. string initialMethod = "GET";
  70. bool pipelined = true;
  71. bool preAuthenticate;
  72. bool usedPreAuth;
  73. Version version = HttpVersion.Version11;
  74. Version actualVersion;
  75. IWebProxy proxy;
  76. bool sendChunked;
  77. ServicePoint servicePoint;
  78. int timeout = 100000;
  79. WebConnectionStream writeStream;
  80. HttpWebResponse webResponse;
  81. WebAsyncResult asyncWrite;
  82. WebAsyncResult asyncRead;
  83. EventHandler abortHandler;
  84. bool aborted;
  85. bool gotRequestStream;
  86. int redirects;
  87. bool expectContinue;
  88. bool authCompleted;
  89. byte[] bodyBuffer;
  90. int bodyBufferLength;
  91. bool getResponseCalled;
  92. Exception saved_exc;
  93. object locker = new object ();
  94. bool is_ntlm_auth;
  95. #if NET_1_1
  96. int maxResponseHeadersLength;
  97. static int defaultMaxResponseHeadersLength;
  98. int readWriteTimeout = 300000; // ms
  99. // Constructors
  100. static HttpWebRequest ()
  101. {
  102. NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
  103. defaultMaxResponseHeadersLength = 64 * 1024;
  104. if (config != null) {
  105. int x = config.MaxResponseHeadersLength;
  106. if (x != -1)
  107. x *= 64;
  108. defaultMaxResponseHeadersLength = x;
  109. }
  110. }
  111. #endif
  112. #if NET_2_1
  113. public
  114. #else
  115. internal
  116. #endif
  117. HttpWebRequest (Uri uri)
  118. {
  119. this.requestUri = uri;
  120. this.actualUri = uri;
  121. this.proxy = GlobalProxySelection.Select;
  122. }
  123. #if NET_2_0
  124. [Obsolete ("Serialization is obsoleted for this type", false)]
  125. #endif
  126. protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
  127. {
  128. SerializationInfo info = serializationInfo;
  129. requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
  130. actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
  131. allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
  132. allowBuffering = info.GetBoolean ("allowBuffering");
  133. certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
  134. connectionGroup = info.GetString ("connectionGroup");
  135. contentLength = info.GetInt64 ("contentLength");
  136. webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
  137. keepAlive = info.GetBoolean ("keepAlive");
  138. maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
  139. mediaType = info.GetString ("mediaType");
  140. method = info.GetString ("method");
  141. initialMethod = info.GetString ("initialMethod");
  142. pipelined = info.GetBoolean ("pipelined");
  143. version = (Version) info.GetValue ("version", typeof (Version));
  144. proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
  145. sendChunked = info.GetBoolean ("sendChunked");
  146. timeout = info.GetInt32 ("timeout");
  147. redirects = info.GetInt32 ("redirects");
  148. }
  149. // Properties
  150. internal bool UsesNtlmAuthentication {
  151. get { return is_ntlm_auth; }
  152. }
  153. public string Accept {
  154. get { return webHeaders ["Accept"]; }
  155. set {
  156. CheckRequestStarted ();
  157. webHeaders.RemoveAndAdd ("Accept", value);
  158. }
  159. }
  160. public Uri Address {
  161. get { return actualUri; }
  162. }
  163. public bool AllowAutoRedirect {
  164. get { return allowAutoRedirect; }
  165. set { this.allowAutoRedirect = value; }
  166. }
  167. public bool AllowWriteStreamBuffering {
  168. get { return allowBuffering; }
  169. set { allowBuffering = value; }
  170. }
  171. #if NET_2_0
  172. static Exception GetMustImplement ()
  173. {
  174. return new NotImplementedException ();
  175. }
  176. [MonoTODO]
  177. public DecompressionMethods AutomaticDecompression
  178. {
  179. get {
  180. throw GetMustImplement ();
  181. }
  182. set {
  183. throw GetMustImplement ();
  184. }
  185. }
  186. #endif
  187. internal bool InternalAllowBuffering {
  188. get {
  189. return (allowBuffering && (method != "HEAD" && method != "GET" &&
  190. method != "MKCOL" && method != "CONNECT" &&
  191. method != "DELETE" && method != "TRACE"));
  192. }
  193. }
  194. public X509CertificateCollection ClientCertificates {
  195. get {
  196. if (certificates == null)
  197. certificates = new X509CertificateCollection ();
  198. return certificates;
  199. }
  200. #if NET_2_0
  201. [MonoTODO]
  202. set {
  203. throw GetMustImplement ();
  204. }
  205. #endif
  206. }
  207. public string Connection {
  208. get { return webHeaders ["Connection"]; }
  209. set {
  210. CheckRequestStarted ();
  211. string val = value;
  212. if (val != null)
  213. val = val.Trim ().ToLower ();
  214. if (val == null || val.Length == 0) {
  215. webHeaders.RemoveInternal ("Connection");
  216. return;
  217. }
  218. if (val == "keep-alive" || val == "close")
  219. throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
  220. if (keepAlive && val.IndexOf ("keep-alive") == -1)
  221. value = value + ", Keep-Alive";
  222. webHeaders.RemoveAndAdd ("Connection", value);
  223. }
  224. }
  225. public override string ConnectionGroupName {
  226. get { return connectionGroup; }
  227. set { connectionGroup = value; }
  228. }
  229. public override long ContentLength {
  230. get { return contentLength; }
  231. set {
  232. CheckRequestStarted ();
  233. if (value < 0)
  234. throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
  235. contentLength = value;
  236. }
  237. }
  238. internal long InternalContentLength {
  239. set { contentLength = value; }
  240. }
  241. public override string ContentType {
  242. get { return webHeaders ["Content-Type"]; }
  243. set {
  244. if (value == null || value.Trim().Length == 0) {
  245. webHeaders.RemoveInternal ("Content-Type");
  246. return;
  247. }
  248. webHeaders.RemoveAndAdd ("Content-Type", value);
  249. }
  250. }
  251. public HttpContinueDelegate ContinueDelegate {
  252. get { return continueDelegate; }
  253. set { continueDelegate = value; }
  254. }
  255. public CookieContainer CookieContainer {
  256. get { return cookieContainer; }
  257. set { cookieContainer = value; }
  258. }
  259. public override ICredentials Credentials {
  260. get { return credentials; }
  261. set { credentials = value; }
  262. }
  263. #if NET_2_0
  264. [MonoTODO]
  265. public static new RequestCachePolicy DefaultCachePolicy
  266. {
  267. get {
  268. throw GetMustImplement ();
  269. }
  270. set {
  271. throw GetMustImplement ();
  272. }
  273. }
  274. [MonoTODO]
  275. public static int DefaultMaximumErrorResponseLength
  276. {
  277. get {
  278. throw GetMustImplement ();
  279. }
  280. set {
  281. throw GetMustImplement ();
  282. }
  283. }
  284. #endif
  285. public string Expect {
  286. get { return webHeaders ["Expect"]; }
  287. set {
  288. CheckRequestStarted ();
  289. string val = value;
  290. if (val != null)
  291. val = val.Trim ().ToLower ();
  292. if (val == null || val.Length == 0) {
  293. webHeaders.RemoveInternal ("Expect");
  294. return;
  295. }
  296. if (val == "100-continue")
  297. throw new ArgumentException ("100-Continue cannot be set with this property.",
  298. "value");
  299. webHeaders.RemoveAndAdd ("Expect", value);
  300. }
  301. }
  302. public bool HaveResponse {
  303. get { return haveResponse; }
  304. }
  305. public override WebHeaderCollection Headers {
  306. get { return webHeaders; }
  307. set {
  308. CheckRequestStarted ();
  309. WebHeaderCollection newHeaders = new WebHeaderCollection (true);
  310. int count = value.Count;
  311. for (int i = 0; i < count; i++)
  312. newHeaders.Add (value.GetKey (i), value.Get (i));
  313. webHeaders = newHeaders;
  314. }
  315. }
  316. public DateTime IfModifiedSince {
  317. get {
  318. string str = webHeaders ["If-Modified-Since"];
  319. if (str == null)
  320. return DateTime.Now;
  321. try {
  322. return MonoHttpDate.Parse (str);
  323. } catch (Exception) {
  324. return DateTime.Now;
  325. }
  326. }
  327. set {
  328. CheckRequestStarted ();
  329. // rfc-1123 pattern
  330. webHeaders.SetInternal ("If-Modified-Since",
  331. value.ToUniversalTime ().ToString ("r", null));
  332. // TODO: check last param when using different locale
  333. }
  334. }
  335. public bool KeepAlive {
  336. get {
  337. return keepAlive;
  338. }
  339. set {
  340. keepAlive = value;
  341. }
  342. }
  343. public int MaximumAutomaticRedirections {
  344. get { return maxAutoRedirect; }
  345. set {
  346. if (value <= 0)
  347. throw new ArgumentException ("Must be > 0", "value");
  348. maxAutoRedirect = value;
  349. }
  350. }
  351. #if NET_1_1
  352. [MonoTODO ("Use this")]
  353. public int MaximumResponseHeadersLength {
  354. get { return maxResponseHeadersLength; }
  355. set { maxResponseHeadersLength = value; }
  356. }
  357. [MonoTODO ("Use this")]
  358. public static int DefaultMaximumResponseHeadersLength {
  359. get { return defaultMaxResponseHeadersLength; }
  360. set { defaultMaxResponseHeadersLength = value; }
  361. }
  362. public
  363. #else
  364. internal
  365. #endif
  366. int ReadWriteTimeout {
  367. get { return readWriteTimeout; }
  368. set {
  369. if (requestSent)
  370. throw new InvalidOperationException ("The request has already been sent.");
  371. if (value < -1)
  372. throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
  373. readWriteTimeout = value;
  374. }
  375. }
  376. public string MediaType {
  377. get { return mediaType; }
  378. set {
  379. mediaType = value;
  380. }
  381. }
  382. public override string Method {
  383. get { return this.method; }
  384. set {
  385. if (value == null || value.Trim () == "")
  386. throw new ArgumentException ("not a valid method");
  387. method = value;
  388. }
  389. }
  390. public bool Pipelined {
  391. get { return pipelined; }
  392. set { pipelined = value; }
  393. }
  394. public override bool PreAuthenticate {
  395. get { return preAuthenticate; }
  396. set { preAuthenticate = value; }
  397. }
  398. public Version ProtocolVersion {
  399. get { return version; }
  400. set {
  401. if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
  402. throw new ArgumentException ("value");
  403. version = value;
  404. }
  405. }
  406. public override IWebProxy Proxy {
  407. get { return proxy; }
  408. set {
  409. CheckRequestStarted ();
  410. #if ONLY_1_1
  411. if (value == null)
  412. throw new ArgumentNullException ("value");
  413. #endif
  414. proxy = value;
  415. servicePoint = null; // we may need a new one
  416. }
  417. }
  418. public string Referer {
  419. get { return webHeaders ["Referer"]; }
  420. set {
  421. CheckRequestStarted ();
  422. if (value == null || value.Trim().Length == 0) {
  423. webHeaders.RemoveInternal ("Referer");
  424. return;
  425. }
  426. webHeaders.SetInternal ("Referer", value);
  427. }
  428. }
  429. public override Uri RequestUri {
  430. get { return requestUri; }
  431. }
  432. public bool SendChunked {
  433. get { return sendChunked; }
  434. set {
  435. CheckRequestStarted ();
  436. sendChunked = value;
  437. }
  438. }
  439. public ServicePoint ServicePoint {
  440. get { return GetServicePoint (); }
  441. }
  442. public override int Timeout {
  443. get { return timeout; }
  444. set {
  445. if (value < -1)
  446. throw new ArgumentOutOfRangeException ("value");
  447. timeout = value;
  448. }
  449. }
  450. public string TransferEncoding {
  451. get { return webHeaders ["Transfer-Encoding"]; }
  452. set {
  453. CheckRequestStarted ();
  454. string val = value;
  455. if (val != null)
  456. val = val.Trim ().ToLower ();
  457. if (val == null || val.Length == 0) {
  458. webHeaders.RemoveInternal ("Transfer-Encoding");
  459. return;
  460. }
  461. if (val == "chunked")
  462. throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
  463. if (!sendChunked)
  464. throw new ArgumentException ("SendChunked must be True", "value");
  465. webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
  466. }
  467. }
  468. #if NET_2_0
  469. [MonoTODO]
  470. public override bool UseDefaultCredentials
  471. {
  472. get {
  473. throw GetMustImplement ();
  474. }
  475. set {
  476. throw GetMustImplement ();
  477. }
  478. }
  479. #endif
  480. public string UserAgent {
  481. get { return webHeaders ["User-Agent"]; }
  482. set { webHeaders.SetInternal ("User-Agent", value); }
  483. }
  484. #if NET_1_1
  485. bool unsafe_auth_blah;
  486. public bool UnsafeAuthenticatedConnectionSharing
  487. {
  488. get { return unsafe_auth_blah; }
  489. set { unsafe_auth_blah = value; }
  490. }
  491. #endif
  492. internal bool GotRequestStream {
  493. get { return gotRequestStream; }
  494. }
  495. internal bool ExpectContinue {
  496. get { return expectContinue; }
  497. set { expectContinue = value; }
  498. }
  499. internal Uri AuthUri {
  500. get { return actualUri; }
  501. }
  502. internal bool ProxyQuery {
  503. get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
  504. }
  505. // Methods
  506. internal ServicePoint GetServicePoint ()
  507. {
  508. lock (locker) {
  509. if (hostChanged || servicePoint == null) {
  510. servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
  511. hostChanged = false;
  512. }
  513. }
  514. return servicePoint;
  515. }
  516. public void AddRange (int range)
  517. {
  518. AddRange ("bytes", range);
  519. }
  520. public void AddRange (int from, int to)
  521. {
  522. AddRange ("bytes", from, to);
  523. }
  524. public void AddRange (string rangeSpecifier, int range)
  525. {
  526. if (rangeSpecifier == null)
  527. throw new ArgumentNullException ("rangeSpecifier");
  528. string value = webHeaders ["Range"];
  529. if (value == null || value.Length == 0)
  530. value = rangeSpecifier + "=";
  531. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  532. value += ",";
  533. else
  534. throw new InvalidOperationException ("rangeSpecifier");
  535. webHeaders.RemoveAndAdd ("Range", value + range + "-");
  536. }
  537. public void AddRange (string rangeSpecifier, int from, int to)
  538. {
  539. if (rangeSpecifier == null)
  540. throw new ArgumentNullException ("rangeSpecifier");
  541. if (from < 0 || to < 0 || from > to)
  542. throw new ArgumentOutOfRangeException ();
  543. string value = webHeaders ["Range"];
  544. if (value == null || value.Length == 0)
  545. value = rangeSpecifier + "=";
  546. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  547. value += ",";
  548. else
  549. throw new InvalidOperationException ("rangeSpecifier");
  550. webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);
  551. }
  552. #if !NET_2_0
  553. public override int GetHashCode ()
  554. {
  555. return base.GetHashCode ();
  556. }
  557. #endif
  558. void CommonChecks (bool putpost)
  559. {
  560. if (method == null)
  561. throw new ProtocolViolationException ("Method is null.");
  562. if (putpost && ((!keepAlive || (contentLength == -1 && !sendChunked)) && !allowBuffering))
  563. throw new ProtocolViolationException ("Content-Length not set");
  564. string transferEncoding = TransferEncoding;
  565. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  566. throw new ProtocolViolationException ("SendChunked should be true.");
  567. }
  568. public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  569. {
  570. if (aborted)
  571. throw new WebException ("The request was previosly aborted.");
  572. bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
  573. method == "TRACE" || method == "DELETE");
  574. if (method == null || !send)
  575. throw new ProtocolViolationException ("Cannot send data when method is: " + method);
  576. CommonChecks (send);
  577. lock (locker)
  578. {
  579. if (asyncWrite != null) {
  580. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  581. "method while a previous call is still in progress.");
  582. }
  583. asyncWrite = new WebAsyncResult (this, callback, state);
  584. initialMethod = method;
  585. if (haveRequest) {
  586. if (writeStream != null) {
  587. asyncWrite.SetCompleted (true, writeStream);
  588. asyncWrite.DoCallback ();
  589. return asyncWrite;
  590. }
  591. }
  592. gotRequestStream = true;
  593. WebAsyncResult result = asyncWrite;
  594. if (!requestSent) {
  595. requestSent = true;
  596. redirects = 0;
  597. servicePoint = GetServicePoint ();
  598. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  599. }
  600. return result;
  601. }
  602. }
  603. public override Stream EndGetRequestStream (IAsyncResult asyncResult)
  604. {
  605. if (asyncResult == null)
  606. throw new ArgumentNullException ("asyncResult");
  607. WebAsyncResult result = asyncResult as WebAsyncResult;
  608. if (result == null)
  609. throw new ArgumentException ("Invalid IAsyncResult");
  610. asyncWrite = result;
  611. result.WaitUntilComplete ();
  612. Exception e = result.Exception;
  613. if (e != null)
  614. throw e;
  615. return result.WriteStream;
  616. }
  617. public override Stream GetRequestStream()
  618. {
  619. IAsyncResult asyncResult = asyncWrite;
  620. if (asyncResult == null) {
  621. asyncResult = BeginGetRequestStream (null, null);
  622. asyncWrite = (WebAsyncResult) asyncResult;
  623. }
  624. if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
  625. Abort ();
  626. throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
  627. }
  628. return EndGetRequestStream (asyncResult);
  629. }
  630. void CheckIfForceWrite ()
  631. {
  632. if (writeStream == null || contentLength < 0 || !InternalAllowBuffering)
  633. return;
  634. // This will write the POST/PUT if the write stream already has the expected
  635. // amount of bytes in it (ContentLength) (bug #77753).
  636. if (writeStream.WriteBufferLength == contentLength)
  637. writeStream.WriteRequest ();
  638. }
  639. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  640. {
  641. bool send = (method == "PUT" || method == "POST");
  642. if (send) {
  643. if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
  644. throw new ProtocolViolationException ("Content-Length not set");
  645. }
  646. CommonChecks (send);
  647. Monitor.Enter (this);
  648. getResponseCalled = true;
  649. if (asyncRead != null && !haveResponse) {
  650. Monitor.Exit (this);
  651. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  652. "method while a previous call is still in progress.");
  653. }
  654. CheckIfForceWrite ();
  655. asyncRead = new WebAsyncResult (this, callback, state);
  656. WebAsyncResult aread = asyncRead;
  657. initialMethod = method;
  658. if (haveResponse) {
  659. if (webResponse != null) {
  660. Exception saved = saved_exc;
  661. Monitor.Exit (this);
  662. if (saved == null) {
  663. aread.SetCompleted (true, webResponse);
  664. } else {
  665. aread.SetCompleted (true, saved);
  666. }
  667. aread.DoCallback ();
  668. return aread;
  669. }
  670. }
  671. if (!requestSent) {
  672. requestSent = true;
  673. redirects = 0;
  674. servicePoint = GetServicePoint ();
  675. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  676. }
  677. Monitor.Exit (this);
  678. return aread;
  679. }
  680. public override WebResponse EndGetResponse (IAsyncResult asyncResult)
  681. {
  682. if (asyncResult == null)
  683. throw new ArgumentNullException ("asyncResult");
  684. WebAsyncResult result = asyncResult as WebAsyncResult;
  685. if (result == null)
  686. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  687. if (!result.WaitUntilComplete (timeout, false)) {
  688. Abort ();
  689. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  690. }
  691. if (result.GotException)
  692. throw result.Exception;
  693. return result.Response;
  694. }
  695. public override WebResponse GetResponse()
  696. {
  697. WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
  698. return EndGetResponse (result);
  699. }
  700. public override void Abort ()
  701. {
  702. haveResponse = true;
  703. aborted = true;
  704. if (asyncWrite != null) {
  705. WebAsyncResult r = asyncWrite;
  706. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  707. r.SetCompleted (false, wexc);
  708. r.DoCallback ();
  709. asyncWrite = null;
  710. }
  711. if (asyncRead != null) {
  712. WebAsyncResult r = asyncRead;
  713. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  714. r.SetCompleted (false, wexc);
  715. r.DoCallback ();
  716. asyncRead = null;
  717. }
  718. if (abortHandler != null) {
  719. try {
  720. abortHandler (this, EventArgs.Empty);
  721. } catch (Exception) {}
  722. abortHandler = null;
  723. }
  724. if (writeStream != null) {
  725. try {
  726. writeStream.Close ();
  727. writeStream = null;
  728. } catch {}
  729. }
  730. if (webResponse != null) {
  731. try {
  732. webResponse.Close ();
  733. webResponse = null;
  734. } catch {}
  735. }
  736. }
  737. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  738. StreamingContext streamingContext)
  739. {
  740. GetObjectData (serializationInfo, streamingContext);
  741. }
  742. #if NET_2_0
  743. protected override
  744. #endif
  745. void GetObjectData (SerializationInfo serializationInfo,
  746. StreamingContext streamingContext)
  747. {
  748. SerializationInfo info = serializationInfo;
  749. info.AddValue ("requestUri", requestUri, typeof (Uri));
  750. info.AddValue ("actualUri", actualUri, typeof (Uri));
  751. info.AddValue ("allowAutoRedirect", allowAutoRedirect);
  752. info.AddValue ("allowBuffering", allowBuffering);
  753. info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
  754. info.AddValue ("connectionGroup", connectionGroup);
  755. info.AddValue ("contentLength", contentLength);
  756. info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
  757. info.AddValue ("keepAlive", keepAlive);
  758. info.AddValue ("maxAutoRedirect", maxAutoRedirect);
  759. info.AddValue ("mediaType", mediaType);
  760. info.AddValue ("method", method);
  761. info.AddValue ("initialMethod", initialMethod);
  762. info.AddValue ("pipelined", pipelined);
  763. info.AddValue ("version", version, typeof (Version));
  764. info.AddValue ("proxy", proxy, typeof (IWebProxy));
  765. info.AddValue ("sendChunked", sendChunked);
  766. info.AddValue ("timeout", timeout);
  767. info.AddValue ("redirects", redirects);
  768. }
  769. void CheckRequestStarted ()
  770. {
  771. if (requestSent)
  772. throw new InvalidOperationException ("request started");
  773. }
  774. internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
  775. {
  776. if (continueDelegate != null)
  777. continueDelegate (statusCode, headers);
  778. }
  779. bool Redirect (WebAsyncResult result, HttpStatusCode code)
  780. {
  781. redirects++;
  782. Exception e = null;
  783. string uriString = null;
  784. switch (code) {
  785. case HttpStatusCode.Ambiguous: // 300
  786. e = new WebException ("Ambiguous redirect.");
  787. break;
  788. case HttpStatusCode.MovedPermanently: // 301
  789. case HttpStatusCode.Redirect: // 302
  790. case HttpStatusCode.TemporaryRedirect: // 307
  791. /* MS follows the redirect for POST too
  792. if (method != "GET" && method != "HEAD") // 10.3
  793. return false;
  794. */
  795. contentLength = 0;
  796. bodyBufferLength = 0;
  797. bodyBuffer = null;
  798. method = "GET";
  799. uriString = webResponse.Headers ["Location"];
  800. break;
  801. case HttpStatusCode.SeeOther: //303
  802. method = "GET";
  803. uriString = webResponse.Headers ["Location"];
  804. break;
  805. case HttpStatusCode.NotModified: // 304
  806. return false;
  807. case HttpStatusCode.UseProxy: // 305
  808. e = new NotImplementedException ("Proxy support not available.");
  809. break;
  810. case HttpStatusCode.Unused: // 306
  811. default:
  812. e = new ProtocolViolationException ("Invalid status code: " + (int) code);
  813. break;
  814. }
  815. if (e != null)
  816. throw e;
  817. if (uriString == null)
  818. throw new WebException ("No Location header found for " + (int) code,
  819. WebExceptionStatus.ProtocolError);
  820. Uri prev = actualUri;
  821. try {
  822. actualUri = new Uri (actualUri, uriString);
  823. } catch (Exception) {
  824. throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
  825. uriString, (int) code),
  826. WebExceptionStatus.ProtocolError);
  827. }
  828. hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host ||
  829. actualUri.Port != prev.Port);
  830. return true;
  831. }
  832. string GetHeaders ()
  833. {
  834. bool continue100 = false;
  835. if (contentLength != -1) {
  836. if (contentLength > 0)
  837. continue100 = true;
  838. webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
  839. webHeaders.RemoveInternal ("Transfer-Encoding");
  840. } else if (sendChunked) {
  841. continue100 = true;
  842. webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
  843. webHeaders.RemoveInternal ("Content-Length");
  844. }
  845. if (actualVersion == HttpVersion.Version11 && continue100 &&
  846. servicePoint.SendContinue) { // RFC2616 8.2.3
  847. webHeaders.RemoveAndAdd ("Expect" , "100-continue");
  848. expectContinue = true;
  849. } else {
  850. webHeaders.RemoveInternal ("Expect");
  851. expectContinue = false;
  852. }
  853. string connectionHeader = (ProxyQuery) ? "Proxy-Connection" : "Connection";
  854. webHeaders.RemoveInternal ((!ProxyQuery) ? "Proxy-Connection" : "Connection");
  855. bool spoint10 = (servicePoint.ProtocolVersion == null ||
  856. servicePoint.ProtocolVersion == HttpVersion.Version10);
  857. if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
  858. webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
  859. } else if (!keepAlive && version == HttpVersion.Version11) {
  860. webHeaders.RemoveAndAdd (connectionHeader, "close");
  861. }
  862. webHeaders.SetInternal ("Host", actualUri.Authority);
  863. if (cookieContainer != null) {
  864. string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
  865. if (cookieHeader != "")
  866. webHeaders.SetInternal ("Cookie", cookieHeader);
  867. }
  868. if (!usedPreAuth && preAuthenticate)
  869. DoPreAuthenticate ();
  870. return webHeaders.ToString ();
  871. }
  872. void DoPreAuthenticate ()
  873. {
  874. webHeaders.RemoveInternal ("Proxy-Authorization");
  875. webHeaders.RemoveInternal ("Authorization");
  876. bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
  877. ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
  878. Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
  879. if (auth == null)
  880. return;
  881. string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
  882. webHeaders [authHeader] = auth.Message;
  883. usedPreAuth = true;
  884. }
  885. internal void SetWriteStreamError (WebExceptionStatus status)
  886. {
  887. if (aborted)
  888. return;
  889. WebAsyncResult r = asyncWrite;
  890. if (r == null)
  891. r = asyncRead;
  892. if (r != null) {
  893. r.SetCompleted (false, new WebException ("Error: " + status, status));
  894. r.DoCallback ();
  895. }
  896. }
  897. internal void SendRequestHeaders ()
  898. {
  899. StringBuilder req = new StringBuilder ();
  900. string query;
  901. if (!ProxyQuery) {
  902. query = actualUri.PathAndQuery;
  903. } else if (actualUri.IsDefaultPort) {
  904. query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
  905. actualUri.Host,
  906. actualUri.PathAndQuery);
  907. } else {
  908. query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
  909. actualUri.Host,
  910. actualUri.Port,
  911. actualUri.PathAndQuery);
  912. }
  913. if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
  914. actualVersion = servicePoint.ProtocolVersion;
  915. } else {
  916. actualVersion = version;
  917. }
  918. req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
  919. actualVersion.Major, actualVersion.Minor);
  920. req.Append (GetHeaders ());
  921. string reqstr = req.ToString ();
  922. byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
  923. try {
  924. writeStream.SetHeaders (bytes, 0, bytes.Length);
  925. } catch (WebException wexc) {
  926. SetWriteStreamError (wexc.Status);
  927. } catch (Exception) {
  928. SetWriteStreamError (WebExceptionStatus.SendFailure);
  929. }
  930. }
  931. internal void SetWriteStream (WebConnectionStream stream)
  932. {
  933. if (aborted)
  934. return;
  935. writeStream = stream;
  936. if (bodyBuffer != null) {
  937. webHeaders.RemoveInternal ("Transfer-Encoding");
  938. contentLength = bodyBufferLength;
  939. writeStream.SendChunked = false;
  940. }
  941. SendRequestHeaders ();
  942. haveRequest = true;
  943. if (bodyBuffer != null) {
  944. // The body has been written and buffered. The request "user"
  945. // won't write it again, so we must do it.
  946. writeStream.Write (bodyBuffer, 0, bodyBufferLength);
  947. bodyBuffer = null;
  948. writeStream.Close ();
  949. } else if (method == "PUT" || method == "POST" || method == "OPTIONS") {
  950. if (getResponseCalled && !writeStream.RequestWritten)
  951. writeStream.WriteRequest ();
  952. }
  953. if (asyncWrite != null) {
  954. asyncWrite.SetCompleted (false, stream);
  955. asyncWrite.DoCallback ();
  956. asyncWrite = null;
  957. }
  958. }
  959. internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
  960. {
  961. if (aborted)
  962. return;
  963. string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
  964. WebAsyncResult r = asyncRead;
  965. if (r == null)
  966. r = asyncWrite;
  967. if (r != null) {
  968. WebException wexc;
  969. if (e is WebException) {
  970. wexc = (WebException) e;
  971. } else {
  972. wexc = new WebException (msg, e, status, null);
  973. }
  974. r.SetCompleted (false, wexc);
  975. r.DoCallback ();
  976. asyncRead = null;
  977. asyncWrite = null;
  978. }
  979. }
  980. void CheckSendError (WebConnectionData data)
  981. {
  982. // Got here, but no one called GetResponse
  983. int status = data.StatusCode;
  984. if (status < 400 || status == 401 || status == 407)
  985. return;
  986. if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
  987. // The request has not been completely sent and we got here!
  988. // We should probably just close and cause an error in any case,
  989. saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
  990. webResponse.ReadAll ();
  991. }
  992. }
  993. void HandleNtlmAuth (WebAsyncResult r)
  994. {
  995. WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
  996. if (wce != null) {
  997. WebConnection cnc = wce.Connection;
  998. cnc.PriorityRequest = this;
  999. bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
  1000. ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
  1001. if (creds != null) {
  1002. cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
  1003. #if NET_1_1
  1004. cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
  1005. #endif
  1006. }
  1007. }
  1008. r.Reset ();
  1009. haveResponse = false;
  1010. webResponse.ReadAll ();
  1011. webResponse = null;
  1012. }
  1013. internal void SetResponseData (WebConnectionData data)
  1014. {
  1015. if (aborted) {
  1016. if (data.stream != null)
  1017. data.stream.Close ();
  1018. return;
  1019. }
  1020. WebException wexc = null;
  1021. try {
  1022. webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
  1023. haveResponse = true;
  1024. } catch (Exception e) {
  1025. wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
  1026. if (data.stream != null)
  1027. data.stream.Close ();
  1028. }
  1029. if (wexc == null && (method == "POST" || method == "PUT")) {
  1030. lock (locker) {
  1031. CheckSendError (data);
  1032. if (saved_exc != null)
  1033. wexc = (WebException) saved_exc;
  1034. }
  1035. }
  1036. WebAsyncResult r = asyncRead;
  1037. if (r != null) {
  1038. if (wexc != null) {
  1039. r.SetCompleted (false, wexc);
  1040. r.DoCallback ();
  1041. return;
  1042. }
  1043. bool redirected;
  1044. try {
  1045. redirected = CheckFinalStatus (r);
  1046. if (!redirected) {
  1047. if (is_ntlm_auth && authCompleted && webResponse != null
  1048. && (int)webResponse.StatusCode < 400) {
  1049. WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
  1050. if (wce != null) {
  1051. WebConnection cnc = wce.Connection;
  1052. cnc.NtlmAuthenticated = true;
  1053. }
  1054. }
  1055. // clear internal buffer so that it does not
  1056. // hold possible big buffer (bug #397627)
  1057. if (writeStream != null)
  1058. writeStream.KillBuffer ();
  1059. r.SetCompleted (false, webResponse);
  1060. r.DoCallback ();
  1061. } else {
  1062. if (webResponse != null) {
  1063. if (is_ntlm_auth) {
  1064. HandleNtlmAuth (r);
  1065. return;
  1066. }
  1067. webResponse.Close ();
  1068. }
  1069. haveResponse = false;
  1070. webResponse = null;
  1071. r.Reset ();
  1072. servicePoint = GetServicePoint ();
  1073. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  1074. }
  1075. } catch (WebException wexc2) {
  1076. r.SetCompleted (false, wexc2);
  1077. r.DoCallback ();
  1078. return;
  1079. } catch (Exception ex) {
  1080. wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
  1081. r.SetCompleted (false, wexc);
  1082. r.DoCallback ();
  1083. return;
  1084. }
  1085. }
  1086. }
  1087. bool CheckAuthorization (WebResponse response, HttpStatusCode code)
  1088. {
  1089. authCompleted = false;
  1090. if (code == HttpStatusCode.Unauthorized && credentials == null)
  1091. return false;
  1092. bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
  1093. if (isProxy && (proxy == null || proxy.Credentials == null))
  1094. return false;
  1095. string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
  1096. if (authHeader == null)
  1097. return false;
  1098. ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
  1099. Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
  1100. if (auth == null)
  1101. return false;
  1102. webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
  1103. authCompleted = auth.Complete;
  1104. is_ntlm_auth = (auth.Module.AuthenticationType == "NTLM");
  1105. return true;
  1106. }
  1107. // Returns true if redirected
  1108. bool CheckFinalStatus (WebAsyncResult result)
  1109. {
  1110. if (result.GotException)
  1111. throw result.Exception;
  1112. Exception throwMe = result.Exception;
  1113. bodyBuffer = null;
  1114. HttpWebResponse resp = result.Response;
  1115. WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
  1116. HttpStatusCode code = 0;
  1117. if (throwMe == null && webResponse != null) {
  1118. code = webResponse.StatusCode;
  1119. if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
  1120. (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
  1121. if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
  1122. // Keep the written body, so it can be rewritten in the retry
  1123. if (InternalAllowBuffering) {
  1124. bodyBuffer = writeStream.WriteBuffer;
  1125. bodyBufferLength = writeStream.WriteBufferLength;
  1126. return true;
  1127. } else if (method != "PUT" && method != "POST") {
  1128. return true;
  1129. }
  1130. writeStream.InternalClose ();
  1131. writeStream = null;
  1132. webResponse.Close ();
  1133. webResponse = null;
  1134. throw new WebException ("This request requires buffering " +
  1135. "of data for authentication or " +
  1136. "redirection to be sucessful.");
  1137. }
  1138. }
  1139. if ((int) code >= 400) {
  1140. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  1141. (int) code, webResponse.StatusDescription);
  1142. throwMe = new WebException (err, null, protoError, webResponse);
  1143. webResponse.ReadAll ();
  1144. } else if ((int) code == 304 && allowAutoRedirect) {
  1145. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  1146. (int) code, webResponse.StatusDescription);
  1147. throwMe = new WebException (err, null, protoError, webResponse);
  1148. } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
  1149. throwMe = new WebException ("Max. redirections exceeded.", null,
  1150. protoError, webResponse);
  1151. webResponse.ReadAll ();
  1152. }
  1153. }
  1154. if (throwMe == null) {
  1155. bool b = false;
  1156. int c = (int) code;
  1157. if (allowAutoRedirect && c >= 300) {
  1158. if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
  1159. bodyBuffer = writeStream.WriteBuffer;
  1160. bodyBufferLength = writeStream.WriteBufferLength;
  1161. }
  1162. b = Redirect (result, code);
  1163. }
  1164. if (resp != null && c >= 300 && c != 304)
  1165. resp.ReadAll ();
  1166. return b;
  1167. }
  1168. if (writeStream != null) {
  1169. writeStream.InternalClose ();
  1170. writeStream = null;
  1171. }
  1172. webResponse = null;
  1173. throw throwMe;
  1174. }
  1175. }
  1176. }