WebConnection.cs 32 KB

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