HttpWebRequest.cs 35 KB

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