HttpWebRequest.cs 27 KB

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