2
0

WebConnection.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. //
  2. // System.Net.WebConnection
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. // Martin Baulig <[email protected]>
  7. //
  8. // (C) 2003 Ximian, Inc (http://www.ximian.com)
  9. // Copyright (c) 2017 Xamarin Inc. (http://www.xamarin.com)
  10. //
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System.IO;
  32. using System.Collections;
  33. using System.Net.Sockets;
  34. using System.Security.Cryptography.X509Certificates;
  35. using System.Text;
  36. using System.Threading;
  37. using System.Threading.Tasks;
  38. using System.Runtime.ExceptionServices;
  39. using System.Diagnostics;
  40. using Mono.Net.Security;
  41. namespace System.Net
  42. {
  43. enum ReadState
  44. {
  45. None,
  46. Status,
  47. Headers,
  48. Content,
  49. Aborted
  50. }
  51. class WebConnection : IDisposable
  52. {
  53. NetworkCredential ntlm_credentials;
  54. bool ntlm_authenticated;
  55. bool unsafe_sharing;
  56. Stream networkStream;
  57. Socket socket;
  58. MonoTlsStream monoTlsStream;
  59. WebConnectionTunnel tunnel;
  60. int disposed;
  61. public ServicePoint ServicePoint {
  62. get;
  63. }
  64. #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
  65. [System.Runtime.InteropServices.DllImport ("__Internal")]
  66. static extern void xamarin_start_wwan (string uri);
  67. #endif
  68. public WebConnection (ServicePoint sPoint)
  69. {
  70. ServicePoint = sPoint;
  71. }
  72. #if MONO_WEB_DEBUG
  73. internal static bool EnableWebDebug {
  74. get; set;
  75. }
  76. static WebConnection ()
  77. {
  78. if (Environment.GetEnvironmentVariable ("MONO_WEB_DEBUG") != null)
  79. EnableWebDebug = true;
  80. }
  81. #endif
  82. [Conditional ("MONO_WEB_DEBUG")]
  83. internal static void Debug (string message, params object[] args)
  84. {
  85. #if MONO_WEB_DEBUG
  86. if (EnableWebDebug)
  87. Console.Error.WriteLine (string.Format (message, args));
  88. #endif
  89. }
  90. [Conditional ("MONO_WEB_DEBUG")]
  91. internal static void Debug (string message)
  92. {
  93. #if MONO_WEB_DEBUG
  94. if (EnableWebDebug)
  95. Console.Error.WriteLine (message);
  96. #endif
  97. }
  98. bool CanReuse ()
  99. {
  100. // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
  101. // but if there's data pending to read (!) we won't reuse the socket.
  102. return (socket.Poll (0, SelectMode.SelectRead) == false);
  103. }
  104. bool CheckReusable ()
  105. {
  106. if (socket != null && socket.Connected) {
  107. try {
  108. if (CanReuse ())
  109. return true;
  110. } catch { }
  111. }
  112. return false;
  113. }
  114. async Task Connect (WebOperation operation, CancellationToken cancellationToken)
  115. {
  116. IPHostEntry hostEntry = ServicePoint.HostEntry;
  117. if (hostEntry == null || hostEntry.AddressList.Length == 0) {
  118. #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
  119. xamarin_start_wwan (ServicePoint.Address.ToString ());
  120. hostEntry = ServicePoint.HostEntry;
  121. if (hostEntry == null) {
  122. #endif
  123. throw GetException (ServicePoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
  124. WebExceptionStatus.NameResolutionFailure, null);
  125. #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
  126. }
  127. #endif
  128. }
  129. foreach (IPAddress address in hostEntry.AddressList) {
  130. operation.ThrowIfDisposed (cancellationToken);
  131. try {
  132. socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  133. } catch (Exception se) {
  134. // The Socket ctor can throw if we run out of FD's
  135. throw GetException (WebExceptionStatus.ConnectFailure, se);
  136. }
  137. IPEndPoint remote = new IPEndPoint (address, ServicePoint.Address.Port);
  138. socket.NoDelay = !ServicePoint.UseNagleAlgorithm;
  139. try {
  140. ServicePoint.KeepAliveSetup (socket);
  141. } catch {
  142. // Ignore. Not supported in all platforms.
  143. }
  144. if (!ServicePoint.CallEndPointDelegate (socket, remote)) {
  145. Interlocked.Exchange (ref socket, null)?.Close ();
  146. continue;
  147. } else {
  148. try {
  149. operation.ThrowIfDisposed (cancellationToken);
  150. await socket.ConnectAsync (remote).ConfigureAwait (false);
  151. } catch (ObjectDisposedException) {
  152. throw;
  153. } catch (Exception exc) {
  154. Interlocked.Exchange (ref socket, null)?.Close ();
  155. throw GetException (WebExceptionStatus.ConnectFailure, exc);
  156. }
  157. }
  158. if (socket != null)
  159. return;
  160. }
  161. throw GetException (WebExceptionStatus.ConnectFailure, null);
  162. }
  163. #if MONO_WEB_DEBUG
  164. static int nextID, nextRequestID;
  165. readonly int id = ++nextID;
  166. public int ID => disposed != 0 ? -id : id;
  167. #else
  168. internal readonly int ID;
  169. #endif
  170. async Task<bool> CreateStream (WebOperation operation, bool reused, CancellationToken cancellationToken)
  171. {
  172. #if MONO_WEB_DEBUG
  173. var requestID = ++nextRequestID;
  174. #else
  175. var requestID = 0;
  176. #endif
  177. try {
  178. var stream = new NetworkStream (socket, false);
  179. Debug ($"WC CREATE STREAM: Cnc={ID} {requestID} {reused} socket={socket.ID}");
  180. if (operation.Request.Address.Scheme == Uri.UriSchemeHttps) {
  181. if (!reused || monoTlsStream == null) {
  182. if (ServicePoint.UseConnect) {
  183. if (tunnel == null)
  184. tunnel = new WebConnectionTunnel (operation.Request, ServicePoint.Address);
  185. await tunnel.Initialize (stream, cancellationToken).ConfigureAwait (false);
  186. if (!tunnel.Success)
  187. return false;
  188. }
  189. monoTlsStream = new MonoTlsStream (operation.Request, stream);
  190. networkStream = await monoTlsStream.CreateStream (tunnel, cancellationToken).ConfigureAwait (false);
  191. }
  192. return true;
  193. }
  194. networkStream = stream;
  195. return true;
  196. } catch (Exception ex) {
  197. ex = HttpWebRequest.FlattenException (ex);
  198. Debug ($"WC CREATE STREAM EX: Cnc={ID} {requestID} {operation.Aborted} - {ex.Message}");
  199. if (operation.Aborted || monoTlsStream == null)
  200. throw GetException (WebExceptionStatus.ConnectFailure, ex);
  201. throw GetException (monoTlsStream.ExceptionStatus, ex);
  202. } finally {
  203. Debug ($"WC CREATE STREAM DONE: Cnc={ID} {requestID}");
  204. }
  205. }
  206. internal async Task<WebRequestStream> InitConnection (WebOperation operation, CancellationToken cancellationToken)
  207. {
  208. Debug ($"WC INIT CONNECTION: Cnc={ID} Req={operation.Request.ID} Op={operation.ID}");
  209. bool reset = true;
  210. retry:
  211. operation.ThrowIfClosedOrDisposed (cancellationToken);
  212. var reused = CheckReusable ();
  213. Debug ($"WC INIT CONNECTION #1: Cnc={ID} Op={operation.ID} - {reused} - {operation.WriteBuffer != null} {operation.IsNtlmChallenge}");
  214. if (!reused) {
  215. CloseSocket ();
  216. if (reset)
  217. Reset ();
  218. try {
  219. await Connect (operation, cancellationToken).ConfigureAwait (false);
  220. Debug ($"WC INIT CONNECTION #2: Cnc={ID} Op={operation.ID} {socket.LocalEndPoint}");
  221. } catch (Exception ex) {
  222. Debug ($"WC INIT CONNECTION #2 FAILED: Cnc={ID} Op={operation.ID} - {ex.Message}\n{ex}");
  223. throw;
  224. }
  225. }
  226. var success = await CreateStream (operation, reused, cancellationToken).ConfigureAwait (false);
  227. Debug ($"WC INIT CONNECTION #3: Cnc={ID} Op={operation.ID} - {success}");
  228. if (!success) {
  229. if (tunnel?.Challenge == null)
  230. throw GetException (WebExceptionStatus.ProtocolError, null);
  231. if (tunnel.CloseConnection)
  232. CloseSocket ();
  233. reset = false;
  234. goto retry;
  235. }
  236. return new WebRequestStream (this, operation, networkStream, tunnel);
  237. }
  238. internal static WebException GetException (WebExceptionStatus status, Exception error)
  239. {
  240. if (error == null)
  241. return new WebException ($"Error: {status}", status);
  242. if (error is WebException wex)
  243. return wex;
  244. return new WebException ($"Error: {status} ({error.Message})", status,
  245. WebExceptionInternalStatus.RequestFatal, error);
  246. }
  247. internal static bool ReadLine (byte[] buffer, ref int start, int max, ref string output)
  248. {
  249. bool foundCR = false;
  250. StringBuilder text = new StringBuilder ();
  251. int c = 0;
  252. while (start < max) {
  253. c = (int)buffer[start++];
  254. if (c == '\n') { // newline
  255. if ((text.Length > 0) && (text[text.Length - 1] == '\r'))
  256. text.Length--;
  257. foundCR = false;
  258. break;
  259. } else if (foundCR) {
  260. text.Length--;
  261. break;
  262. }
  263. if (c == '\r')
  264. foundCR = true;
  265. text.Append ((char)c);
  266. }
  267. if (c != '\n' && c != '\r')
  268. return false;
  269. if (text.Length == 0) {
  270. output = null;
  271. return (c == '\n' || c == '\r');
  272. }
  273. if (foundCR)
  274. text.Length--;
  275. output = text.ToString ();
  276. return true;
  277. }
  278. internal bool CanReuseConnection (WebOperation operation)
  279. {
  280. lock (this) {
  281. if (Closed || currentOperation != null)
  282. return false;
  283. if (!NtlmAuthenticated)
  284. return true;
  285. NetworkCredential cnc_cred = NtlmCredential;
  286. var request = operation.Request;
  287. bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.RequestUri));
  288. ICredentials req_icreds = (!isProxy) ? request.Credentials : request.Proxy.Credentials;
  289. NetworkCredential req_cred = (req_icreds != null) ? req_icreds.GetCredential (request.RequestUri, "NTLM") : null;
  290. if (cnc_cred == null || req_cred == null ||
  291. cnc_cred.Domain != req_cred.Domain || cnc_cred.UserName != req_cred.UserName ||
  292. cnc_cred.Password != req_cred.Password) {
  293. return false;
  294. }
  295. bool req_sharing = request.UnsafeAuthenticatedConnectionSharing;
  296. bool cnc_sharing = UnsafeAuthenticatedConnectionSharing;
  297. return !(req_sharing == false || req_sharing != cnc_sharing);
  298. }
  299. }
  300. bool PrepareSharingNtlm (WebOperation operation)
  301. {
  302. if (operation == null || !NtlmAuthenticated)
  303. return true;
  304. bool needs_reset = false;
  305. NetworkCredential cnc_cred = NtlmCredential;
  306. var request = operation.Request;
  307. bool isProxy = (request.Proxy != null && !request.Proxy.IsBypassed (request.RequestUri));
  308. ICredentials req_icreds = (!isProxy) ? request.Credentials : request.Proxy.Credentials;
  309. NetworkCredential req_cred = (req_icreds != null) ? req_icreds.GetCredential (request.RequestUri, "NTLM") : null;
  310. if (cnc_cred == null || req_cred == null ||
  311. cnc_cred.Domain != req_cred.Domain || cnc_cred.UserName != req_cred.UserName ||
  312. cnc_cred.Password != req_cred.Password) {
  313. needs_reset = true;
  314. }
  315. if (!needs_reset) {
  316. bool req_sharing = request.UnsafeAuthenticatedConnectionSharing;
  317. bool cnc_sharing = UnsafeAuthenticatedConnectionSharing;
  318. needs_reset = (req_sharing == false || req_sharing != cnc_sharing);
  319. }
  320. return needs_reset;
  321. }
  322. void Reset ()
  323. {
  324. lock (this) {
  325. tunnel = null;
  326. ResetNtlm ();
  327. }
  328. }
  329. void Close (bool reset)
  330. {
  331. lock (this) {
  332. CloseSocket ();
  333. if (reset)
  334. Reset ();
  335. }
  336. }
  337. void CloseSocket ()
  338. {
  339. lock (this) {
  340. if (networkStream != null) {
  341. try {
  342. networkStream.Dispose ();
  343. } catch { }
  344. networkStream = null;
  345. }
  346. if (socket != null) {
  347. try {
  348. socket.Dispose ();
  349. } catch { }
  350. socket = null;
  351. }
  352. monoTlsStream = null;
  353. }
  354. }
  355. DateTime idleSince;
  356. WebOperation currentOperation;
  357. public bool Closed => disposed != 0;
  358. public bool Busy {
  359. get { return currentOperation != null; }
  360. }
  361. public DateTime IdleSince {
  362. get { return idleSince; }
  363. }
  364. public bool StartOperation (WebOperation operation, bool reused)
  365. {
  366. lock (this) {
  367. if (Closed)
  368. return false;
  369. if (Interlocked.CompareExchange (ref currentOperation, operation, null) != null)
  370. return false;
  371. idleSince = DateTime.UtcNow + TimeSpan.FromDays (3650);
  372. if (reused && !PrepareSharingNtlm (operation)) {
  373. Debug ($"WC START - CAN'T REUSE: Cnc={ID} Op={operation.ID}");
  374. Close (true);
  375. }
  376. operation.RegisterRequest (ServicePoint, this);
  377. Debug ($"WC START: Cnc={ID} Op={operation.ID}");
  378. }
  379. operation.Run ();
  380. return true;
  381. }
  382. public bool Continue (WebOperation next)
  383. {
  384. lock (this) {
  385. if (Closed)
  386. return false;
  387. Debug ($"WC CONTINUE: Cnc={ID} connected={socket?.Connected} next={next?.ID} current={currentOperation?.ID}");
  388. if (socket == null || !socket.Connected || !PrepareSharingNtlm (next)) {
  389. Close (true);
  390. return false;
  391. }
  392. currentOperation = next;
  393. if (next == null)
  394. return true;
  395. // Ok, we got another connection. Let's run it!
  396. next.RegisterRequest (ServicePoint, this);
  397. }
  398. next.Run ();
  399. return true;
  400. }
  401. void Dispose (bool disposing)
  402. {
  403. if (Interlocked.CompareExchange (ref disposed, 1, 0) != 0)
  404. return;
  405. Debug ($"WC DISPOSE: Cnc={ID}");
  406. Close (true);
  407. }
  408. public void Dispose ()
  409. {
  410. Dispose (true);
  411. }
  412. void ResetNtlm ()
  413. {
  414. ntlm_authenticated = false;
  415. ntlm_credentials = null;
  416. unsafe_sharing = false;
  417. }
  418. internal bool NtlmAuthenticated {
  419. get { return ntlm_authenticated; }
  420. set { ntlm_authenticated = value; }
  421. }
  422. internal NetworkCredential NtlmCredential {
  423. get { return ntlm_credentials; }
  424. set { ntlm_credentials = value; }
  425. }
  426. internal bool UnsafeAuthenticatedConnectionSharing {
  427. get { return unsafe_sharing; }
  428. set { unsafe_sharing = value; }
  429. }
  430. // -
  431. }
  432. }