WebConnection.cs 25 KB

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