WebConnection.cs 21 KB

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