HttpWebRequest.cs 32 KB

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