WebConnection.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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. WebExceptionStatus status;
  51. WebConnectionGroup group;
  52. bool busy;
  53. WaitOrTimerCallback initConn;
  54. bool keepAlive;
  55. byte [] buffer;
  56. static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
  57. EventHandler abortHandler;
  58. ReadState readState;
  59. internal WebConnectionData Data;
  60. WebConnectionStream prevStream;
  61. bool chunkedRead;
  62. ChunkStream chunkStream;
  63. AutoResetEvent goAhead;
  64. Queue queue;
  65. bool reused;
  66. int position;
  67. bool ssl;
  68. bool certsAvailable;
  69. static object classLock = new object ();
  70. static Type sslStream;
  71. static PropertyInfo piClient;
  72. static PropertyInfo piServer;
  73. public WebConnection (WebConnectionGroup group, ServicePoint sPoint)
  74. {
  75. this.group = group;
  76. this.sPoint = sPoint;
  77. buffer = new byte [4096];
  78. readState = ReadState.None;
  79. Data = new WebConnectionData ();
  80. initConn = new WaitOrTimerCallback (InitConnection);
  81. abortHandler = new EventHandler (Abort);
  82. goAhead = new AutoResetEvent (true);
  83. queue = group.Queue;
  84. }
  85. bool CanReuse ()
  86. {
  87. // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
  88. // but if there's data pending to read (!) we won't reuse the socket.
  89. return (socket.Poll (0, SelectMode.SelectRead) == false);
  90. }
  91. void Connect ()
  92. {
  93. lock (this) {
  94. if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
  95. // Take the chunked stream to the expected state (State.None)
  96. if (CanReuse () && CompleteChunkedRead ()) {
  97. reused = true;
  98. return;
  99. }
  100. }
  101. reused = false;
  102. if (socket != null) {
  103. socket.Close();
  104. socket = null;
  105. }
  106. chunkStream = null;
  107. IPHostEntry hostEntry = sPoint.HostEntry;
  108. if (hostEntry == null) {
  109. status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
  110. WebExceptionStatus.NameResolutionFailure;
  111. return;
  112. }
  113. foreach (IPAddress address in hostEntry.AddressList) {
  114. socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  115. try {
  116. socket.Connect (new IPEndPoint(address, sPoint.Address.Port));
  117. status = WebExceptionStatus.Success;
  118. break;
  119. } catch (SocketException) {
  120. socket.Close();
  121. socket = null;
  122. status = WebExceptionStatus.ConnectFailure;
  123. }
  124. }
  125. }
  126. }
  127. static void EnsureSSLStreamAvailable ()
  128. {
  129. lock (classLock) {
  130. if (sslStream != null)
  131. return;
  132. // HttpsClientStream is an internal glue class in Mono.Security.dll
  133. sslStream = Type.GetType ("Mono.Security.Protocol.Tls.HttpsClientStream, " +
  134. Consts.AssemblyMono_Security, false);
  135. if (sslStream == null) {
  136. string msg = "Missing Mono.Security.dll assembly. " +
  137. "Support for SSL/TLS is unavailable.";
  138. throw new NotSupportedException (msg);
  139. }
  140. piClient = sslStream.GetProperty ("SelectedClientCertificate");
  141. piServer = sslStream.GetProperty ("ServerCertificate");
  142. }
  143. }
  144. bool CreateTunnel (HttpWebRequest request, Stream stream, out byte [] buffer)
  145. {
  146. StringBuilder sb = new StringBuilder ();
  147. sb.Append ("CONNECT ");
  148. sb.Append (request.Address.Host);
  149. sb.Append (':');
  150. sb.Append (request.Address.Port);
  151. sb.Append (" HTTP/");
  152. if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
  153. sb.Append ("1.1");
  154. else
  155. sb.Append ("1.0");
  156. sb.Append ("\r\nHost: ");
  157. sb.Append (request.Address.Authority);
  158. if (request.Headers ["Proxy-Authorization"] != null) {
  159. sb.Append ("\r\nProxy-Authorization: ");
  160. sb.Append (request.Headers ["Proxy-Authorization"]);
  161. }
  162. sb.Append ("\r\n\r\n");
  163. byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
  164. stream.Write (connectBytes, 0, connectBytes.Length);
  165. return ReadHeaders (request, stream, out buffer);
  166. }
  167. bool ReadHeaders (HttpWebRequest request, Stream stream, out byte [] retBuffer)
  168. {
  169. retBuffer = null;
  170. byte [] buffer = new byte [256];
  171. MemoryStream ms = new MemoryStream ();
  172. bool gotStatus = false;
  173. while (true) {
  174. int n = stream.Read (buffer, 0, 256);
  175. if (n == 0) {
  176. HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeders");
  177. return false;
  178. }
  179. ms.Write (buffer, 0, n);
  180. int start = 0;
  181. string str = null;
  182. while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
  183. if (str == null) {
  184. if (ms.Length - start > 0) {
  185. retBuffer = new byte [ms.Length - start];
  186. Buffer.BlockCopy (ms.GetBuffer (), start, retBuffer, 0, retBuffer.Length);
  187. }
  188. return true;
  189. }
  190. if (gotStatus)
  191. continue;
  192. int spaceidx = str.IndexOf (' ');
  193. if (spaceidx == -1)
  194. throw new Exception ();
  195. int resultCode = Int32.Parse (str.Substring (spaceidx + 1, 3));
  196. if (resultCode != 200)
  197. throw new Exception ();
  198. gotStatus = true;
  199. }
  200. }
  201. }
  202. bool CreateStream (HttpWebRequest request)
  203. {
  204. try {
  205. NetworkStream serverStream = new NetworkStream (socket, false);
  206. if (request.Address.Scheme == Uri.UriSchemeHttps) {
  207. ssl = true;
  208. EnsureSSLStreamAvailable ();
  209. if (!reused || nstream == null || nstream.GetType () != sslStream) {
  210. byte [] buffer = null;
  211. if (sPoint.UseConnect) {
  212. bool ok = CreateTunnel (request, serverStream, out buffer);
  213. if (!ok)
  214. return false;
  215. }
  216. object[] args = new object [4] { serverStream,
  217. request.ClientCertificates,
  218. request, buffer};
  219. nstream = (Stream) Activator.CreateInstance (sslStream, args);
  220. }
  221. // we also need to set ServicePoint.Certificate
  222. // and ServicePoint.ClientCertificate but this can
  223. // only be done later (after handshake - which is
  224. // done only after a read operation).
  225. } else {
  226. ssl = false;
  227. nstream = serverStream;
  228. }
  229. } catch (Exception) {
  230. status = WebExceptionStatus.ConnectFailure;
  231. return false;
  232. }
  233. return true;
  234. }
  235. void HandleError (WebExceptionStatus st, Exception e, string where)
  236. {
  237. status = st;
  238. lock (this) {
  239. if (st == WebExceptionStatus.RequestCanceled)
  240. Data = new WebConnectionData ();
  241. }
  242. if (e == null) { // At least we now where it comes from
  243. try {
  244. throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
  245. } catch (Exception e2) {
  246. e = e2;
  247. }
  248. }
  249. if (Data != null && Data.request != null)
  250. Data.request.SetResponseError (st, e, where);
  251. Close (true);
  252. }
  253. static void ReadDone (IAsyncResult result)
  254. {
  255. WebConnection cnc = (WebConnection) result.AsyncState;
  256. WebConnectionData data = cnc.Data;
  257. Stream ns = cnc.nstream;
  258. if (ns == null) {
  259. cnc.Close (true);
  260. return;
  261. }
  262. int nread = -1;
  263. try {
  264. nread = ns.EndRead (result);
  265. } catch (Exception e) {
  266. cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
  267. return;
  268. }
  269. if (nread == 0) {
  270. cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
  271. return;
  272. }
  273. if (nread < 0) {
  274. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
  275. return;
  276. }
  277. int pos = -1;
  278. nread += cnc.position;
  279. if (cnc.readState == ReadState.None) {
  280. Exception exc = null;
  281. try {
  282. pos = cnc.GetResponse (cnc.buffer, nread);
  283. } catch (Exception e) {
  284. exc = e;
  285. }
  286. if (exc != null) {
  287. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
  288. return;
  289. }
  290. }
  291. if (cnc.readState != ReadState.Content) {
  292. int est = nread * 2;
  293. int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
  294. byte [] newBuffer = new byte [max];
  295. Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
  296. cnc.buffer = newBuffer;
  297. cnc.position = nread;
  298. cnc.readState = ReadState.None;
  299. InitRead (cnc);
  300. return;
  301. }
  302. cnc.position = 0;
  303. WebConnectionStream stream = new WebConnectionStream (cnc);
  304. string contentType = data.Headers ["Transfer-Encoding"];
  305. cnc.chunkedRead = (contentType != null && contentType.ToLower ().IndexOf ("chunked") != -1);
  306. if (!cnc.chunkedRead) {
  307. stream.ReadBuffer = cnc.buffer;
  308. stream.ReadBufferOffset = pos;
  309. stream.ReadBufferSize = nread;
  310. } else if (cnc.chunkStream == null) {
  311. try {
  312. cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
  313. } catch (Exception e) {
  314. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
  315. return;
  316. }
  317. } else {
  318. cnc.chunkStream.ResetBuffer ();
  319. try {
  320. cnc.chunkStream.Write (cnc.buffer, pos, nread);
  321. } catch (Exception e) {
  322. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
  323. return;
  324. }
  325. }
  326. data.stream = stream;
  327. if (!ExpectContent (data.StatusCode))
  328. stream.ForceCompletion ();
  329. lock (cnc) {
  330. lock (cnc.queue) {
  331. if (cnc.queue.Count > 0) {
  332. stream.ReadAll ();
  333. } else {
  334. cnc.prevStream = stream;
  335. stream.CheckComplete ();
  336. }
  337. }
  338. }
  339. data.request.SetResponseData (data);
  340. }
  341. static bool ExpectContent (int statusCode)
  342. {
  343. return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
  344. }
  345. internal void GetCertificates ()
  346. {
  347. // here the SSL negotiation have been done
  348. X509Certificate client = (X509Certificate) piClient.GetValue (nstream, null);
  349. X509Certificate server = (X509Certificate) piServer.GetValue (nstream, null);
  350. sPoint.SetCertificates (client, server);
  351. certsAvailable = (server != null);
  352. }
  353. static void InitRead (object state)
  354. {
  355. WebConnection cnc = (WebConnection) state;
  356. Stream ns = cnc.nstream;
  357. try {
  358. int size = cnc.buffer.Length - cnc.position;
  359. ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
  360. } catch (Exception e) {
  361. cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
  362. }
  363. }
  364. int GetResponse (byte [] buffer, int max)
  365. {
  366. int pos = 0;
  367. string line = null;
  368. bool lineok = false;
  369. bool isContinue = false;
  370. bool emptyFirstLine = false;
  371. do {
  372. if (readState == ReadState.None) {
  373. lineok = ReadLine (buffer, ref pos, max, ref line);
  374. if (!lineok)
  375. return -1;
  376. if (line == null) {
  377. emptyFirstLine = true;
  378. continue;
  379. }
  380. emptyFirstLine = false;
  381. readState = ReadState.Status;
  382. string [] parts = line.Split (' ');
  383. if (parts.Length < 2)
  384. return -1;
  385. if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
  386. Data.Version = HttpVersion.Version11;
  387. sPoint.SetVersion (HttpVersion.Version11);
  388. } else {
  389. Data.Version = HttpVersion.Version10;
  390. sPoint.SetVersion (HttpVersion.Version10);
  391. }
  392. Data.StatusCode = (int) UInt32.Parse (parts [1]);
  393. if (parts.Length >= 3)
  394. Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
  395. else
  396. Data.StatusDescription = "";
  397. if (pos >= max)
  398. return pos;
  399. }
  400. emptyFirstLine = false;
  401. if (readState == ReadState.Status) {
  402. readState = ReadState.Headers;
  403. Data.Headers = new WebHeaderCollection ();
  404. ArrayList headers = new ArrayList ();
  405. bool finished = false;
  406. while (!finished) {
  407. if (ReadLine (buffer, ref pos, max, ref line) == false)
  408. break;
  409. if (line == null) {
  410. // Empty line: end of headers
  411. finished = true;
  412. continue;
  413. }
  414. if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
  415. int count = headers.Count - 1;
  416. if (count < 0)
  417. break;
  418. string prev = (string) headers [count] + line;
  419. headers [count] = prev;
  420. } else {
  421. headers.Add (line);
  422. }
  423. }
  424. if (!finished)
  425. return -1;
  426. foreach (string s in headers)
  427. Data.Headers.SetInternal (s);
  428. if (Data.StatusCode == (int) HttpStatusCode.Continue) {
  429. sPoint.SendContinue = true;
  430. if (pos >= max)
  431. return pos;
  432. if (Data.request.ExpectContinue) {
  433. Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers);
  434. // Prevent double calls when getting the
  435. // headers in several packets.
  436. Data.request.ExpectContinue = false;
  437. }
  438. readState = ReadState.None;
  439. isContinue = true;
  440. }
  441. else {
  442. readState = ReadState.Content;
  443. return pos;
  444. }
  445. }
  446. } while (emptyFirstLine || isContinue);
  447. return -1;
  448. }
  449. void InitConnection (object state, bool notUsed)
  450. {
  451. HttpWebRequest request = (HttpWebRequest) state;
  452. if (status == WebExceptionStatus.RequestCanceled) {
  453. busy = false;
  454. Data = new WebConnectionData ();
  455. goAhead.Set ();
  456. SendNext ();
  457. return;
  458. }
  459. keepAlive = request.KeepAlive;
  460. Data = new WebConnectionData ();
  461. Data.request = request;
  462. Connect ();
  463. if (status != WebExceptionStatus.Success) {
  464. request.SetWriteStreamError (status);
  465. Close (true);
  466. return;
  467. }
  468. if (!CreateStream (request)) {
  469. request.SetWriteStreamError (status);
  470. Close (true);
  471. return;
  472. }
  473. readState = ReadState.None;
  474. request.SetWriteStream (new WebConnectionStream (this, request));
  475. InitRead (this);
  476. }
  477. internal EventHandler SendRequest (HttpWebRequest request)
  478. {
  479. lock (this) {
  480. if (prevStream != null && socket != null && socket.Connected) {
  481. prevStream.ReadAll ();
  482. prevStream = null;
  483. }
  484. if (!busy) {
  485. busy = true;
  486. ThreadPool.RegisterWaitForSingleObject (goAhead, initConn,
  487. request, -1, true);
  488. } else {
  489. lock (queue) {
  490. queue.Enqueue (request);
  491. }
  492. }
  493. }
  494. return abortHandler;
  495. }
  496. void SendNext ()
  497. {
  498. lock (queue) {
  499. if (queue.Count > 0) {
  500. prevStream = null;
  501. SendRequest ((HttpWebRequest) queue.Dequeue ());
  502. }
  503. }
  504. }
  505. internal void NextRead ()
  506. {
  507. lock (this) {
  508. busy = false;
  509. string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
  510. string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
  511. bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
  512. if (cncHeader != null) {
  513. cncHeader = cncHeader.ToLower ();
  514. keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive") != -1);
  515. }
  516. if ((socket != null && !socket.Connected) ||
  517. (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close") != -1))) {
  518. Close (false);
  519. }
  520. goAhead.Set ();
  521. lock (queue) {
  522. if (queue.Count > 0) {
  523. prevStream = null;
  524. SendRequest ((HttpWebRequest) queue.Dequeue ());
  525. }
  526. }
  527. }
  528. }
  529. static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
  530. {
  531. bool foundCR = false;
  532. StringBuilder text = new StringBuilder ();
  533. int c = 0;
  534. while (start < max) {
  535. c = (int) buffer [start++];
  536. if (c == '\n') { // newline
  537. if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
  538. text.Length--;
  539. foundCR = false;
  540. break;
  541. } else if (foundCR) {
  542. text.Length--;
  543. break;
  544. }
  545. if (c == '\r')
  546. foundCR = true;
  547. text.Append ((char) c);
  548. }
  549. if (c != '\n' && c != '\r')
  550. return false;
  551. if (text.Length == 0) {
  552. output = null;
  553. return (c == '\n' || c == '\r');
  554. }
  555. if (foundCR)
  556. text.Length--;
  557. output = text.ToString ();
  558. return true;
  559. }
  560. internal IAsyncResult BeginRead (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  561. {
  562. if (nstream == null)
  563. return null;
  564. IAsyncResult result = null;
  565. if (!chunkedRead || chunkStream.WantMore) {
  566. try {
  567. result = nstream.BeginRead (buffer, offset, size, cb, state);
  568. } catch (Exception) {
  569. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
  570. throw;
  571. }
  572. }
  573. if (chunkedRead) {
  574. WebAsyncResult wr = new WebAsyncResult (null, null, buffer, offset, size);
  575. wr.InnerAsyncResult = result;
  576. return wr;
  577. }
  578. return result;
  579. }
  580. internal int EndRead (IAsyncResult result)
  581. {
  582. if (nstream == null)
  583. return 0;
  584. if (chunkedRead) {
  585. WebAsyncResult wr = (WebAsyncResult) result;
  586. int nbytes = 0;
  587. if (wr.InnerAsyncResult != null)
  588. nbytes = nstream.EndRead (wr.InnerAsyncResult);
  589. bool done = (nbytes == 0);
  590. try {
  591. chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
  592. if (!done && nbytes == 0 && chunkStream.WantMore)
  593. nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
  594. } catch (Exception e) {
  595. if (e is WebException)
  596. throw e;
  597. throw new WebException ("Invalid chunked data.", e,
  598. WebExceptionStatus.ServerProtocolViolation, null);
  599. }
  600. if ((done || nbytes == 0) && chunkStream.WantMore) {
  601. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
  602. throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
  603. }
  604. return nbytes;
  605. }
  606. return nstream.EndRead (result);
  607. }
  608. // To be called on chunkedRead when we can read no data from the ChunkStream yet
  609. int EnsureRead (byte [] buffer, int offset, int size)
  610. {
  611. byte [] morebytes = null;
  612. int nbytes = 0;
  613. while (nbytes == 0 && chunkStream.WantMore) {
  614. int localsize = chunkStream.ChunkLeft;
  615. if (localsize <= 0) // not read chunk size yet
  616. localsize = 1024;
  617. else if (localsize > 16384)
  618. localsize = 16384;
  619. if (morebytes == null || morebytes.Length < localsize)
  620. morebytes = new byte [localsize];
  621. int nread = nstream.Read (morebytes, 0, localsize);
  622. if (nread <= 0)
  623. return 0; // Error
  624. chunkStream.Write (morebytes, 0, nread);
  625. nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
  626. }
  627. return nbytes;
  628. }
  629. bool CompleteChunkedRead()
  630. {
  631. if (!chunkedRead || chunkStream == null)
  632. return true;
  633. while (chunkStream.WantMore) {
  634. int nbytes = nstream.Read (buffer, 0, buffer.Length);
  635. if (nbytes <= 0)
  636. return false; // Socket was disconnected
  637. chunkStream.Write (buffer, 0, nbytes);
  638. }
  639. return true;
  640. }
  641. internal IAsyncResult BeginWrite (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  642. {
  643. IAsyncResult result = null;
  644. if (nstream == null)
  645. return null;
  646. try {
  647. result = nstream.BeginWrite (buffer, offset, size, cb, state);
  648. } catch (Exception) {
  649. status = WebExceptionStatus.SendFailure;
  650. throw;
  651. }
  652. return result;
  653. }
  654. internal void EndWrite (IAsyncResult result)
  655. {
  656. if (nstream != null)
  657. nstream.EndWrite (result);
  658. }
  659. internal int Read (byte [] buffer, int offset, int size)
  660. {
  661. if (nstream == null)
  662. return 0;
  663. int result = 0;
  664. try {
  665. bool done = false;
  666. if (!chunkedRead) {
  667. result = nstream.Read (buffer, offset, size);
  668. done = (result == 0);
  669. }
  670. if (chunkedRead) {
  671. try {
  672. chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
  673. if (!done && result == 0 && chunkStream.WantMore)
  674. result = EnsureRead (buffer, offset, size);
  675. } catch (Exception e) {
  676. HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
  677. throw;
  678. }
  679. if ((done || result == 0) && chunkStream.WantMore) {
  680. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
  681. throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
  682. }
  683. }
  684. } catch (Exception e) {
  685. HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
  686. }
  687. return result;
  688. }
  689. internal void Write (byte [] buffer, int offset, int size)
  690. {
  691. if (nstream == null)
  692. return;
  693. try {
  694. nstream.Write (buffer, offset, size);
  695. // here SSL handshake should have been done
  696. if (ssl && !certsAvailable) {
  697. GetCertificates ();
  698. }
  699. } catch (Exception) {
  700. }
  701. }
  702. internal bool TryReconnect ()
  703. {
  704. lock (this) {
  705. if (!reused) {
  706. HandleError (WebExceptionStatus.SendFailure, null, "TryReconnect");
  707. return false;
  708. }
  709. Close (false);
  710. reused = false;
  711. Connect ();
  712. if (status != WebExceptionStatus.Success) {
  713. HandleError (WebExceptionStatus.SendFailure, null, "TryReconnect2");
  714. return false;
  715. }
  716. if (!CreateStream (Data.request)) {
  717. HandleError (WebExceptionStatus.SendFailure, null, "TryReconnect3");
  718. return false;
  719. }
  720. }
  721. return true;
  722. }
  723. void Close (bool sendNext)
  724. {
  725. lock (this) {
  726. busy = false;
  727. if (nstream != null) {
  728. try {
  729. nstream.Close ();
  730. } catch {}
  731. nstream = null;
  732. }
  733. if (socket != null) {
  734. try {
  735. socket.Close ();
  736. } catch {}
  737. socket = null;
  738. }
  739. if (sendNext) {
  740. goAhead.Set ();
  741. SendNext ();
  742. }
  743. }
  744. }
  745. void Abort (object sender, EventArgs args)
  746. {
  747. HandleError (WebExceptionStatus.RequestCanceled, null, "Abort");
  748. }
  749. internal bool Busy {
  750. get { lock (this) return busy; }
  751. }
  752. internal bool Connected {
  753. get {
  754. lock (this) {
  755. return (socket != null && socket.Connected);
  756. }
  757. }
  758. }
  759. ~WebConnection ()
  760. {
  761. Close (false);
  762. }
  763. }
  764. }