WebConnection.cs 22 KB

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