Пример #1
0
        static async Task AcceptClient(TcpClient client)
        {
            var clientId = 0;

            //ClientInfo clientInfo = null;
            try
            {
                var clientStream            = client.GetStream();
                var cancellationTokenSource = new CancellationTokenSource(15 * 1000);
                var requestText             = await ReceiveRequest(clientStream, client.ReceiveBufferSize, cancellationTokenSource.Token);

                var request = Request.Parse(requestText);

                //if (!_acceptedHosts.Any(ah => request.Host.Contains(ah)))
                //{
                //    client.Dispose();
                //    return;
                //}

                lock (_lock)
                {
                    _clientCount++;
                    clientId = _clientCount;
                }
                //_clients.TryAdd()

                switch (request.Method)
                {
                case "CONNECT":

                    using (var clientInfo = client.AsClientInfo(clientId))
                        using (var httpsClient = await GetClient(request.Host, request.Port, request.Version))
                            using (var fakeCert = _certificateService.CreateFakeCertificate(request.Host, rootCertSerialNumber))
                            {
                                await HandleConnectRequest(clientInfo, client.ReceiveBufferSize, request.Version, cancellationTokenSource.Token);

                                var threadId = Thread.CurrentThread.ManagedThreadId;
                                WriteLine($"Client '{clientInfo.Id}: {clientInfo.Remote}' connected on thread '{threadId}' for: '{request.HostAndPort}'");
                                //var fakeCertHash = string.Join(string.Empty, System.Security.Cryptography.SHA256.Create().ComputeHash(fakeCert.RawData).Select(b => b.ToString("x2")));
                                //if (fakeCertHash != "a28a5e7ebbfe5a2cd1040ba579f58d77988b7cbd320db27fe41b94b442ff1a47")
                                //{
                                //    throw new Exception("invalid cert...");
                                //}
                                await AuthenticateAsServer(clientInfo, fakeCert);
                                await HandleHttpsRequests(clientInfo, client.ReceiveBufferSize, httpsClient);
                            }
                    break;

                default:
                    throw new NotSupportedException("http not supported yet");
                }
            }
            catch (IOException ex)
            {
                WriteLine($"Client '{clientId}' disconnected");
                WriteLine(ex.Message);
                //clientInfo?.Dispose();
                lock (_lock)
                {
                    _clientCount--;
                }
            }
            catch (Exception ex)
            {
            }
        }