WebConnection.cs 20 KB

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