HttpWebRequest.cs 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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 == "PUT" || method == "POST"));
  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. [MonoTODO]
  411. public bool UnsafeAuthenticatedConnectionSharing
  412. {
  413. get { throw new NotImplementedException (); }
  414. set { throw new NotImplementedException (); }
  415. }
  416. #endif
  417. internal bool GotRequestStream {
  418. get { return gotRequestStream; }
  419. }
  420. internal bool ExpectContinue {
  421. get { return expectContinue; }
  422. set { expectContinue = value; }
  423. }
  424. internal Uri AuthUri {
  425. get { return actualUri; }
  426. }
  427. internal bool ProxyQuery {
  428. get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
  429. }
  430. // Methods
  431. internal ServicePoint GetServicePoint ()
  432. {
  433. lock (locker) {
  434. if (hostChanged || servicePoint == null) {
  435. servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
  436. hostChanged = false;
  437. }
  438. }
  439. return servicePoint;
  440. }
  441. public void AddRange (int range)
  442. {
  443. AddRange ("bytes", range);
  444. }
  445. public void AddRange (int from, int to)
  446. {
  447. AddRange ("bytes", from, to);
  448. }
  449. public void AddRange (string rangeSpecifier, int range)
  450. {
  451. if (rangeSpecifier == null)
  452. throw new ArgumentNullException ("rangeSpecifier");
  453. string value = webHeaders ["Range"];
  454. if (value == null || value.Length == 0)
  455. value = rangeSpecifier + "=";
  456. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  457. value += ",";
  458. else
  459. throw new InvalidOperationException ("rangeSpecifier");
  460. webHeaders.RemoveAndAdd ("Range", value + range + "-");
  461. }
  462. public void AddRange (string rangeSpecifier, int from, int to)
  463. {
  464. if (rangeSpecifier == null)
  465. throw new ArgumentNullException ("rangeSpecifier");
  466. if (from < 0 || to < 0 || from > to)
  467. throw new ArgumentOutOfRangeException ();
  468. string value = webHeaders ["Range"];
  469. if (value == null || value.Length == 0)
  470. value = rangeSpecifier + "=";
  471. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  472. value += ",";
  473. else
  474. throw new InvalidOperationException ("rangeSpecifier");
  475. webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);
  476. }
  477. public override int GetHashCode ()
  478. {
  479. return base.GetHashCode ();
  480. }
  481. void CommonChecks (bool putpost)
  482. {
  483. if (method == null)
  484. throw new ProtocolViolationException ("Method is null.");
  485. if (putpost && ((!keepAlive || (contentLength == -1 && !sendChunked)) && !allowBuffering))
  486. throw new ProtocolViolationException ("Content-Length not set");
  487. string transferEncoding = TransferEncoding;
  488. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  489. throw new ProtocolViolationException ("SendChunked should be true.");
  490. }
  491. public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  492. {
  493. if (aborted)
  494. throw new WebException ("The request was previosly aborted.");
  495. bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD");
  496. if (method == null || !send)
  497. throw new ProtocolViolationException ("Cannot send data when method is: " + method);
  498. CommonChecks (send);
  499. lock (locker)
  500. {
  501. if (asyncWrite != null) {
  502. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  503. "method while a previous call is still in progress.");
  504. }
  505. asyncWrite = new WebAsyncResult (this, callback, state);
  506. initialMethod = method;
  507. if (haveRequest) {
  508. if (writeStream != null) {
  509. asyncWrite.SetCompleted (true, writeStream);
  510. asyncWrite.DoCallback ();
  511. return asyncWrite;
  512. }
  513. }
  514. gotRequestStream = true;
  515. WebAsyncResult result = asyncWrite;
  516. if (!requestSent) {
  517. requestSent = true;
  518. redirects = 0;
  519. servicePoint = GetServicePoint ();
  520. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  521. }
  522. return result;
  523. }
  524. }
  525. public override Stream EndGetRequestStream (IAsyncResult asyncResult)
  526. {
  527. if (asyncResult == null)
  528. throw new ArgumentNullException ("asyncResult");
  529. WebAsyncResult result = asyncResult as WebAsyncResult;
  530. if (result == null)
  531. throw new ArgumentException ("Invalid IAsyncResult");
  532. asyncWrite = result;
  533. result.WaitUntilComplete ();
  534. Exception e = result.Exception;
  535. if (e != null)
  536. throw e;
  537. return result.WriteStream;
  538. }
  539. public override Stream GetRequestStream()
  540. {
  541. IAsyncResult asyncResult = BeginGetRequestStream (null, null);
  542. asyncWrite = (WebAsyncResult) asyncResult;
  543. if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
  544. Abort ();
  545. throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
  546. }
  547. return EndGetRequestStream (asyncResult);
  548. }
  549. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  550. {
  551. bool send = (method == "PUT" || method == "POST");
  552. if (send) {
  553. if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
  554. throw new ProtocolViolationException ("Content-Length not set");
  555. }
  556. CommonChecks (send);
  557. Monitor.Enter (this);
  558. getResponseCalled = true;
  559. if (asyncRead != null && !haveResponse) {
  560. Monitor.Exit (this);
  561. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  562. "method while a previous call is still in progress.");
  563. }
  564. asyncRead = new WebAsyncResult (this, callback, state);
  565. initialMethod = method;
  566. if (haveResponse) {
  567. if (webResponse != null) {
  568. Exception saved = saved_exc;
  569. Monitor.Exit (this);
  570. if (saved == null) {
  571. asyncRead.SetCompleted (true, webResponse);
  572. } else {
  573. asyncRead.SetCompleted (true, saved);
  574. }
  575. asyncRead.DoCallback ();
  576. return asyncRead;
  577. }
  578. }
  579. if (!requestSent) {
  580. requestSent = true;
  581. redirects = 0;
  582. servicePoint = GetServicePoint ();
  583. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  584. }
  585. Monitor.Exit (this);
  586. return asyncRead;
  587. }
  588. public override WebResponse EndGetResponse (IAsyncResult asyncResult)
  589. {
  590. if (asyncResult == null)
  591. throw new ArgumentNullException ("asyncResult");
  592. WebAsyncResult result = asyncResult as WebAsyncResult;
  593. if (result == null)
  594. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  595. if (!result.WaitUntilComplete (timeout, false)) {
  596. Abort ();
  597. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  598. }
  599. if (result.GotException)
  600. throw result.Exception;
  601. return result.Response;
  602. }
  603. public override WebResponse GetResponse()
  604. {
  605. WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
  606. return EndGetResponse (result);
  607. }
  608. public override void Abort ()
  609. {
  610. haveResponse = true;
  611. aborted = true;
  612. if (asyncWrite != null) {
  613. WebAsyncResult r = asyncWrite;
  614. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  615. r.SetCompleted (false, wexc);
  616. r.DoCallback ();
  617. asyncWrite = null;
  618. }
  619. if (asyncRead != null) {
  620. WebAsyncResult r = asyncRead;
  621. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  622. r.SetCompleted (false, wexc);
  623. r.DoCallback ();
  624. asyncRead = null;
  625. }
  626. if (abortHandler != null) {
  627. try {
  628. abortHandler (this, EventArgs.Empty);
  629. } catch (Exception) {}
  630. abortHandler = null;
  631. }
  632. if (writeStream != null) {
  633. try {
  634. writeStream.Close ();
  635. writeStream = null;
  636. } catch {}
  637. }
  638. if (webResponse != null) {
  639. try {
  640. webResponse.Close ();
  641. webResponse = null;
  642. } catch {}
  643. }
  644. }
  645. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  646. StreamingContext streamingContext)
  647. {
  648. SerializationInfo info = serializationInfo;
  649. info.AddValue ("requestUri", requestUri, typeof (Uri));
  650. info.AddValue ("actualUri", actualUri, typeof (Uri));
  651. info.AddValue ("allowAutoRedirect", allowAutoRedirect);
  652. info.AddValue ("allowBuffering", allowBuffering);
  653. info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
  654. info.AddValue ("connectionGroup", connectionGroup);
  655. info.AddValue ("contentLength", contentLength);
  656. info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
  657. info.AddValue ("keepAlive", keepAlive);
  658. info.AddValue ("maxAutoRedirect", maxAutoRedirect);
  659. info.AddValue ("mediaType", mediaType);
  660. info.AddValue ("method", method);
  661. info.AddValue ("initialMethod", initialMethod);
  662. info.AddValue ("pipelined", pipelined);
  663. info.AddValue ("version", version, typeof (Version));
  664. info.AddValue ("proxy", proxy, typeof (IWebProxy));
  665. info.AddValue ("sendChunked", sendChunked);
  666. info.AddValue ("timeout", timeout);
  667. info.AddValue ("redirects", redirects);
  668. }
  669. void CheckRequestStarted ()
  670. {
  671. if (requestSent)
  672. throw new InvalidOperationException ("request started");
  673. }
  674. internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
  675. {
  676. if (continueDelegate != null)
  677. continueDelegate (statusCode, headers);
  678. }
  679. bool Redirect (WebAsyncResult result, HttpStatusCode code)
  680. {
  681. redirects++;
  682. Exception e = null;
  683. string uriString = null;
  684. switch (code) {
  685. case HttpStatusCode.Ambiguous: // 300
  686. e = new WebException ("Ambiguous redirect.");
  687. break;
  688. case HttpStatusCode.MovedPermanently: // 301
  689. case HttpStatusCode.Redirect: // 302
  690. case HttpStatusCode.TemporaryRedirect: // 307
  691. /* MS follows the redirect for POST too
  692. if (method != "GET" && method != "HEAD") // 10.3
  693. return false;
  694. */
  695. uriString = webResponse.Headers ["Location"];
  696. break;
  697. case HttpStatusCode.SeeOther: //303
  698. method = "GET";
  699. uriString = webResponse.Headers ["Location"];
  700. break;
  701. case HttpStatusCode.NotModified: // 304
  702. return false;
  703. case HttpStatusCode.UseProxy: // 305
  704. e = new NotImplementedException ("Proxy support not available.");
  705. break;
  706. case HttpStatusCode.Unused: // 306
  707. default:
  708. e = new ProtocolViolationException ("Invalid status code: " + (int) code);
  709. break;
  710. }
  711. if (e != null)
  712. throw e;
  713. if (uriString == null)
  714. throw new WebException ("No Location header found for " + (int) code,
  715. WebExceptionStatus.ProtocolError);
  716. Uri prev = actualUri;
  717. try {
  718. actualUri = new Uri (actualUri, uriString);
  719. } catch (Exception) {
  720. throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
  721. uriString, (int) code),
  722. WebExceptionStatus.ProtocolError);
  723. }
  724. hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host ||
  725. actualUri.Port != prev.Port);
  726. return true;
  727. }
  728. string GetHeaders ()
  729. {
  730. bool continue100 = false;
  731. if (contentLength != -1) {
  732. continue100 = true;
  733. webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
  734. webHeaders.RemoveInternal ("Transfer-Encoding");
  735. } else if (sendChunked) {
  736. continue100 = true;
  737. webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
  738. webHeaders.RemoveInternal ("Content-Length");
  739. }
  740. if (actualVersion == HttpVersion.Version11 && continue100 &&
  741. servicePoint.SendContinue) { // RFC2616 8.2.3
  742. webHeaders.RemoveAndAdd ("Expect" , "100-continue");
  743. expectContinue = true;
  744. } else {
  745. webHeaders.RemoveInternal ("Expect");
  746. expectContinue = false;
  747. }
  748. string connectionHeader = (ProxyQuery) ? "Proxy-Connection" : "Connection";
  749. webHeaders.RemoveInternal ((!ProxyQuery) ? "Proxy-Connection" : "Connection");
  750. bool spoint10 = (servicePoint.ProtocolVersion == null ||
  751. servicePoint.ProtocolVersion == HttpVersion.Version10);
  752. if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
  753. webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
  754. } else if (!keepAlive && version == HttpVersion.Version11) {
  755. webHeaders.RemoveAndAdd (connectionHeader, "close");
  756. }
  757. webHeaders.SetInternal ("Host", actualUri.Authority);
  758. if (cookieContainer != null) {
  759. string cookieHeader = cookieContainer.GetCookieHeader (requestUri);
  760. if (cookieHeader != "")
  761. webHeaders.SetInternal ("Cookie", cookieHeader);
  762. }
  763. if (!usedPreAuth && preAuthenticate)
  764. DoPreAuthenticate ();
  765. return webHeaders.ToString ();
  766. }
  767. void DoPreAuthenticate ()
  768. {
  769. webHeaders.RemoveInternal ("Proxy-Authorization");
  770. webHeaders.RemoveInternal ("Authorization");
  771. bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
  772. ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
  773. Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
  774. if (auth == null)
  775. return;
  776. string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
  777. webHeaders [authHeader] = auth.Message;
  778. usedPreAuth = true;
  779. }
  780. internal void SetWriteStreamError (WebExceptionStatus status)
  781. {
  782. if (aborted)
  783. return;
  784. WebAsyncResult r = asyncWrite;
  785. if (r == null)
  786. r = asyncRead;
  787. if (r != null) {
  788. r.SetCompleted (false, new WebException ("Error: " + status, status));
  789. r.DoCallback ();
  790. }
  791. }
  792. internal void SendRequestHeaders ()
  793. {
  794. StringBuilder req = new StringBuilder ();
  795. string query;
  796. if (!ProxyQuery) {
  797. query = actualUri.PathAndQuery;
  798. } else if (actualUri.IsDefaultPort) {
  799. query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
  800. actualUri.Host,
  801. actualUri.PathAndQuery);
  802. } else {
  803. query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
  804. actualUri.Host,
  805. actualUri.Port,
  806. actualUri.PathAndQuery);
  807. }
  808. if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
  809. actualVersion = servicePoint.ProtocolVersion;
  810. } else {
  811. actualVersion = version;
  812. }
  813. req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
  814. actualVersion.Major, actualVersion.Minor);
  815. req.Append (GetHeaders ());
  816. string reqstr = req.ToString ();
  817. byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
  818. writeStream.SetHeaders (bytes, 0, bytes.Length);
  819. }
  820. internal void SetWriteStream (WebConnectionStream stream)
  821. {
  822. if (aborted)
  823. return;
  824. writeStream = stream;
  825. if (bodyBuffer != null) {
  826. webHeaders.RemoveInternal ("Transfer-Encoding");
  827. contentLength = bodyBufferLength;
  828. writeStream.SendChunked = false;
  829. }
  830. SendRequestHeaders ();
  831. haveRequest = true;
  832. if (bodyBuffer != null) {
  833. // The body has been written and buffered. The request "user"
  834. // won't write it again, so we must do it.
  835. writeStream.Write (bodyBuffer, 0, bodyBufferLength);
  836. bodyBuffer = null;
  837. writeStream.Close ();
  838. } else if (method == "PUT" || method == "POST") {
  839. if (getResponseCalled && !writeStream.RequestWritten)
  840. writeStream.WriteRequest ();
  841. }
  842. if (asyncWrite != null) {
  843. asyncWrite.SetCompleted (false, stream);
  844. asyncWrite.DoCallback ();
  845. asyncWrite = null;
  846. }
  847. }
  848. internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
  849. {
  850. if (aborted)
  851. return;
  852. string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
  853. WebAsyncResult r = asyncRead;
  854. if (r == null)
  855. r = asyncWrite;
  856. if (r != null) {
  857. WebException wexc;
  858. if (e is WebException) {
  859. wexc = (WebException) e;
  860. } else {
  861. wexc = new WebException (msg, e, status, null);
  862. }
  863. r.SetCompleted (false, wexc);
  864. r.DoCallback ();
  865. asyncRead = null;
  866. asyncWrite = null;
  867. }
  868. }
  869. void CheckSendError (WebConnectionData data)
  870. {
  871. // Got here, but no one called GetResponse
  872. if (data.StatusCode < 400)
  873. return;
  874. if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
  875. // The request has not been completely sent and we got here!
  876. // We should probably just close and cause an error in any case,
  877. saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
  878. webResponse.ReadAll ();
  879. }
  880. }
  881. internal void SetResponseData (WebConnectionData data)
  882. {
  883. if (aborted) {
  884. if (data.stream != null)
  885. data.stream.Close ();
  886. return;
  887. }
  888. WebException wexc = null;
  889. try {
  890. webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
  891. haveResponse = true;
  892. } catch (Exception e) {
  893. wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
  894. if (data.stream != null)
  895. data.stream.Close ();
  896. }
  897. if (wexc == null && (method == "POST" || method == "PUT")) {
  898. lock (locker) {
  899. CheckSendError (data);
  900. if (saved_exc != null)
  901. wexc = (WebException) saved_exc;
  902. }
  903. }
  904. WebAsyncResult r = asyncRead;
  905. if (r != null) {
  906. if (wexc != null) {
  907. r.SetCompleted (false, wexc);
  908. r.DoCallback ();
  909. return;
  910. }
  911. bool redirected;
  912. try {
  913. redirected = CheckFinalStatus (r);
  914. if (!redirected) {
  915. r.SetCompleted (false, webResponse);
  916. r.DoCallback ();
  917. } else {
  918. if (webResponse != null) {
  919. webResponse.Close ();
  920. webResponse = null;
  921. }
  922. haveResponse = false;
  923. webResponse = null;
  924. r.Reset ();
  925. servicePoint = GetServicePoint ();
  926. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  927. }
  928. } catch (WebException wexc2) {
  929. r.SetCompleted (false, wexc2);
  930. r.DoCallback ();
  931. return;
  932. } catch (Exception ex) {
  933. wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
  934. r.SetCompleted (false, wexc);
  935. r.DoCallback ();
  936. return;
  937. }
  938. }
  939. }
  940. bool CheckAuthorization (WebResponse response, HttpStatusCode code)
  941. {
  942. authCompleted = false;
  943. if (code == HttpStatusCode.Unauthorized && credentials == null)
  944. return false;
  945. bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
  946. if (isProxy && (proxy == null || proxy.Credentials == null))
  947. return false;
  948. string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
  949. if (authHeader == null)
  950. return false;
  951. ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
  952. Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
  953. if (auth == null)
  954. return false;
  955. webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
  956. authCompleted = auth.Complete;
  957. return true;
  958. }
  959. // Returns true if redirected
  960. bool CheckFinalStatus (WebAsyncResult result)
  961. {
  962. if (result.GotException)
  963. throw result.Exception;
  964. Exception throwMe = result.Exception;
  965. bodyBuffer = null;
  966. HttpWebResponse resp = result.Response;
  967. WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
  968. HttpStatusCode code = 0;
  969. if (throwMe == null && webResponse != null) {
  970. code = webResponse.StatusCode;
  971. if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
  972. code == HttpStatusCode.ProxyAuthenticationRequired)) {
  973. if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
  974. // Keep the written body, so it can be rewritten in the retry
  975. if (InternalAllowBuffering) {
  976. bodyBuffer = writeStream.WriteBuffer;
  977. bodyBufferLength = writeStream.WriteBufferLength;
  978. webResponse.Close ();
  979. return true;
  980. } else if (method != "PUT" && method != "POST") {
  981. webResponse.Close ();
  982. return true;
  983. }
  984. writeStream.InternalClose ();
  985. writeStream = null;
  986. webResponse.Close ();
  987. webResponse = null;
  988. throw new WebException ("This request requires buffering " +
  989. "of data for authentication or " +
  990. "redirection to be sucessful.");
  991. }
  992. }
  993. if ((int) code >= 400) {
  994. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  995. (int) code, webResponse.StatusDescription);
  996. throwMe = new WebException (err, null, protoError, webResponse);
  997. webResponse.ReadAll ();
  998. } else if ((int) code == 304 && allowAutoRedirect) {
  999. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  1000. (int) code, webResponse.StatusDescription);
  1001. throwMe = new WebException (err, null, protoError, webResponse);
  1002. } else if ((int) code >= 300 && allowAutoRedirect && redirects > maxAutoRedirect) {
  1003. throwMe = new WebException ("Max. redirections exceeded.", null,
  1004. protoError, webResponse);
  1005. webResponse.ReadAll ();
  1006. }
  1007. }
  1008. if (throwMe == null) {
  1009. bool b = false;
  1010. int c = (int) code;
  1011. if (allowAutoRedirect && c >= 300)
  1012. b = Redirect (result, code);
  1013. if (resp != null && c >= 300 && c != 304)
  1014. resp.ReadAll ();
  1015. return b;
  1016. }
  1017. if (writeStream != null) {
  1018. writeStream.InternalClose ();
  1019. writeStream = null;
  1020. }
  1021. webResponse = null;
  1022. throw throwMe;
  1023. }
  1024. }
  1025. }