WebConnection.cs 28 KB

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