WebConnection.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. //
  2. // System.Net.WebConnection
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2003 Ximian, Inc (http://www.ximian.com)
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System.IO;
  30. using System.Collections;
  31. using System.Net.Sockets;
  32. using System.Reflection;
  33. using System.Security.Cryptography.X509Certificates;
  34. using System.Text;
  35. using System.Threading;
  36. namespace System.Net
  37. {
  38. enum ReadState
  39. {
  40. None,
  41. Status,
  42. Headers,
  43. Content
  44. }
  45. class WebConnection
  46. {
  47. ServicePoint sPoint;
  48. Stream nstream;
  49. Socket socket;
  50. object socketLock = new object ();
  51. WebExceptionStatus status;
  52. WaitCallback initConn;
  53. bool keepAlive;
  54. byte [] buffer;
  55. static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
  56. EventHandler abortHandler;
  57. AbortHelper abortHelper;
  58. ReadState readState;
  59. internal WebConnectionData Data;
  60. bool chunkedRead;
  61. ChunkStream chunkStream;
  62. Queue queue;
  63. bool reused;
  64. int position;
  65. bool busy;
  66. HttpWebRequest priority_request;
  67. NetworkCredential ntlm_credentials;
  68. bool ntlm_authenticated;
  69. #if NET_1_1
  70. bool unsafe_sharing;
  71. #endif
  72. bool ssl;
  73. bool certsAvailable;
  74. Exception connect_exception;
  75. static object classLock = new object ();
  76. static Type sslStream;
  77. static PropertyInfo piClient;
  78. static PropertyInfo piServer;
  79. static PropertyInfo piTrustFailure;
  80. public WebConnection (WebConnectionGroup group, ServicePoint sPoint)
  81. {
  82. this.sPoint = sPoint;
  83. buffer = new byte [4096];
  84. readState = ReadState.None;
  85. Data = new WebConnectionData ();
  86. initConn = new WaitCallback (InitConnection);
  87. queue = group.Queue;
  88. abortHelper = new AbortHelper ();
  89. abortHelper.Connection = this;
  90. abortHandler = new EventHandler (abortHelper.Abort);
  91. }
  92. class AbortHelper {
  93. public WebConnection Connection;
  94. public void Abort (object sender, EventArgs args)
  95. {
  96. WebConnection other = ((HttpWebRequest) sender).WebConnection;
  97. if (other == null)
  98. other = Connection;
  99. other.Abort (sender, args);
  100. }
  101. }
  102. bool CanReuse ()
  103. {
  104. // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
  105. // but if there's data pending to read (!) we won't reuse the socket.
  106. return (socket.Poll (0, SelectMode.SelectRead) == false);
  107. }
  108. void Connect (HttpWebRequest request)
  109. {
  110. lock (socketLock) {
  111. if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
  112. // Take the chunked stream to the expected state (State.None)
  113. if (CanReuse () && CompleteChunkedRead ()) {
  114. reused = true;
  115. return;
  116. }
  117. }
  118. reused = false;
  119. if (socket != null) {
  120. socket.Close();
  121. socket = null;
  122. }
  123. chunkStream = null;
  124. IPHostEntry hostEntry = sPoint.HostEntry;
  125. if (hostEntry == null) {
  126. status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
  127. WebExceptionStatus.NameResolutionFailure;
  128. return;
  129. }
  130. WebConnectionData data = Data;
  131. foreach (IPAddress address in hostEntry.AddressList) {
  132. socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  133. IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
  134. #if NET_1_1
  135. socket.SetSocketOption (SocketOptionLevel.Tcp, SocketOptionName.NoDelay, sPoint.UseNagleAlgorithm ? 0 : 1);
  136. #endif
  137. #if NET_2_0
  138. socket.NoDelay = !sPoint.UseNagleAlgorithm;
  139. if (!sPoint.CallEndPointDelegate (socket, remote)) {
  140. socket.Close ();
  141. socket = null;
  142. status = WebExceptionStatus.ConnectFailure;
  143. } else {
  144. #endif
  145. try {
  146. if (request.Aborted)
  147. return;
  148. socket.Connect (remote);
  149. status = WebExceptionStatus.Success;
  150. break;
  151. } catch (ThreadAbortException) {
  152. // program exiting...
  153. Socket s = socket;
  154. socket = null;
  155. if (s != null)
  156. s.Close ();
  157. return;
  158. } catch (ObjectDisposedException exc) {
  159. // socket closed from another thread
  160. return;
  161. } catch (Exception exc) {
  162. Socket s = socket;
  163. socket = null;
  164. if (s != null)
  165. s.Close ();
  166. if (!request.Aborted)
  167. status = WebExceptionStatus.ConnectFailure;
  168. connect_exception = exc;
  169. }
  170. #if NET_2_0
  171. }
  172. #endif
  173. }
  174. }
  175. }
  176. static void EnsureSSLStreamAvailable ()
  177. {
  178. lock (classLock) {
  179. if (sslStream != null)
  180. return;
  181. #if MONOTOUCH && SECURITY_DEP
  182. sslStream = typeof (Mono.Security.Protocol.Tls.HttpsClientStream);
  183. #else
  184. // HttpsClientStream is an internal glue class in Mono.Security.dll
  185. sslStream = Type.GetType ("Mono.Security.Protocol.Tls.HttpsClientStream, " +
  186. Consts.AssemblyMono_Security, false);
  187. if (sslStream == null) {
  188. string msg = "Missing Mono.Security.dll assembly. " +
  189. "Support for SSL/TLS is unavailable.";
  190. throw new NotSupportedException (msg);
  191. }
  192. #endif
  193. piClient = sslStream.GetProperty ("SelectedClientCertificate");
  194. piServer = sslStream.GetProperty ("ServerCertificate");
  195. piTrustFailure = sslStream.GetProperty ("TrustFailure");
  196. }
  197. }
  198. bool CreateTunnel (HttpWebRequest request, Stream stream, out byte [] buffer)
  199. {
  200. StringBuilder sb = new StringBuilder ();
  201. sb.Append ("CONNECT ");
  202. sb.Append (request.Address.Host);
  203. sb.Append (':');
  204. sb.Append (request.Address.Port);
  205. sb.Append (" HTTP/");
  206. if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
  207. sb.Append ("1.1");
  208. else
  209. sb.Append ("1.0");
  210. sb.Append ("\r\nHost: ");
  211. sb.Append (request.Address.Authority);
  212. string challenge = Data.Challenge;
  213. Data.Challenge = null;
  214. bool have_auth = (request.Headers ["Proxy-Authorization"] != null);
  215. if (have_auth) {
  216. sb.Append ("\r\nProxy-Authorization: ");
  217. sb.Append (request.Headers ["Proxy-Authorization"]);
  218. } else if (challenge != null && Data.StatusCode == 407) {
  219. have_auth = true;
  220. ICredentials creds = request.Proxy.Credentials;
  221. Authorization auth = AuthenticationManager.Authenticate (challenge, request, creds);
  222. if (auth != null) {
  223. sb.Append ("\r\nProxy-Authorization: ");
  224. sb.Append (auth.Message);
  225. }
  226. }
  227. sb.Append ("\r\n\r\n");
  228. Data.StatusCode = 0;
  229. byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
  230. stream.Write (connectBytes, 0, connectBytes.Length);
  231. int status;
  232. WebHeaderCollection result = ReadHeaders (request, stream, out buffer, out status);
  233. if (!have_auth && result != null && status == 407) { // Needs proxy auth
  234. Data.StatusCode = status;
  235. Data.Challenge = result ["Proxy-Authenticate"];
  236. return false;
  237. } else if (status != 200) {
  238. string msg = String.Format ("The remote server returned a {0} status code.", status);
  239. HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
  240. return false;
  241. }
  242. return (result != null);
  243. }
  244. WebHeaderCollection ReadHeaders (HttpWebRequest request, Stream stream, out byte [] retBuffer, out int status)
  245. {
  246. retBuffer = null;
  247. status = 200;
  248. byte [] buffer = new byte [1024];
  249. MemoryStream ms = new MemoryStream ();
  250. bool gotStatus = false;
  251. WebHeaderCollection headers = null;
  252. while (true) {
  253. int n = stream.Read (buffer, 0, 1024);
  254. if (n == 0) {
  255. HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
  256. return null;
  257. }
  258. ms.Write (buffer, 0, n);
  259. int start = 0;
  260. string str = null;
  261. headers = new WebHeaderCollection ();
  262. while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
  263. if (str == null) {
  264. if (ms.Length - start > 0) {
  265. retBuffer = new byte [ms.Length - start];
  266. Buffer.BlockCopy (ms.GetBuffer (), start, retBuffer, 0, retBuffer.Length);
  267. }
  268. return headers;
  269. }
  270. if (gotStatus) {
  271. headers.Add (str);
  272. continue;
  273. }
  274. int spaceidx = str.IndexOf (' ');
  275. if (spaceidx == -1) {
  276. HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
  277. return null;
  278. }
  279. status = (int) UInt32.Parse (str.Substring (spaceidx + 1, 3));
  280. gotStatus = true;
  281. }
  282. }
  283. }
  284. bool CreateStream (HttpWebRequest request)
  285. {
  286. try {
  287. NetworkStream serverStream = new NetworkStream (socket, false);
  288. if (request.Address.Scheme == Uri.UriSchemeHttps) {
  289. ssl = true;
  290. EnsureSSLStreamAvailable ();
  291. if (!reused || nstream == null || nstream.GetType () != sslStream) {
  292. byte [] buffer = null;
  293. if (sPoint.UseConnect) {
  294. bool ok = CreateTunnel (request, serverStream, out buffer);
  295. if (!ok)
  296. return false;
  297. }
  298. object[] args = new object [4] { serverStream,
  299. request.ClientCertificates,
  300. request, buffer};
  301. nstream = (Stream) Activator.CreateInstance (sslStream, args);
  302. certsAvailable = false;
  303. }
  304. // we also need to set ServicePoint.Certificate
  305. // and ServicePoint.ClientCertificate but this can
  306. // only be done later (after handshake - which is
  307. // done only after a read operation).
  308. } else {
  309. ssl = false;
  310. nstream = serverStream;
  311. }
  312. } catch (Exception) {
  313. if (!request.Aborted)
  314. status = WebExceptionStatus.ConnectFailure;
  315. return false;
  316. }
  317. return true;
  318. }
  319. void HandleError (WebExceptionStatus st, Exception e, string where)
  320. {
  321. status = st;
  322. lock (this) {
  323. if (st == WebExceptionStatus.RequestCanceled)
  324. Data = new WebConnectionData ();
  325. }
  326. if (e == null) { // At least we now where it comes from
  327. try {
  328. #if TARGET_JVM
  329. throw new Exception ();
  330. #else
  331. throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
  332. #endif
  333. } catch (Exception e2) {
  334. e = e2;
  335. }
  336. }
  337. HttpWebRequest req = null;
  338. if (Data != null && Data.request != null)
  339. req = Data.request;
  340. Close (true);
  341. if (req != null) {
  342. req.FinishedReading = true;
  343. req.SetResponseError (st, e, where);
  344. }
  345. }
  346. static void ReadDone (IAsyncResult result)
  347. {
  348. WebConnection cnc = (WebConnection) result.AsyncState;
  349. WebConnectionData data = cnc.Data;
  350. Stream ns = cnc.nstream;
  351. if (ns == null) {
  352. cnc.Close (true);
  353. return;
  354. }
  355. int nread = -1;
  356. try {
  357. nread = ns.EndRead (result);
  358. } catch (Exception e) {
  359. cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
  360. return;
  361. }
  362. if (nread == 0) {
  363. cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
  364. return;
  365. }
  366. if (nread < 0) {
  367. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
  368. return;
  369. }
  370. int pos = -1;
  371. nread += cnc.position;
  372. if (cnc.readState == ReadState.None) {
  373. Exception exc = null;
  374. try {
  375. pos = cnc.GetResponse (cnc.buffer, nread);
  376. } catch (Exception e) {
  377. exc = e;
  378. }
  379. if (exc != null) {
  380. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
  381. return;
  382. }
  383. }
  384. if (cnc.readState != ReadState.Content) {
  385. int est = nread * 2;
  386. int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
  387. byte [] newBuffer = new byte [max];
  388. Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
  389. cnc.buffer = newBuffer;
  390. cnc.position = nread;
  391. cnc.readState = ReadState.None;
  392. InitRead (cnc);
  393. return;
  394. }
  395. cnc.position = 0;
  396. WebConnectionStream stream = new WebConnectionStream (cnc);
  397. string contentType = data.Headers ["Transfer-Encoding"];
  398. cnc.chunkedRead = (contentType != null && contentType.ToLower ().IndexOf ("chunked") != -1);
  399. if (!cnc.chunkedRead) {
  400. stream.ReadBuffer = cnc.buffer;
  401. stream.ReadBufferOffset = pos;
  402. stream.ReadBufferSize = nread;
  403. stream.CheckResponseInBuffer ();
  404. } else if (cnc.chunkStream == null) {
  405. try {
  406. cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
  407. } catch (Exception e) {
  408. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
  409. return;
  410. }
  411. } else {
  412. cnc.chunkStream.ResetBuffer ();
  413. try {
  414. cnc.chunkStream.Write (cnc.buffer, pos, nread);
  415. } catch (Exception e) {
  416. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
  417. return;
  418. }
  419. }
  420. data.stream = stream;
  421. if (!ExpectContent (data.StatusCode) || data.request.Method == "HEAD")
  422. stream.ForceCompletion ();
  423. data.request.SetResponseData (data);
  424. }
  425. static bool ExpectContent (int statusCode)
  426. {
  427. return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
  428. }
  429. internal void GetCertificates ()
  430. {
  431. // here the SSL negotiation have been done
  432. X509Certificate client = (X509Certificate) piClient.GetValue (nstream, null);
  433. X509Certificate server = (X509Certificate) piServer.GetValue (nstream, null);
  434. sPoint.SetCertificates (client, server);
  435. certsAvailable = (server != null);
  436. }
  437. internal static void InitRead (object state)
  438. {
  439. WebConnection cnc = (WebConnection) state;
  440. Stream ns = cnc.nstream;
  441. try {
  442. int size = cnc.buffer.Length - cnc.position;
  443. ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
  444. } catch (Exception e) {
  445. cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
  446. }
  447. }
  448. int GetResponse (byte [] buffer, int max)
  449. {
  450. int pos = 0;
  451. string line = null;
  452. bool lineok = false;
  453. bool isContinue = false;
  454. bool emptyFirstLine = false;
  455. do {
  456. if (readState == ReadState.None) {
  457. lineok = ReadLine (buffer, ref pos, max, ref line);
  458. if (!lineok)
  459. return -1;
  460. if (line == null) {
  461. emptyFirstLine = true;
  462. continue;
  463. }
  464. emptyFirstLine = false;
  465. readState = ReadState.Status;
  466. string [] parts = line.Split (' ');
  467. if (parts.Length < 2)
  468. return -1;
  469. if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
  470. Data.Version = HttpVersion.Version11;
  471. sPoint.SetVersion (HttpVersion.Version11);
  472. } else {
  473. Data.Version = HttpVersion.Version10;
  474. sPoint.SetVersion (HttpVersion.Version10);
  475. }
  476. Data.StatusCode = (int) UInt32.Parse (parts [1]);
  477. if (parts.Length >= 3)
  478. Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
  479. else
  480. Data.StatusDescription = "";
  481. if (pos >= max)
  482. return pos;
  483. }
  484. emptyFirstLine = false;
  485. if (readState == ReadState.Status) {
  486. readState = ReadState.Headers;
  487. Data.Headers = new WebHeaderCollection ();
  488. ArrayList headers = new ArrayList ();
  489. bool finished = false;
  490. while (!finished) {
  491. if (ReadLine (buffer, ref pos, max, ref line) == false)
  492. break;
  493. if (line == null) {
  494. // Empty line: end of headers
  495. finished = true;
  496. continue;
  497. }
  498. if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
  499. int count = headers.Count - 1;
  500. if (count < 0)
  501. break;
  502. string prev = (string) headers [count] + line;
  503. headers [count] = prev;
  504. } else {
  505. headers.Add (line);
  506. }
  507. }
  508. if (!finished)
  509. return -1;
  510. foreach (string s in headers)
  511. Data.Headers.SetInternal (s);
  512. if (Data.StatusCode == (int) HttpStatusCode.Continue) {
  513. sPoint.SendContinue = true;
  514. if (pos >= max)
  515. return pos;
  516. if (Data.request.ExpectContinue) {
  517. Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers);
  518. // Prevent double calls when getting the
  519. // headers in several packets.
  520. Data.request.ExpectContinue = false;
  521. }
  522. readState = ReadState.None;
  523. isContinue = true;
  524. }
  525. else {
  526. readState = ReadState.Content;
  527. return pos;
  528. }
  529. }
  530. } while (emptyFirstLine || isContinue);
  531. return -1;
  532. }
  533. void InitConnection (object state)
  534. {
  535. HttpWebRequest request = (HttpWebRequest) state;
  536. request.WebConnection = this;
  537. if (request.Aborted)
  538. return;
  539. keepAlive = request.KeepAlive;
  540. Data = new WebConnectionData ();
  541. Data.request = request;
  542. retry:
  543. Connect (request);
  544. if (request.Aborted)
  545. return;
  546. if (status != WebExceptionStatus.Success) {
  547. if (!request.Aborted) {
  548. request.SetWriteStreamError (status, connect_exception);
  549. Close (true);
  550. }
  551. return;
  552. }
  553. if (!CreateStream (request)) {
  554. if (request.Aborted)
  555. return;
  556. WebExceptionStatus st = status;
  557. if (Data.Challenge != null)
  558. goto retry;
  559. Exception cnc_exc = connect_exception;
  560. connect_exception = null;
  561. request.SetWriteStreamError (st, cnc_exc);
  562. Close (true);
  563. return;
  564. }
  565. readState = ReadState.None;
  566. request.SetWriteStream (new WebConnectionStream (this, request));
  567. }
  568. internal EventHandler SendRequest (HttpWebRequest request)
  569. {
  570. if (request.Aborted)
  571. return null;
  572. lock (this) {
  573. if (!busy) {
  574. busy = true;
  575. status = WebExceptionStatus.Success;
  576. ThreadPool.QueueUserWorkItem (initConn, request);
  577. } else {
  578. lock (queue) {
  579. queue.Enqueue (request);
  580. }
  581. }
  582. }
  583. return abortHandler;
  584. }
  585. void SendNext ()
  586. {
  587. lock (queue) {
  588. if (queue.Count > 0) {
  589. SendRequest ((HttpWebRequest) queue.Dequeue ());
  590. }
  591. }
  592. }
  593. internal void NextRead ()
  594. {
  595. lock (this) {
  596. Data.request.FinishedReading = true;
  597. string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
  598. string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
  599. bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
  600. if (cncHeader != null) {
  601. cncHeader = cncHeader.ToLower ();
  602. keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive") != -1);
  603. }
  604. if ((socket != null && !socket.Connected) ||
  605. (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close") != -1))) {
  606. Close (false);
  607. }
  608. busy = false;
  609. if (priority_request != null) {
  610. SendRequest (priority_request);
  611. priority_request = null;
  612. } else {
  613. SendNext ();
  614. }
  615. }
  616. }
  617. static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
  618. {
  619. bool foundCR = false;
  620. StringBuilder text = new StringBuilder ();
  621. int c = 0;
  622. while (start < max) {
  623. c = (int) buffer [start++];
  624. if (c == '\n') { // newline
  625. if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
  626. text.Length--;
  627. foundCR = false;
  628. break;
  629. } else if (foundCR) {
  630. text.Length--;
  631. break;
  632. }
  633. if (c == '\r')
  634. foundCR = true;
  635. text.Append ((char) c);
  636. }
  637. if (c != '\n' && c != '\r')
  638. return false;
  639. if (text.Length == 0) {
  640. output = null;
  641. return (c == '\n' || c == '\r');
  642. }
  643. if (foundCR)
  644. text.Length--;
  645. output = text.ToString ();
  646. return true;
  647. }
  648. internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  649. {
  650. lock (this) {
  651. if (Data.request != request)
  652. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  653. if (nstream == null)
  654. return null;
  655. }
  656. IAsyncResult result = null;
  657. if (!chunkedRead || chunkStream.WantMore) {
  658. try {
  659. result = nstream.BeginRead (buffer, offset, size, cb, state);
  660. cb = null;
  661. } catch (Exception) {
  662. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
  663. throw;
  664. }
  665. }
  666. if (chunkedRead) {
  667. WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
  668. wr.InnerAsyncResult = result;
  669. if (result == null) {
  670. // Will be completed from the data in ChunkStream
  671. wr.SetCompleted (true, (Exception) null);
  672. wr.DoCallback ();
  673. }
  674. return wr;
  675. }
  676. return result;
  677. }
  678. internal int EndRead (HttpWebRequest request, IAsyncResult result)
  679. {
  680. lock (this) {
  681. if (Data.request != request)
  682. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  683. if (nstream == null)
  684. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  685. }
  686. int nbytes = 0;
  687. WebAsyncResult wr = null;
  688. IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
  689. if (chunkedRead && (nsAsync is WebAsyncResult)) {
  690. wr = (WebAsyncResult) nsAsync;
  691. IAsyncResult inner = wr.InnerAsyncResult;
  692. if (inner != null && !(inner is WebAsyncResult))
  693. nbytes = nstream.EndRead (inner);
  694. } else if (!(nsAsync is WebAsyncResult)) {
  695. nbytes = nstream.EndRead (nsAsync);
  696. wr = (WebAsyncResult) result;
  697. }
  698. if (chunkedRead) {
  699. bool done = (nbytes == 0);
  700. try {
  701. chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
  702. if (!done && nbytes == 0 && chunkStream.WantMore)
  703. nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
  704. } catch (Exception e) {
  705. if (e is WebException)
  706. throw e;
  707. throw new WebException ("Invalid chunked data.", e,
  708. WebExceptionStatus.ServerProtocolViolation, null);
  709. }
  710. if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
  711. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
  712. throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
  713. }
  714. }
  715. return (nbytes != 0) ? nbytes : -1;
  716. }
  717. // To be called on chunkedRead when we can read no data from the ChunkStream yet
  718. int EnsureRead (byte [] buffer, int offset, int size)
  719. {
  720. byte [] morebytes = null;
  721. int nbytes = 0;
  722. while (nbytes == 0 && chunkStream.WantMore) {
  723. int localsize = chunkStream.ChunkLeft;
  724. if (localsize <= 0) // not read chunk size yet
  725. localsize = 1024;
  726. else if (localsize > 16384)
  727. localsize = 16384;
  728. if (morebytes == null || morebytes.Length < localsize)
  729. morebytes = new byte [localsize];
  730. int nread = nstream.Read (morebytes, 0, localsize);
  731. if (nread <= 0)
  732. return 0; // Error
  733. chunkStream.Write (morebytes, 0, nread);
  734. nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
  735. }
  736. return nbytes;
  737. }
  738. bool CompleteChunkedRead()
  739. {
  740. if (!chunkedRead || chunkStream == null)
  741. return true;
  742. while (chunkStream.WantMore) {
  743. int nbytes = nstream.Read (buffer, 0, buffer.Length);
  744. if (nbytes <= 0)
  745. return false; // Socket was disconnected
  746. chunkStream.Write (buffer, 0, nbytes);
  747. }
  748. return true;
  749. }
  750. internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  751. {
  752. lock (this) {
  753. if (Data.request != request)
  754. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  755. if (nstream == null)
  756. return null;
  757. }
  758. IAsyncResult result = null;
  759. try {
  760. result = nstream.BeginWrite (buffer, offset, size, cb, state);
  761. } catch (Exception) {
  762. status = WebExceptionStatus.SendFailure;
  763. throw;
  764. }
  765. return result;
  766. }
  767. internal void EndWrite2 (HttpWebRequest request, IAsyncResult result)
  768. {
  769. if (request.FinishedReading)
  770. return;
  771. lock (this) {
  772. if (Data.request != request)
  773. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  774. if (nstream == null)
  775. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  776. }
  777. try {
  778. nstream.EndWrite (result);
  779. } catch (Exception exc) {
  780. status = WebExceptionStatus.SendFailure;
  781. if (exc.InnerException != null)
  782. throw exc.InnerException;
  783. throw;
  784. }
  785. }
  786. internal bool EndWrite (HttpWebRequest request, IAsyncResult result)
  787. {
  788. if (request.FinishedReading)
  789. return true;
  790. lock (this) {
  791. if (Data.request != request)
  792. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  793. if (nstream == null)
  794. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  795. }
  796. try {
  797. nstream.EndWrite (result);
  798. return true;
  799. } catch {
  800. status = WebExceptionStatus.SendFailure;
  801. return false;
  802. }
  803. }
  804. internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
  805. {
  806. lock (this) {
  807. if (Data.request != request)
  808. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  809. if (nstream == null)
  810. return 0;
  811. }
  812. int result = 0;
  813. try {
  814. bool done = false;
  815. if (!chunkedRead) {
  816. result = nstream.Read (buffer, offset, size);
  817. done = (result == 0);
  818. }
  819. if (chunkedRead) {
  820. try {
  821. chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
  822. if (!done && result == 0 && chunkStream.WantMore)
  823. result = EnsureRead (buffer, offset, size);
  824. } catch (Exception e) {
  825. HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
  826. throw;
  827. }
  828. if ((done || result == 0) && chunkStream.WantMore) {
  829. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
  830. throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
  831. }
  832. }
  833. } catch (Exception e) {
  834. HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
  835. }
  836. return result;
  837. }
  838. internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
  839. {
  840. err_msg = null;
  841. lock (this) {
  842. if (Data.request != request)
  843. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  844. if (nstream == null)
  845. return false;
  846. }
  847. try {
  848. nstream.Write (buffer, offset, size);
  849. // here SSL handshake should have been done
  850. if (ssl && !certsAvailable)
  851. GetCertificates ();
  852. } catch (Exception e) {
  853. err_msg = e.Message;
  854. WebExceptionStatus wes = WebExceptionStatus.SendFailure;
  855. string msg = "Write: " + err_msg;
  856. if (e is WebException) {
  857. HandleError (wes, e, msg);
  858. return false;
  859. }
  860. // if SSL is in use then check for TrustFailure
  861. if (ssl && (bool) piTrustFailure.GetValue (nstream, null)) {
  862. wes = WebExceptionStatus.TrustFailure;
  863. msg = "Trust failure";
  864. }
  865. HandleError (wes, e, msg);
  866. return false;
  867. }
  868. return true;
  869. }
  870. internal void Close (bool sendNext)
  871. {
  872. lock (this) {
  873. if (nstream != null) {
  874. try {
  875. nstream.Close ();
  876. } catch {}
  877. nstream = null;
  878. }
  879. if (socket != null) {
  880. try {
  881. socket.Close ();
  882. } catch {}
  883. socket = null;
  884. }
  885. busy = false;
  886. Data = new WebConnectionData ();
  887. if (sendNext)
  888. SendNext ();
  889. }
  890. }
  891. void Abort (object sender, EventArgs args)
  892. {
  893. lock (this) {
  894. lock (queue) {
  895. HttpWebRequest req = (HttpWebRequest) sender;
  896. if (Data.request == req) {
  897. if (!req.FinishedReading) {
  898. status = WebExceptionStatus.RequestCanceled;
  899. Close (false);
  900. if (queue.Count > 0) {
  901. Data.request = (HttpWebRequest) queue.Dequeue ();
  902. SendRequest (Data.request);
  903. }
  904. }
  905. return;
  906. }
  907. req.FinishedReading = true;
  908. req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
  909. if (queue.Count > 0 && queue.Peek () == sender) {
  910. queue.Dequeue ();
  911. } else if (queue.Count > 0) {
  912. object [] old = queue.ToArray ();
  913. queue.Clear ();
  914. for (int i = old.Length - 1; i >= 0; i--) {
  915. if (old [i] != sender)
  916. queue.Enqueue (old [i]);
  917. }
  918. }
  919. }
  920. }
  921. }
  922. internal void ResetNtlm ()
  923. {
  924. ntlm_authenticated = false;
  925. ntlm_credentials = null;
  926. unsafe_sharing = false;
  927. }
  928. internal bool Busy {
  929. get { lock (this) return busy; }
  930. }
  931. internal bool Connected {
  932. get {
  933. lock (this) {
  934. return (socket != null && socket.Connected);
  935. }
  936. }
  937. }
  938. // -Used for NTLM authentication
  939. internal HttpWebRequest PriorityRequest {
  940. set { priority_request = value; }
  941. }
  942. internal bool NtlmAuthenticated {
  943. get { return ntlm_authenticated; }
  944. set { ntlm_authenticated = value; }
  945. }
  946. internal NetworkCredential NtlmCredential {
  947. get { return ntlm_credentials; }
  948. set { ntlm_credentials = value; }
  949. }
  950. #if NET_1_1
  951. internal bool UnsafeAuthenticatedConnectionSharing {
  952. get { return unsafe_sharing; }
  953. set { unsafe_sharing = value; }
  954. }
  955. #endif
  956. // -
  957. }
  958. }