public static async Task <SslSock> SslStartClientAsync(this ConnSock baseSock, PalSslClientAuthenticationOptions sslOptions, CancellationToken cancel = default)
    {
        SslSock ret = new SslSock(baseSock);

        await ret.StartSslClientAsync(sslOptions, cancel);

        return(ret);
    }
Example #2
0
    protected sealed override async Task TcpAcceptedImplAsync(NetTcpListenerPort listener, ConnSock s)
    {
        await using (SslSock ssl = new SslSock(s))
        {
            await ssl.StartSslServerAsync(this.Options.SslServerAuthenticationOptions, s.GrandCancel);

            ssl.UpdateSslSessionInfo();

            await SslAcceptedImplAsync(listener, ssl);
        }
    }
Example #3
0
        static void Net_Test6_DualStack_Client()
        {
            string hostname = "www.google.com";

            using (var tcp = LocalNet.ConnectIPv4v6Dual(new TcpConnectParam(hostname, 443, connectTimeout: 5 * 1000)))
            {
                tcp.Info.GetValue <ILayerInfoIpEndPoint>().RemoteIPAddress !.AddressFamily.ToString()._Print();

                using (SslSock ssl = new SslSock(tcp))
                {
                    var sslClientOptions = new PalSslClientAuthenticationOptions()
                    {
                        TargetHost = hostname,
                        ValidateRemoteCertificateProc = (cert) => { return(true); },
                    };

                    ssl.StartSslClient(sslClientOptions);

                    var st = ssl.GetStream();

                    var w = new StreamWriter(st);
                    var r = new StreamReader(st);

                    w.WriteLine("GET / HTTP/1.0");
                    w.WriteLine($"HOST: {hostname}");
                    w.WriteLine();
                    w.WriteLine();
                    w.Flush();

                    while (true)
                    {
                        string?s = r.ReadLine();
                        if (s == null)
                        {
                            break;
                        }

                        Con.WriteLine(s);
                    }
                }
            }
        }
Example #4
0
        static void Net_Test2_Ssl_Client()
        {
            string hostname = "www.google.co.jp";

            using (ConnSock sock = LocalNet.Connect(new TcpConnectParam(hostname, 443)))
            {
                using (SslSock ssl = new SslSock(sock))
                {
                    //ssl.StartPCapRecorder(new PCapFileEmitter(new PCapFileEmitterOptions(new FilePath(@"c:\tmp\190610\test1.pcapng", flags: FileFlags.AutoCreateDirectory), false)));
                    var sslClientOptions = new PalSslClientAuthenticationOptions()
                    {
                        TargetHost = hostname,
                        ValidateRemoteCertificateProc = (cert) => { return(true); },
                    };

                    ssl.StartSslClient(sslClientOptions);

                    var st = ssl.GetStream();

                    var w = new StreamWriter(st);
                    var r = new StreamReader(st);

                    w.WriteLine("GET / HTTP/1.0");
                    w.WriteLine($"HOST: {hostname}");
                    w.WriteLine();
                    w.WriteLine();
                    w.Flush();

                    while (true)
                    {
                        string?s = r.ReadLine();
                        if (s == null)
                        {
                            break;
                        }

                        Con.WriteLine(s);
                    }
                }
            }
        }
Example #5
0
            protected override async Task SslAcceptedImplAsync(NetTcpListenerPort listener, SslSock sock)
            {
                using (var stream = sock.GetStream())
                    using (var r = new StreamReader(stream))
                        using (var w = new StreamWriter(stream))
                        {
                            while (true)
                            {
                                string?recv = await r.ReadLineAsync();

                                if (recv == null)
                                {
                                    return;
                                }

                                Con.WriteLine(recv);

                                await w.WriteLineAsync("[" + recv + "]\r\n");

                                await w.FlushAsync();
                            }
                        }
            }
Example #6
0
 protected abstract Task SslAcceptedImplAsync(NetTcpListenerPort listener, SslSock sock);
Example #7
0
    public async Task <WtcSocket> WideClientConnectAsync(string pcid, WideTunnelClientOptions clientOptions, bool noCache, CancellationToken cancel = default)
    {
        bool retryFlag = false;

L_RETRY:
        WtConnectParam connectParam = await WideClientConnectInnerAsync(pcid, clientOptions, noCache, cancel);

        $"WideClientConnect: pcid {pcid}: Redirecting to {connectParam.HostName}:{connectParam.Port} (CacheUsed = {connectParam.CacheUsed}) ..."._Debug();

        try
        {
            ConnSock tcpSock = await this.TcpIp.ConnectAsync(new TcpConnectParam(connectParam.HostName, connectParam.Port, AddressFamily.InterNetwork, connectTimeout : CoresConfig.WtcConfig.WpcTimeoutMsec, dnsTimeout : CoresConfig.WtcConfig.WpcTimeoutMsec), cancel);

            try
            {
                ConnSock targetSock = tcpSock;

                try
                {
                    PalSslClientAuthenticationOptions sslOptions = new PalSslClientAuthenticationOptions(connectParam.HostName, false, (cert) => this.CheckValidationCallback(this, cert.NativeCertificate, null, SslPolicyErrors.None));

                    SslSock sslSock = new SslSock(tcpSock);
                    try
                    {
                        await sslSock.StartSslClientAsync(sslOptions, cancel);

                        targetSock = sslSock;
                    }
                    catch
                    {
                        await sslSock._DisposeSafeAsync();

                        throw;
                    }

                    WtcSocket wtcSocket = new WtcSocket(targetSock, new WtcOptions(this, connectParam));

                    await wtcSocket.StartWtcAsync(cancel);

                    return(wtcSocket);
                }
                catch
                {
                    await targetSock._DisposeSafeAsync();

                    throw;
                }
            }
            catch
            {
                await tcpSock._DisposeSafeAsync();

                throw;
            }
        }
        catch
        {
            if (connectParam.CacheUsed && retryFlag == false)
            {
                retryFlag = true;

                // 接続キャッシュを使用して接続することに失敗した
                // 場合はキャッシュを消去して再試行する
                WideTunnel.ConnectParamCache.Delete(pcid);

                $"WideClientConnect: pcid {pcid}: Connect with Session Cache Failed. Retrying..."._Debug();
                goto L_RETRY;
            }

            throw;
        }
    }
    protected override async Task SslAcceptedImplAsync(NetTcpListenerPort listener, SslSock sock)
    {
        using (PipeStream st = sock.GetStream())
        {
            await sock.AttachHandle.SetStreamReceiveTimeoutAsync(this.Options.RecvTimeout);

            int magicNumber = await st.ReceiveSInt32Async();

            if (magicNumber != MagicNumber)
            {
                throw new ApplicationException($"Invalid magicNumber = 0x{magicNumber:X}");
            }

            int clientVersion = await st.ReceiveSInt32Async();

            var accessKeyData = await st.ReceiveAllAsync(256);

            if (accessKeyData._GetString_UTF8(untilNullByte: true)._IsSame(this.Options.AccessKey) == false)
            {
                throw new ApplicationException($"Invalid access key");
            }

            MemoryBuffer <byte> sendBuffer = new MemoryBuffer <byte>();
            sendBuffer.WriteSInt32(MagicNumber);
            sendBuffer.WriteSInt32(ServerVersion);
            await st.SendAsync(sendBuffer);

            SizedDataQueue <Memory <byte> > standardDataQueue = new SizedDataQueue <Memory <byte> >();
            try
            {
                while (true)
                {
                    if (standardDataQueue.CurrentTotalSize >= CoresConfig.DataVaultProtocolSettings.BufferingSizeThresholdPerServer || st.IsReadyToReceive(sizeof(int)) == false)
                    {
                        var list = standardDataQueue.GetList();
                        standardDataQueue.Clear();
                        await DataVaultDataReceivedInternalAsync(list);
                    }

                    DataVaultProtocolDataType type = (DataVaultProtocolDataType)await st.ReceiveSInt32Async();

                    switch (type)
                    {
                    case DataVaultProtocolDataType.StandardData:
                    {
                        int size = await st.ReceiveSInt32Async();

                        if (size > CoresConfig.DataVaultProtocolSettings.MaxDataSize)
                        {
                            throw new ApplicationException($"size > MaxDataSize. size = {size}");
                        }

                        Memory <byte> data = new byte[size];

                        await st.ReceiveAllAsync(data);

                        standardDataQueue.Add(data, data.Length);

                        break;
                    }

                    case DataVaultProtocolDataType.KeepAlive:
                        break;

                    default:
                        throw new ApplicationException("Invalid DataVaultProtocolDataType");
                    }
                }
            }
            finally
            {
                await DataVaultDataReceivedInternalAsync(standardDataQueue.GetList());
            }
        }
    }
Example #9
0
    public static async Task <WebSocket> ConnectAsync(string uri, WebSocketConnectOptions?options = null, CancellationToken cancel = default)
    {
        if (options == null)
        {
            options = new WebSocketConnectOptions();
        }

        Uri u = new Uri(uri);

        int  port   = 0;
        bool useSsl = false;

        if (u.Scheme._IsSamei("ws"))
        {
            port = Consts.Ports.Http;
        }
        else if (u.Scheme._IsSamei("wss"))
        {
            port   = Consts.Ports.Https;
            useSsl = true;
        }
        else
        {
            throw new ArgumentException($"uri \"{uri}\" is not a WebSocket address.");
        }

        if (u.IsDefaultPort == false)
        {
            port = u.Port;
        }

        ConnSock tcpSock = await LocalNet.ConnectIPv4v6DualAsync(new TcpConnectParam(u.Host, port, connectTimeout : options.WebSocketOptions.TimeoutOpen, dnsTimeout : options.WebSocketOptions.TimeoutOpen), cancel);

        try
        {
            ConnSock targetSock = tcpSock;

            try
            {
                if (useSsl)
                {
                    SslSock sslSock = new SslSock(tcpSock);
                    try
                    {
                        options.SslOptions.TargetHost = u.Host;

                        await sslSock.StartSslClientAsync(options.SslOptions, cancel);

                        targetSock = sslSock;
                    }
                    catch
                    {
                        sslSock._DisposeSafe();
                        throw;
                    }
                }

                WebSocket webSock = new WebSocket(targetSock, options.WebSocketOptions);

                await webSock.StartWebSocketClientAsync(uri, cancel);

                return(webSock);
            }
            catch
            {
                targetSock.Dispose();
                throw;
            }
        }
        catch
        {
            tcpSock._DisposeSafe();
            throw;
        }
    }