WebConnection.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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. internal 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. }
  471. internal EventHandler SendRequest (HttpWebRequest request)
  472. {
  473. lock (this) {
  474. if (!busy) {
  475. busy = true;
  476. ThreadPool.RegisterWaitForSingleObject (goAhead, initConn,
  477. request, -1, true);
  478. } else {
  479. lock (queue) {
  480. queue.Enqueue (request);
  481. }
  482. }
  483. }
  484. return abortHandler;
  485. }
  486. void SendNext ()
  487. {
  488. lock (queue) {
  489. if (queue.Count > 0) {
  490. SendRequest ((HttpWebRequest) queue.Dequeue ());
  491. }
  492. }
  493. }
  494. internal void NextRead ()
  495. {
  496. lock (this) {
  497. busy = false;
  498. string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
  499. string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
  500. bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
  501. if (cncHeader != null) {
  502. cncHeader = cncHeader.ToLower ();
  503. keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive") != -1);
  504. }
  505. if ((socket != null && !socket.Connected) ||
  506. (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close") != -1))) {
  507. Close (false);
  508. }
  509. goAhead.Set ();
  510. lock (queue) {
  511. if (queue.Count > 0) {
  512. SendRequest ((HttpWebRequest) queue.Dequeue ());
  513. }
  514. }
  515. }
  516. }
  517. static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
  518. {
  519. bool foundCR = false;
  520. StringBuilder text = new StringBuilder ();
  521. int c = 0;
  522. while (start < max) {
  523. c = (int) buffer [start++];
  524. if (c == '\n') { // newline
  525. if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
  526. text.Length--;
  527. foundCR = false;
  528. break;
  529. } else if (foundCR) {
  530. text.Length--;
  531. break;
  532. }
  533. if (c == '\r')
  534. foundCR = true;
  535. text.Append ((char) c);
  536. }
  537. if (c != '\n' && c != '\r')
  538. return false;
  539. if (text.Length == 0) {
  540. output = null;
  541. return (c == '\n' || c == '\r');
  542. }
  543. if (foundCR)
  544. text.Length--;
  545. output = text.ToString ();
  546. return true;
  547. }
  548. internal IAsyncResult BeginRead (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  549. {
  550. if (nstream == null)
  551. return null;
  552. IAsyncResult result = null;
  553. if (!chunkedRead || chunkStream.WantMore) {
  554. try {
  555. result = nstream.BeginRead (buffer, offset, size, cb, state);
  556. cb = null;
  557. } catch (Exception) {
  558. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
  559. throw;
  560. }
  561. }
  562. if (chunkedRead) {
  563. WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
  564. wr.InnerAsyncResult = result;
  565. if (result == null) {
  566. // Will be completed from the data in ChunkStream
  567. wr.SetCompleted (true, (Exception) null);
  568. wr.DoCallback ();
  569. }
  570. return wr;
  571. }
  572. return result;
  573. }
  574. internal int EndRead (IAsyncResult result)
  575. {
  576. if (nstream == null)
  577. return 0;
  578. int nbytes = 0;
  579. WebAsyncResult wr = null;
  580. IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
  581. if (chunkedRead && (nsAsync is WebAsyncResult)) {
  582. wr = (WebAsyncResult) nsAsync;
  583. IAsyncResult inner = wr.InnerAsyncResult;
  584. if (inner != null && !(inner is WebAsyncResult))
  585. nbytes = nstream.EndRead (inner);
  586. } else {
  587. nbytes = nstream.EndRead (nsAsync);
  588. wr = (WebAsyncResult) result;
  589. }
  590. if (chunkedRead) {
  591. bool done = (nbytes == 0);
  592. try {
  593. chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
  594. if (!done && nbytes == 0 && chunkStream.WantMore)
  595. nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
  596. } catch (Exception e) {
  597. if (e is WebException)
  598. throw e;
  599. throw new WebException ("Invalid chunked data.", e,
  600. WebExceptionStatus.ServerProtocolViolation, null);
  601. }
  602. if ((done || nbytes == 0) && chunkStream.WantMore) {
  603. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
  604. throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
  605. }
  606. }
  607. return (nbytes != 0) ? nbytes : -1;
  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. WebExceptionStatus wes = WebExceptionStatus.SendFailure;
  703. // if SSL is in use then check for TrustFailure
  704. if (ssl && (bool) piTrustFailure.GetValue (nstream, null)) {
  705. wes = WebExceptionStatus.TrustFailure;
  706. }
  707. HandleError (wes, e, "Write");
  708. throw new WebException ("Not connected", e, wes, null);
  709. }
  710. }
  711. internal void Close (bool sendNext)
  712. {
  713. lock (this) {
  714. busy = false;
  715. if (nstream != null) {
  716. try {
  717. nstream.Close ();
  718. } catch {}
  719. nstream = null;
  720. }
  721. if (socket != null) {
  722. try {
  723. socket.Close ();
  724. } catch {}
  725. socket = null;
  726. }
  727. goAhead.Set ();
  728. if (sendNext)
  729. SendNext ();
  730. }
  731. }
  732. void Abort (object sender, EventArgs args)
  733. {
  734. lock (this) {
  735. if (Data.request == sender) {
  736. HandleError (WebExceptionStatus.RequestCanceled, null, "Abort");
  737. return;
  738. }
  739. lock (queue) {
  740. if (queue.Count > 0 && queue.Peek () == sender) {
  741. queue.Dequeue ();
  742. return;
  743. }
  744. object [] old = queue.ToArray ();
  745. queue.Clear ();
  746. for (int i = old.Length - 1; i >= 0; i--) {
  747. if (old [i] != sender)
  748. queue.Enqueue (old [i]);
  749. }
  750. }
  751. }
  752. }
  753. internal bool Busy {
  754. get { lock (this) return busy; }
  755. }
  756. internal bool Connected {
  757. get {
  758. lock (this) {
  759. return (socket != null && socket.Connected);
  760. }
  761. }
  762. }
  763. }
  764. }