TCPConnector.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. #if !UNITY_WEBGL || UNITY_EDITOR
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. #if !NETFX_CORE || UNITY_EDITOR
  6. using System.Net.Security;
  7. #endif
  8. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls;
  10. using BestHTTP.Connections.TLS;
  11. using System.Threading;
  12. #endif
  13. #if NETFX_CORE
  14. using System.Threading.Tasks;
  15. using Windows.Networking.Sockets;
  16. using TcpClient = BestHTTP.PlatformSupport.TcpClient.WinRT.TcpClient;
  17. //Disable CD4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
  18. #pragma warning disable 4014
  19. #else
  20. using TcpClient = BestHTTP.PlatformSupport.TcpClient.General.TcpClient;
  21. using System.Security.Cryptography.X509Certificates;
  22. #endif
  23. using BestHTTP.Timings;
  24. namespace BestHTTP.Connections
  25. {
  26. public sealed class TCPConnector : IDisposable
  27. {
  28. public bool IsConnected { get { return this.Client != null && this.Client.Connected; } }
  29. public string NegotiatedProtocol { get; private set; }
  30. public TcpClient Client { get; private set; }
  31. public Stream TopmostStream { get; private set; }
  32. public Stream Stream { get; private set; }
  33. public bool LeaveOpen { get; set; }
  34. public void Connect(HTTPRequest request)
  35. {
  36. string negotiatedProtocol = HTTPProtocolFactory.W3C_HTTP1;
  37. Uri uri =
  38. #if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR)
  39. request.HasProxy ? request.Proxy.Address :
  40. #endif
  41. request.CurrentUri;
  42. #region TCP Connection
  43. if (Client == null)
  44. Client = new TcpClient();
  45. if (!Client.Connected)
  46. {
  47. Client.ConnectTimeout = request.ConnectTimeout;
  48. #if NETFX_CORE
  49. Client.UseHTTPSProtocol =
  50. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  51. !Request.UseAlternateSSL &&
  52. #endif
  53. HTTPProtocolFactory.IsSecureProtocol(uri);
  54. #endif
  55. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  56. HTTPManager.Logger.Verbose("TCPConnector", string.Format("'{0}' - Connecting to {1}:{2}", request.CurrentUri.ToString(), uri.Host, uri.Port.ToString()), request.Context);
  57. #if !NETFX_CORE && (!UNITY_WEBGL || UNITY_EDITOR)
  58. bool changed = false;
  59. int? sendBufferSize = null, receiveBufferSize = null;
  60. if (HTTPManager.SendBufferSize.HasValue)
  61. {
  62. sendBufferSize = Client.SendBufferSize;
  63. Client.SendBufferSize = HTTPManager.SendBufferSize.Value;
  64. changed = true;
  65. }
  66. if (HTTPManager.ReceiveBufferSize.HasValue)
  67. {
  68. receiveBufferSize = Client.ReceiveBufferSize;
  69. Client.ReceiveBufferSize = HTTPManager.ReceiveBufferSize.Value;
  70. changed = true;
  71. }
  72. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  73. {
  74. if (changed)
  75. HTTPManager.Logger.Verbose("TCPConnector", string.Format("'{0}' - Buffer sizes changed - Send from: {1} to: {2}, Receive from: {3} to: {4}, Blocking: {5}",
  76. request.CurrentUri.ToString(),
  77. sendBufferSize,
  78. Client.SendBufferSize,
  79. receiveBufferSize,
  80. Client.ReceiveBufferSize,
  81. Client.Client.Blocking),
  82. request.Context);
  83. else
  84. HTTPManager.Logger.Verbose("TCPConnector", string.Format("'{0}' - Buffer sizes - Send: {1} Receive: {2} Blocking: {3}", request.CurrentUri.ToString(), Client.SendBufferSize, Client.ReceiveBufferSize, Client.Client.Blocking), request.Context);
  85. }
  86. #endif
  87. #if NETFX_CORE && !UNITY_EDITOR && !ENABLE_IL2CPP
  88. try
  89. {
  90. Client.Connect(uri.Host, uri.Port);
  91. }
  92. finally
  93. {
  94. request.Timing.Add(TimingEventNames.TCP_Connection);
  95. }
  96. #else
  97. System.Net.IPAddress[] addresses = null;
  98. try
  99. {
  100. if (Client.ConnectTimeout > TimeSpan.Zero)
  101. {
  102. // https://forum.unity3d.com/threads/best-http-released.200006/page-37#post-3150972
  103. using (System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false))
  104. {
  105. IAsyncResult result = System.Net.Dns.BeginGetHostAddresses(uri.Host, (res) => { try { mre.Set(); } catch { } }, null);
  106. bool success = mre.WaitOne(Client.ConnectTimeout);
  107. if (success)
  108. {
  109. addresses = System.Net.Dns.EndGetHostAddresses(result);
  110. }
  111. else
  112. {
  113. throw new TimeoutException("DNS resolve timed out!");
  114. }
  115. }
  116. }
  117. else
  118. {
  119. addresses = System.Net.Dns.GetHostAddresses(uri.Host);
  120. }
  121. }
  122. finally
  123. {
  124. request.Timing.Add(TimingEventNames.DNS_Lookup);
  125. }
  126. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  127. HTTPManager.Logger.Verbose("TCPConnector", string.Format("'{0}' - DNS Query returned with addresses: {1}", request.CurrentUri.ToString(), addresses != null ? addresses.Length : -1), request.Context);
  128. if (request.IsCancellationRequested)
  129. throw new Exception("IsCancellationRequested");
  130. try
  131. {
  132. Client.Connect(addresses, uri.Port, request);
  133. }
  134. finally
  135. {
  136. request.Timing.Add(TimingEventNames.TCP_Connection);
  137. }
  138. if (request.IsCancellationRequested)
  139. throw new Exception("IsCancellationRequested");
  140. #endif
  141. if (HTTPManager.Logger.Level <= Logger.Loglevels.Information)
  142. HTTPManager.Logger.Information("TCPConnector", "Connected to " + uri.Host + ":" + uri.Port.ToString(), request.Context);
  143. }
  144. else if (HTTPManager.Logger.Level <= Logger.Loglevels.Information)
  145. HTTPManager.Logger.Information("TCPConnector", "Already connected to " + uri.Host + ":" + uri.Port.ToString(), request.Context);
  146. #endregion
  147. if (Stream == null)
  148. {
  149. bool isSecure = HTTPProtocolFactory.IsSecureProtocol(request.CurrentUri);
  150. // set the stream to Client.GetStream() so the proxy, if there's any can use it directly.
  151. this.Stream = this.TopmostStream = Client.GetStream();
  152. /*if (Stream.CanTimeout)
  153. Stream.ReadTimeout = Stream.WriteTimeout = (int)Request.Timeout.TotalMilliseconds;*/
  154. #if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR)
  155. if (request.HasProxy)
  156. {
  157. try
  158. {
  159. request.Proxy.Connect(this.Stream, request);
  160. }
  161. finally
  162. {
  163. request.Timing.Add(TimingEventNames.Proxy_Negotiation);
  164. }
  165. }
  166. if (request.IsCancellationRequested)
  167. throw new Exception("IsCancellationRequested");
  168. #endif
  169. // proxy connect is done, we can set the stream to a buffered one. HTTPProxy requires the raw NetworkStream for HTTPResponse's ReadUnknownSize!
  170. this.Stream = this.TopmostStream = new BufferedReadNetworkStream(Client.GetStream(), Math.Max(8 * 1024, HTTPManager.ReceiveBufferSize ?? Client.ReceiveBufferSize));
  171. // We have to use Request.CurrentUri here, because uri can be a proxy uri with a different protocol
  172. if (isSecure)
  173. {
  174. DateTime tlsNegotiationStartedAt = DateTime.Now;
  175. #region SSL Upgrade
  176. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  177. if (HTTPManager.UseAlternateSSLDefaultValue)
  178. {
  179. var handler = new TlsClientProtocol(this.Stream);
  180. List<ProtocolName> protocols = new List<ProtocolName>();
  181. #if !BESTHTTP_DISABLE_HTTP2
  182. SupportedProtocols protocol = HTTPProtocolFactory.GetProtocolFromUri(request.CurrentUri);
  183. if (protocol == SupportedProtocols.HTTP && request.IsKeepAlive)
  184. {
  185. // http/2 over tls (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)
  186. protocols.Add(ProtocolName.AsUtf8Encoding(HTTPProtocolFactory.W3C_HTTP2));
  187. }
  188. #endif
  189. protocols.Add(ProtocolName.AsUtf8Encoding(HTTPProtocolFactory.W3C_HTTP1));
  190. AbstractTls13Client tlsClient = null;
  191. if (HTTPManager.TlsClientFactory == null)
  192. {
  193. tlsClient = HTTPManager.DefaultTlsClientFactory(request, protocols);
  194. }
  195. else
  196. {
  197. try
  198. {
  199. tlsClient = HTTPManager.TlsClientFactory(request, protocols);
  200. }
  201. catch (Exception ex)
  202. {
  203. HTTPManager.Logger.Exception(nameof(TCPConnector), nameof(HTTPManager.TlsClientFactory), ex, request.Context);
  204. }
  205. if (tlsClient == null)
  206. tlsClient = HTTPManager.DefaultTlsClientFactory(request, protocols);
  207. }
  208. //tlsClient.LoggingContext = request.Context;
  209. handler.Connect(tlsClient);
  210. var applicationProtocol = tlsClient.GetNegotiatedApplicationProtocol();
  211. if (!string.IsNullOrEmpty(applicationProtocol))
  212. negotiatedProtocol = applicationProtocol;
  213. Stream = handler.Stream;
  214. }
  215. else
  216. #endif
  217. {
  218. #if !NETFX_CORE
  219. SslStream sslStream = null;
  220. if (HTTPManager.ClientCertificationProvider == null)
  221. sslStream = new SslStream(Client.GetStream(), false, (sender, cert, chain, errors) =>
  222. {
  223. if (HTTPManager.DefaultCertificationValidator != null)
  224. return HTTPManager.DefaultCertificationValidator(request, cert, chain, errors);
  225. else
  226. return true;
  227. });
  228. else
  229. sslStream = new SslStream(Client.GetStream(), false, (sender, cert, chain, errors) =>
  230. {
  231. if (HTTPManager.DefaultCertificationValidator != null)
  232. return HTTPManager.DefaultCertificationValidator(request, cert, chain, errors);
  233. else
  234. return true;
  235. },
  236. (object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) =>
  237. {
  238. return HTTPManager.ClientCertificationProvider(request, targetHost, localCertificates, remoteCertificate, acceptableIssuers);
  239. });
  240. if (!sslStream.IsAuthenticated)
  241. {
  242. #if !BESTHTTP_DISABLE_HTTP2 && !BESTHTTP_DISABLE_ALTERNATE_SSL && false
  243. List<SslApplicationProtocol> protocols = new List<SslApplicationProtocol>();
  244. SupportedProtocols protocol = HTTPProtocolFactory.GetProtocolFromUri(request.CurrentUri);
  245. if (protocol == SupportedProtocols.HTTP && request.IsKeepAlive)
  246. {
  247. // http/2 over tls (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)
  248. protocols.Add(new SslApplicationProtocol(HTTPProtocolFactory.W3C_HTTP2));
  249. }
  250. protocols.Add(new SslApplicationProtocol(HTTPProtocolFactory.W3C_HTTP1));
  251. SslClientAuthenticationOptions options = new SslClientAuthenticationOptions();
  252. options.ApplicationProtocols = protocols;
  253. options.TargetHost = request.CurrentUri.Host;
  254. var task = sslStream.AuthenticateAsClientAsync(options, default(System.Threading.CancellationToken));
  255. task.Wait();
  256. try
  257. {
  258. negotiatedProtocol = System.Text.Encoding.UTF8.GetString(sslStream.NegotiatedApplicationProtocol.Protocol.Span);
  259. }
  260. catch (Exception ex)
  261. {
  262. HTTPManager.Logger.Exception(nameof(TCPConnector), "Accessing SslStream's NegotiatedApplicationProtocol throwed an exception, falling back using HTTP/1.1", ex, request.Context);
  263. negotiatedProtocol = HTTPProtocolFactory.W3C_HTTP1;
  264. }
  265. #else
  266. sslStream.AuthenticateAsClient(request.CurrentUri.Host);
  267. #endif
  268. }
  269. Stream = sslStream;
  270. #else
  271. Stream = Client.GetStream();
  272. #endif
  273. }
  274. #endregion
  275. request.Timing.Add(TimingEventNames.TLS_Negotiation, DateTime.Now - tlsNegotiationStartedAt);
  276. }
  277. }
  278. this.NegotiatedProtocol = negotiatedProtocol;
  279. }
  280. public void Close()
  281. {
  282. if (Client != null && !this.LeaveOpen)
  283. {
  284. try
  285. {
  286. if (Stream != null)
  287. Stream.Close();
  288. }
  289. catch { }
  290. finally
  291. {
  292. Stream = null;
  293. }
  294. try
  295. {
  296. if (TopmostStream != null)
  297. TopmostStream.Close();
  298. }
  299. catch { }
  300. finally
  301. {
  302. TopmostStream = null;
  303. }
  304. try
  305. {
  306. Client.Close();
  307. }
  308. catch { }
  309. finally
  310. {
  311. Client = null;
  312. }
  313. }
  314. }
  315. public void Dispose()
  316. {
  317. Close();
  318. }
  319. }
  320. }
  321. #endif