WebConnection.cs 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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. return false;
  269. } else if (status != 200) {
  270. string msg = String.Format ("The remote server returned a {0} status code.", status);
  271. HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
  272. return false;
  273. }
  274. return (result != null);
  275. }
  276. WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
  277. {
  278. retBuffer = null;
  279. status = 200;
  280. byte [] buffer = new byte [1024];
  281. MemoryStream ms = new MemoryStream ();
  282. while (true) {
  283. int n = stream.Read (buffer, 0, 1024);
  284. if (n == 0) {
  285. HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
  286. return null;
  287. }
  288. ms.Write (buffer, 0, n);
  289. int start = 0;
  290. string str = null;
  291. bool gotStatus = false;
  292. WebHeaderCollection headers = new WebHeaderCollection ();
  293. while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
  294. if (str == null) {
  295. int contentLen = 0;
  296. try {
  297. contentLen = int.Parse(headers["Content-Length"]);
  298. }
  299. catch {
  300. contentLen = 0;
  301. }
  302. if (ms.Length - start - contentLen > 0) {
  303. // we've read more data than the response header and conents,
  304. // give back extra data to the caller
  305. retBuffer = new byte[ms.Length - start - contentLen];
  306. Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
  307. }
  308. else {
  309. // haven't read in some or all of the contents for the response, do so now
  310. FlushContents(stream, contentLen - (int)(ms.Length - start));
  311. }
  312. return headers;
  313. }
  314. if (gotStatus) {
  315. headers.Add (str);
  316. continue;
  317. }
  318. string[] parts = str.Split (' ');
  319. if (parts.Length < 2) {
  320. HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
  321. return null;
  322. }
  323. if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
  324. Data.ProxyVersion = HttpVersion.Version11;
  325. else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
  326. Data.ProxyVersion = HttpVersion.Version10;
  327. else {
  328. HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
  329. return null;
  330. }
  331. status = (int)UInt32.Parse (parts [1]);
  332. gotStatus = true;
  333. }
  334. }
  335. }
  336. void FlushContents(Stream stream, int contentLength)
  337. {
  338. while (contentLength > 0) {
  339. byte[] contentBuffer = new byte[contentLength];
  340. int bytesRead = stream.Read(contentBuffer, 0, contentLength);
  341. if (bytesRead > 0) {
  342. contentLength -= bytesRead;
  343. }
  344. else {
  345. break;
  346. }
  347. }
  348. }
  349. bool CreateStream (HttpWebRequest request)
  350. {
  351. try {
  352. NetworkStream serverStream = new NetworkStream (socket, false);
  353. if (request.Address.Scheme == Uri.UriSchemeHttps) {
  354. #if SECURITY_DEP
  355. if (!reused || nstream == null || tlsStream == null) {
  356. byte [] buffer = null;
  357. if (sPoint.UseConnect) {
  358. bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
  359. if (!ok)
  360. return false;
  361. }
  362. tlsStream = new MonoTlsStream (request, serverStream);
  363. nstream = tlsStream.CreateStream (buffer);
  364. }
  365. // we also need to set ServicePoint.Certificate
  366. // and ServicePoint.ClientCertificate but this can
  367. // only be done later (after handshake - which is
  368. // done only after a read operation).
  369. #else
  370. throw new NotSupportedException ();
  371. #endif
  372. } else {
  373. nstream = serverStream;
  374. }
  375. } catch (Exception ex) {
  376. if (tlsStream != null)
  377. status = tlsStream.ExceptionStatus;
  378. else if (!request.Aborted)
  379. status = WebExceptionStatus.ConnectFailure;
  380. connect_exception = ex;
  381. return false;
  382. }
  383. return true;
  384. }
  385. void HandleError (WebExceptionStatus st, Exception e, string where)
  386. {
  387. status = st;
  388. lock (this) {
  389. if (st == WebExceptionStatus.RequestCanceled)
  390. Data = new WebConnectionData ();
  391. }
  392. if (e == null) { // At least we now where it comes from
  393. try {
  394. throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
  395. } catch (Exception e2) {
  396. e = e2;
  397. }
  398. }
  399. HttpWebRequest req = null;
  400. if (Data != null && Data.request != null)
  401. req = Data.request;
  402. Close (true);
  403. if (req != null) {
  404. req.FinishedReading = true;
  405. req.SetResponseError (st, e, where);
  406. }
  407. }
  408. static void ReadDone (IAsyncResult result)
  409. {
  410. WebConnection cnc = (WebConnection)result.AsyncState;
  411. WebConnectionData data = cnc.Data;
  412. Stream ns = cnc.nstream;
  413. if (ns == null) {
  414. cnc.Close (true);
  415. return;
  416. }
  417. int nread = -1;
  418. try {
  419. nread = ns.EndRead (result);
  420. } catch (ObjectDisposedException) {
  421. return;
  422. } catch (Exception e) {
  423. if (e.InnerException is ObjectDisposedException)
  424. return;
  425. cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
  426. return;
  427. }
  428. if (nread == 0) {
  429. cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
  430. return;
  431. }
  432. if (nread < 0) {
  433. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
  434. return;
  435. }
  436. int pos = -1;
  437. nread += cnc.position;
  438. if (data.ReadState == ReadState.None) {
  439. Exception exc = null;
  440. try {
  441. pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
  442. } catch (Exception e) {
  443. exc = e;
  444. }
  445. if (exc != null || pos == -1) {
  446. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
  447. return;
  448. }
  449. }
  450. if (data.ReadState == ReadState.Aborted) {
  451. cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
  452. return;
  453. }
  454. if (data.ReadState != ReadState.Content) {
  455. int est = nread * 2;
  456. int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
  457. byte [] newBuffer = new byte [max];
  458. Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
  459. cnc.buffer = newBuffer;
  460. cnc.position = nread;
  461. data.ReadState = ReadState.None;
  462. InitRead (cnc);
  463. return;
  464. }
  465. cnc.position = 0;
  466. WebConnectionStream stream = new WebConnectionStream (cnc, data);
  467. bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
  468. string tencoding = null;
  469. if (expect_content)
  470. tencoding = data.Headers ["Transfer-Encoding"];
  471. cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
  472. if (!cnc.chunkedRead) {
  473. stream.ReadBuffer = cnc.buffer;
  474. stream.ReadBufferOffset = pos;
  475. stream.ReadBufferSize = nread;
  476. try {
  477. stream.CheckResponseInBuffer ();
  478. } catch (Exception e) {
  479. cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
  480. }
  481. } else if (cnc.chunkStream == null) {
  482. try {
  483. cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
  484. } catch (Exception e) {
  485. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
  486. return;
  487. }
  488. } else {
  489. cnc.chunkStream.ResetBuffer ();
  490. try {
  491. cnc.chunkStream.Write (cnc.buffer, pos, nread);
  492. } catch (Exception e) {
  493. cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
  494. return;
  495. }
  496. }
  497. data.stream = stream;
  498. if (!expect_content)
  499. stream.ForceCompletion ();
  500. data.request.SetResponseData (data);
  501. }
  502. static bool ExpectContent (int statusCode, string method)
  503. {
  504. if (method == "HEAD")
  505. return false;
  506. return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
  507. }
  508. internal static void InitRead (object state)
  509. {
  510. WebConnection cnc = (WebConnection) state;
  511. Stream ns = cnc.nstream;
  512. try {
  513. int size = cnc.buffer.Length - cnc.position;
  514. ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
  515. } catch (Exception e) {
  516. cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
  517. }
  518. }
  519. static int GetResponse (WebConnectionData data, ServicePoint sPoint,
  520. byte [] buffer, int max)
  521. {
  522. int pos = 0;
  523. string line = null;
  524. bool lineok = false;
  525. bool isContinue = false;
  526. bool emptyFirstLine = false;
  527. do {
  528. if (data.ReadState == ReadState.Aborted)
  529. return -1;
  530. if (data.ReadState == ReadState.None) {
  531. lineok = ReadLine (buffer, ref pos, max, ref line);
  532. if (!lineok)
  533. return 0;
  534. if (line == null) {
  535. emptyFirstLine = true;
  536. continue;
  537. }
  538. emptyFirstLine = false;
  539. data.ReadState = ReadState.Status;
  540. string [] parts = line.Split (' ');
  541. if (parts.Length < 2)
  542. return -1;
  543. if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
  544. data.Version = HttpVersion.Version11;
  545. sPoint.SetVersion (HttpVersion.Version11);
  546. } else {
  547. data.Version = HttpVersion.Version10;
  548. sPoint.SetVersion (HttpVersion.Version10);
  549. }
  550. data.StatusCode = (int) UInt32.Parse (parts [1]);
  551. if (parts.Length >= 3)
  552. data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
  553. else
  554. data.StatusDescription = "";
  555. if (pos >= max)
  556. return pos;
  557. }
  558. emptyFirstLine = false;
  559. if (data.ReadState == ReadState.Status) {
  560. data.ReadState = ReadState.Headers;
  561. data.Headers = new WebHeaderCollection ();
  562. ArrayList headers = new ArrayList ();
  563. bool finished = false;
  564. while (!finished) {
  565. if (ReadLine (buffer, ref pos, max, ref line) == false)
  566. break;
  567. if (line == null) {
  568. // Empty line: end of headers
  569. finished = true;
  570. continue;
  571. }
  572. if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
  573. int count = headers.Count - 1;
  574. if (count < 0)
  575. break;
  576. string prev = (string) headers [count] + line;
  577. headers [count] = prev;
  578. } else {
  579. headers.Add (line);
  580. }
  581. }
  582. if (!finished)
  583. return 0;
  584. // .NET uses ParseHeaders or ParseHeadersStrict which is much better
  585. foreach (string s in headers) {
  586. int pos_s = s.IndexOf (':');
  587. if (pos_s == -1)
  588. throw new ArgumentException ("no colon found", "header");
  589. var header = s.Substring (0, pos_s);
  590. var value = s.Substring (pos_s + 1).Trim ();
  591. var h = data.Headers;
  592. if (h.AllowMultiValues (header)) {
  593. h.AddInternal (header, value);
  594. } else {
  595. h.SetInternal (header, value);
  596. }
  597. }
  598. if (data.StatusCode == (int) HttpStatusCode.Continue) {
  599. sPoint.SendContinue = true;
  600. if (pos >= max)
  601. return pos;
  602. if (data.request.ExpectContinue) {
  603. data.request.DoContinueDelegate (data.StatusCode, data.Headers);
  604. // Prevent double calls when getting the
  605. // headers in several packets.
  606. data.request.ExpectContinue = false;
  607. }
  608. data.ReadState = ReadState.None;
  609. isContinue = true;
  610. }
  611. else {
  612. data.ReadState = ReadState.Content;
  613. return pos;
  614. }
  615. }
  616. } while (emptyFirstLine || isContinue);
  617. return -1;
  618. }
  619. void InitConnection (object state)
  620. {
  621. HttpWebRequest request = (HttpWebRequest) state;
  622. request.WebConnection = this;
  623. if (request.ReuseConnection)
  624. request.StoredConnection = this;
  625. if (request.Aborted)
  626. return;
  627. keepAlive = request.KeepAlive;
  628. Data = new WebConnectionData (request);
  629. retry:
  630. Connect (request);
  631. if (request.Aborted)
  632. return;
  633. if (status != WebExceptionStatus.Success) {
  634. if (!request.Aborted) {
  635. request.SetWriteStreamError (status, connect_exception);
  636. Close (true);
  637. }
  638. return;
  639. }
  640. if (!CreateStream (request)) {
  641. if (request.Aborted)
  642. return;
  643. WebExceptionStatus st = status;
  644. if (Data.Challenge != null)
  645. goto retry;
  646. Exception cnc_exc = connect_exception;
  647. if (cnc_exc == null && (Data.StatusCode == 401 || Data.StatusCode == 407)) {
  648. st = WebExceptionStatus.ProtocolError;
  649. cnc_exc = new WebException (Data.StatusCode == 407 ? "(407) Proxy Authentication Required" : "(401) Unauthorized" , st);
  650. }
  651. connect_exception = null;
  652. request.SetWriteStreamError (st, cnc_exc);
  653. Close (true);
  654. return;
  655. }
  656. request.SetWriteStream (new WebConnectionStream (this, request));
  657. }
  658. #if MONOTOUCH
  659. static bool warned_about_queue = false;
  660. #endif
  661. internal EventHandler SendRequest (HttpWebRequest request)
  662. {
  663. if (request.Aborted)
  664. return null;
  665. lock (this) {
  666. if (state.TrySetBusy ()) {
  667. status = WebExceptionStatus.Success;
  668. ThreadPool.QueueUserWorkItem (initConn, request);
  669. } else {
  670. lock (queue) {
  671. #if MONOTOUCH
  672. if (!warned_about_queue) {
  673. warned_about_queue = true;
  674. Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
  675. }
  676. #endif
  677. queue.Enqueue (request);
  678. }
  679. }
  680. }
  681. return abortHandler;
  682. }
  683. void SendNext ()
  684. {
  685. lock (queue) {
  686. if (queue.Count > 0) {
  687. SendRequest ((HttpWebRequest) queue.Dequeue ());
  688. }
  689. }
  690. }
  691. internal void NextRead ()
  692. {
  693. lock (this) {
  694. if (Data.request != null)
  695. Data.request.FinishedReading = true;
  696. string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
  697. string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
  698. bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
  699. if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
  700. keepAlive = false;
  701. if (cncHeader != null) {
  702. cncHeader = cncHeader.ToLower ();
  703. keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
  704. }
  705. if ((socket != null && !socket.Connected) ||
  706. (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
  707. Close (false);
  708. }
  709. state.SetIdle ();
  710. if (priority_request != null) {
  711. SendRequest (priority_request);
  712. priority_request = null;
  713. } else {
  714. SendNext ();
  715. }
  716. }
  717. }
  718. static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
  719. {
  720. bool foundCR = false;
  721. StringBuilder text = new StringBuilder ();
  722. int c = 0;
  723. while (start < max) {
  724. c = (int) buffer [start++];
  725. if (c == '\n') { // newline
  726. if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
  727. text.Length--;
  728. foundCR = false;
  729. break;
  730. } else if (foundCR) {
  731. text.Length--;
  732. break;
  733. }
  734. if (c == '\r')
  735. foundCR = true;
  736. text.Append ((char) c);
  737. }
  738. if (c != '\n' && c != '\r')
  739. return false;
  740. if (text.Length == 0) {
  741. output = null;
  742. return (c == '\n' || c == '\r');
  743. }
  744. if (foundCR)
  745. text.Length--;
  746. output = text.ToString ();
  747. return true;
  748. }
  749. internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  750. {
  751. Stream s = null;
  752. lock (this) {
  753. if (Data.request != request)
  754. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  755. if (nstream == null)
  756. return null;
  757. s = nstream;
  758. }
  759. IAsyncResult result = null;
  760. if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
  761. try {
  762. result = s.BeginRead (buffer, offset, size, cb, state);
  763. cb = null;
  764. } catch (Exception) {
  765. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
  766. throw;
  767. }
  768. }
  769. if (chunkedRead) {
  770. WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
  771. wr.InnerAsyncResult = result;
  772. if (result == null) {
  773. // Will be completed from the data in ChunkStream
  774. wr.SetCompleted (true, (Exception) null);
  775. wr.DoCallback ();
  776. }
  777. return wr;
  778. }
  779. return result;
  780. }
  781. internal int EndRead (HttpWebRequest request, IAsyncResult result)
  782. {
  783. Stream s = null;
  784. lock (this) {
  785. if (request.Aborted)
  786. throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
  787. if (Data.request != request)
  788. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  789. if (nstream == null)
  790. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  791. s = nstream;
  792. }
  793. int nbytes = 0;
  794. bool done = false;
  795. WebAsyncResult wr = null;
  796. IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
  797. if (chunkedRead && (nsAsync is WebAsyncResult)) {
  798. wr = (WebAsyncResult) nsAsync;
  799. IAsyncResult inner = wr.InnerAsyncResult;
  800. if (inner != null && !(inner is WebAsyncResult)) {
  801. nbytes = s.EndRead (inner);
  802. done = nbytes == 0;
  803. }
  804. } else if (!(nsAsync is WebAsyncResult)) {
  805. nbytes = s.EndRead (nsAsync);
  806. wr = (WebAsyncResult) result;
  807. done = nbytes == 0;
  808. }
  809. if (chunkedRead) {
  810. try {
  811. chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
  812. if (!done && nbytes == 0 && chunkStream.WantMore)
  813. nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
  814. } catch (Exception e) {
  815. if (e is WebException)
  816. throw e;
  817. throw new WebException ("Invalid chunked data.", e,
  818. WebExceptionStatus.ServerProtocolViolation, null);
  819. }
  820. if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
  821. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
  822. throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
  823. }
  824. }
  825. return (nbytes != 0) ? nbytes : -1;
  826. }
  827. // To be called on chunkedRead when we can read no data from the ChunkStream yet
  828. int EnsureRead (byte [] buffer, int offset, int size)
  829. {
  830. byte [] morebytes = null;
  831. int nbytes = 0;
  832. while (nbytes == 0 && chunkStream.WantMore) {
  833. int localsize = chunkStream.ChunkLeft;
  834. if (localsize <= 0) // not read chunk size yet
  835. localsize = 1024;
  836. else if (localsize > 16384)
  837. localsize = 16384;
  838. if (morebytes == null || morebytes.Length < localsize)
  839. morebytes = new byte [localsize];
  840. int nread = nstream.Read (morebytes, 0, localsize);
  841. if (nread <= 0)
  842. return 0; // Error
  843. chunkStream.Write (morebytes, 0, nread);
  844. nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
  845. }
  846. return nbytes;
  847. }
  848. bool CompleteChunkedRead()
  849. {
  850. if (!chunkedRead || chunkStream == null)
  851. return true;
  852. while (chunkStream.WantMore) {
  853. int nbytes = nstream.Read (buffer, 0, buffer.Length);
  854. if (nbytes <= 0)
  855. return false; // Socket was disconnected
  856. chunkStream.Write (buffer, 0, nbytes);
  857. }
  858. return true;
  859. }
  860. internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
  861. {
  862. Stream s = null;
  863. lock (this) {
  864. if (Data.request != request)
  865. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  866. if (nstream == null)
  867. return null;
  868. s = nstream;
  869. }
  870. IAsyncResult result = null;
  871. try {
  872. result = s.BeginWrite (buffer, offset, size, cb, state);
  873. } catch (Exception) {
  874. status = WebExceptionStatus.SendFailure;
  875. throw;
  876. }
  877. return result;
  878. }
  879. internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
  880. {
  881. Stream s = null;
  882. lock (this) {
  883. if (status == WebExceptionStatus.RequestCanceled)
  884. return true;
  885. if (Data.request != request)
  886. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  887. if (nstream == null)
  888. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  889. s = nstream;
  890. }
  891. try {
  892. s.EndWrite (result);
  893. return true;
  894. } catch (Exception exc) {
  895. status = WebExceptionStatus.SendFailure;
  896. if (throwOnError && exc.InnerException != null)
  897. throw exc.InnerException;
  898. return false;
  899. }
  900. }
  901. internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
  902. {
  903. Stream s = null;
  904. lock (this) {
  905. if (Data.request != request)
  906. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  907. if (nstream == null)
  908. return 0;
  909. s = nstream;
  910. }
  911. int result = 0;
  912. try {
  913. bool done = false;
  914. if (!chunkedRead) {
  915. result = s.Read (buffer, offset, size);
  916. done = (result == 0);
  917. }
  918. if (chunkedRead) {
  919. try {
  920. chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
  921. if (!done && result == 0 && chunkStream.WantMore)
  922. result = EnsureRead (buffer, offset, size);
  923. } catch (Exception e) {
  924. HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
  925. throw;
  926. }
  927. if ((done || result == 0) && chunkStream.WantMore) {
  928. HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
  929. throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
  930. }
  931. }
  932. } catch (Exception e) {
  933. HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
  934. }
  935. return result;
  936. }
  937. internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
  938. {
  939. err_msg = null;
  940. Stream s = null;
  941. lock (this) {
  942. if (Data.request != request)
  943. throw new ObjectDisposedException (typeof (NetworkStream).FullName);
  944. s = nstream;
  945. if (s == null)
  946. return false;
  947. }
  948. try {
  949. s.Write (buffer, offset, size);
  950. } catch (Exception e) {
  951. err_msg = e.Message;
  952. WebExceptionStatus wes = WebExceptionStatus.SendFailure;
  953. string msg = "Write: " + err_msg;
  954. if (e is WebException) {
  955. HandleError (wes, e, msg);
  956. return false;
  957. }
  958. HandleError (wes, e, msg);
  959. return false;
  960. }
  961. return true;
  962. }
  963. internal void Close (bool sendNext)
  964. {
  965. lock (this) {
  966. if (Data != null && Data.request != null && Data.request.ReuseConnection) {
  967. Data.request.ReuseConnection = false;
  968. return;
  969. }
  970. if (nstream != null) {
  971. try {
  972. nstream.Close ();
  973. } catch {}
  974. nstream = null;
  975. }
  976. if (socket != null) {
  977. try {
  978. socket.Close ();
  979. } catch {}
  980. socket = null;
  981. }
  982. if (ntlm_authenticated)
  983. ResetNtlm ();
  984. if (Data != null) {
  985. lock (Data) {
  986. Data.ReadState = ReadState.Aborted;
  987. }
  988. }
  989. state.SetIdle ();
  990. Data = new WebConnectionData ();
  991. if (sendNext)
  992. SendNext ();
  993. connect_request = null;
  994. connect_ntlm_auth_state = NtlmAuthState.None;
  995. }
  996. }
  997. void Abort (object sender, EventArgs args)
  998. {
  999. lock (this) {
  1000. lock (queue) {
  1001. HttpWebRequest req = (HttpWebRequest) sender;
  1002. if (Data.request == req || Data.request == null) {
  1003. if (!req.FinishedReading) {
  1004. status = WebExceptionStatus.RequestCanceled;
  1005. Close (false);
  1006. if (queue.Count > 0) {
  1007. Data.request = (HttpWebRequest) queue.Dequeue ();
  1008. SendRequest (Data.request);
  1009. }
  1010. }
  1011. return;
  1012. }
  1013. req.FinishedReading = true;
  1014. req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
  1015. if (queue.Count > 0 && queue.Peek () == sender) {
  1016. queue.Dequeue ();
  1017. } else if (queue.Count > 0) {
  1018. object [] old = queue.ToArray ();
  1019. queue.Clear ();
  1020. for (int i = old.Length - 1; i >= 0; i--) {
  1021. if (old [i] != sender)
  1022. queue.Enqueue (old [i]);
  1023. }
  1024. }
  1025. }
  1026. }
  1027. }
  1028. internal void ResetNtlm ()
  1029. {
  1030. ntlm_authenticated = false;
  1031. ntlm_credentials = null;
  1032. unsafe_sharing = false;
  1033. }
  1034. internal bool Connected {
  1035. get {
  1036. lock (this) {
  1037. return (socket != null && socket.Connected);
  1038. }
  1039. }
  1040. }
  1041. // -Used for NTLM authentication
  1042. internal HttpWebRequest PriorityRequest {
  1043. set { priority_request = value; }
  1044. }
  1045. internal bool NtlmAuthenticated {
  1046. get { return ntlm_authenticated; }
  1047. set { ntlm_authenticated = value; }
  1048. }
  1049. internal NetworkCredential NtlmCredential {
  1050. get { return ntlm_credentials; }
  1051. set { ntlm_credentials = value; }
  1052. }
  1053. internal bool UnsafeAuthenticatedConnectionSharing {
  1054. get { return unsafe_sharing; }
  1055. set { unsafe_sharing = value; }
  1056. }
  1057. // -
  1058. }
  1059. }