2
0

WebConnection.cs 22 KB

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