TCPConnector.cs 13 KB

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