HttpWebRequest.cs 33 KB

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