WebConnection.cs 24 KB

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