HttpWebRequest.cs 33 KB

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