public async Task <ConnSock> ConnectAsyncInternal(SpeculativeConnectorBase connector, CancellationToken cancel = default) { try { cancel.ThrowIfCancellationRequested(); ConnSock tcp = await this.System.ConnectAsync(this.Param, cancel); if (PostWaitMsecs >= 1) { await connector.PostWaitEvent.WaitAsync(this.PostWaitMsecs, cancel); } return(tcp); } catch (Exception ex) { if (PostWaitMsecs == 0) { connector.PostWaitEvent.Set(); } connector.ExceptionList.Add(ex, ex is GetIpAddressFamilyMismatchException ? 1 : 100); throw; } }
// 1 つの SSL 接続試行を処理する非同期関数 async Task PerformOneAsync(SslCertCollectorItem e, CancellationToken cancel = default) { using (ConnSock sock = await TcpIp.ConnectAsync(new TcpConnectParam(IPAddress.Parse(e.IpAddress), e.Port, connectTimeout: 5000), cancel)) { using (SslSock ssl = await sock.SslStartClientAsync(new PalSslClientAuthenticationOptions(e.SniHostName, true))) { ILayerInfoSsl sslInfo = ssl.Info.Ssl; PalX509Certificate cert = sslInfo.RemoteCertificate !; Certificate cert2 = cert.PkiCertificate; e.CertIssuer = cert2.CertData.IssuerDN.ToString()._MakeAsciiOneLinePrintableStr(); e.CertSubject = cert2.CertData.SubjectDN.ToString()._MakeAsciiOneLinePrintableStr(); e.CertFqdnList = cert2.HostNameList.Select(x => x.HostName)._Combine(",")._MakeAsciiOneLinePrintableStr(); e.CertHashSha1 = cert2.DigestSHA1Str; e.CertNotAfter = cert2.CertData.NotAfter; e.CertNotBefore = cert2.CertData.NotBefore; // 無視リストに含まれないものだけを出力 if (Consts.Strings.AutoEnrollCertificateSubjectInStrList.Where(x => e.CertIssuer._InStr(x, true)).Any() == false) { this.ResultList.Add(e); } $"OK: {e.SniHostName}:{e.Port} => {e._ObjectToJson(compact: true)}"._Print(); } } }
static void Net_Test3_2_PlainTcp_Server_AcceptQueue() { using (var listener = LocalNet.CreateListener(new TcpListenParam(null, null, 9821))) { Task acceptTask = TaskUtil.StartAsyncTaskAsync(async() => { // Accept ループタスク while (true) { ConnSock sock = await listener.AcceptNextSocketFromQueueUtilAsync(); TaskUtil.StartAsyncTaskAsync(async(obj) => { using (ConnSock s = (ConnSock)obj !) { var stream = s.GetStream(); StreamWriter w = new StreamWriter(stream); while (true) { w.WriteLine(DateTimeOffset.Now._ToDtStr(true)); await w.FlushAsync(); await Task.Delay(100); } } }, sock)._LaissezFaire(); } }); Con.ReadLine(">"); } }
static void Net_Test1_PlainTcp_Client() { for (int i = 0; i < 1; i++) { ConnSock sock = LocalNet.Connect(new TcpConnectParam("dnobori.cs.tsukuba.ac.jp", 80)); sock.StartPCapRecorder(new PCapFileEmitter(new PCapFileEmitterOptions(new FilePath(@"c:\tmp\190610\test1.pcapng", flags: FileFlags.AutoCreateDirectory), true))); { var st = sock.GetStream(); //sock.DisposeSafe(); var w = new StreamWriter(st); var r = new StreamReader(st); w.WriteLine("GET /ja/ HTTP/1.0"); w.WriteLine("HOST: dnobori.cs.tsukuba.ac.jp"); w.WriteLine(); w.Flush(); while (true) { string?s = r.ReadLine(); if (s == null) { break; } Con.WriteLine(s); } st.Dispose(); } } }
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); }
public WtcSocket(ConnSock lowerSock, WtcOptions options) : base(new NetWtcProtocolStack(lowerSock.UpperPoint, null, options)) { try { this.GatePhysicalEndPoint = new IPEndPoint(IPAddress.Parse(lowerSock.EndPointInfo.RemoteIP !), lowerSock.EndPointInfo.RemotePort); } catch (Exception ex) { this._DisposeSafe(ex); throw; } }
public KestrelStackConnection(ConnSock sock, PipeScheduler scheduler) { this.Sock = sock; this.Scheduler = scheduler; LocalAddress = sock.Info.Ip.LocalIPAddress; LocalPort = sock.Info.Tcp.LocalPort; RemoteAddress = sock.Info.Ip.RemoteIPAddress; RemotePort = sock.Info.Tcp.RemotePort; this.ConnectionClosed = this.Sock.GrandCancel; }
public async ValueTask <ConnectionContext> AcceptAsync(CancellationToken cancellationToken = default) { if (this.Listener == null) { throw new ApplicationException("Listener is not bound yet."); } ConnSock sock = await this.Listener.AcceptNextSocketFromQueueUtilAsync(cancellationToken); var connection = new KestrelStackConnection(sock); connection.Start(); return(connection); }
// 1 個の HTTP テストを実行する async Task <bool> PerformSingleHttpTestAsync(InternetCheckerHttpTestItem http, CancellationToken cancel = default) { await using ConnSock sock = await this.TcpIp.ConnectAsync(new TcpConnectParam (http.Fqdn, http.Port, http.Family, connectTimeout : Options.HttpTimeout, dnsTimeout : Options.HttpTimeout), cancel); await using PipeStream stream = sock.GetStream(); stream.ReadTimeout = stream.WriteTimeout = Options.HttpTimeout; await using StringWriter w = new StringWriter(); // リクエスト w.WriteLine($"GET {http.Path} HTTP/1.1"); w.WriteLine($"HOST: {http.Fqdn}"); w.WriteLine(); byte[] sendData = w.ToString()._GetBytes_UTF8(); await stream.SendAsync(sendData, cancel); // レスポンス MemoryBuffer <byte> recvBuffer = new MemoryBuffer <byte>(); bool ret = false; while (recvBuffer.Length <= 65536) { ReadOnlyMemory <byte> recvData = await stream.ReceiveAsync(1024, cancel); if (recvData.IsEmpty) { break; } recvBuffer.Write(recvData); // 現時点で指定された文字列が受信されているかどうか確認する string utf8 = recvBuffer.Memory._GetString_UTF8(); if (utf8._InStr(http.ExpectedResultString, ignoreCase: true)) { // 受信されていた ret = true; break; } } return(ret); }
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); } } } }
async Task ListenerAcceptNewSocketCallback(NetTcpListenerPort listener, ConnSock newSock) { using (var connection = new KestrelStackConnection(newSock, this.PipeScheduler)) { // Note: // In ASP.NET Core 2.2 or higher, Dispatcher.OnConnection() will return Task. // Otherwise, Dispatcher.OnConnection() will return void. // Then we need to use the reflection to call the OnConnection() method indirectly. Task?middlewareTask = Dispatcher._PrivateInvoke("OnConnection", connection) as Task; // Wait for transport to end await connection.StartAsync(); // Wait for middleware to end if (middlewareTask != null) { await middlewareTask; } connection._DisposeSafe(); } }
static async Task Net_Test13_WebSocketClientAsync() { using (ConnSock sock = LocalNet.Connect(new TcpConnectParam("echo.websocket.org", 80))) { using (WebSocket ws = new WebSocket(sock)) { await ws.StartWebSocketClientAsync("wss://echo.websocket.org"); using (var stream = ws.GetStream()) using (var r = new StreamReader(stream)) using (var w = new StreamWriter(stream)) { w.AutoFlush = true; for (int i = 1; i < 20; i++) { string src = Str.MakeCharArray((char)('a' + (i % 25)), i * 100); Con.WriteLine(src.Length); //await w.WriteLineAsync(src); await stream.WriteAsync((src + "\r\n")._GetBytes_Ascii()); string?dst = await r.ReadLineAsync(); //Con.WriteLine(dst); Con.WriteLine(i); Debug.Assert(src == dst); } } } } }
public static SslSock SslStartClient(this ConnSock baseSock, PalSslClientAuthenticationOptions sslOptions, CancellationToken cancel = default) => SslStartClientAsync(baseSock, sslOptions, cancel)._GetResult();
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; } }
public SslSock(ConnSock lowerSock) : base(new NetSslProtocolStack(lowerSock.UpperPoint, null, null)) { }
async Task ListenerCallbackAsync(NetTcpListenerPort listener, ConnSock newSock) { await TcpAcceptedImplAsync(listener, newSock); }
protected abstract Task TcpAcceptedImplAsync(NetTcpListenerPort listener, ConnSock sock);
protected sealed override async Task TcpAcceptedImplAsync(NetTcpListenerPort listener, ConnSock s) { using (SslSock ssl = new SslSock(s)) { await ssl.StartSslServerAsync(this.Options.SslServerAuthenticationOptions, s.GrandCancel); ssl.UpdateSslSessionInfo(); await SslAcceptedImplAsync(listener, ssl); } }
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; } }
public WebSocket(ConnSock lowerSock, WebSocketOptions?options = null) : base(new NetWebSocketProtocolStack(lowerSock.UpperPoint, null, options._FilledOrDefault(new WebSocketOptions()))) { }
async Task <Result> ClientSingleConnectionAsync(Direction dir, AsyncManualResetEvent fireMeWhenReady, CancellationToken cancel) { Result ret = new Result(); using (NetPalTcpProtocolStub tcp = new NetPalTcpProtocolStub(cancel: cancel)) { await tcp.ConnectAsync(ServerIP, ServerPort, cancel, ConnectTimeout); using (ConnSock sock = new ConnSock(tcp)) { NetAppStub app = sock.GetNetAppProtocolStub(); AttachHandle attachHandle = app.AttachHandle; PipeStream st = app.GetStream(); if (dir == Direction.Recv) { app.AttachHandle.SetStreamReceiveTimeout(RecvTimeout); } try { var hello = await st.ReceiveAllAsync(16); if (hello.Span.ToArray()._GetString_Ascii().StartsWith("TrafficServer\r\n") == false) { throw new ApplicationException("Target server is not a Traffic Server."); } //throw new ApplicationException("aaaa" + dir.ToString()); fireMeWhenReady.Set(); cancel.ThrowIfCancellationRequested(); await TaskUtil.WaitObjectsAsync( manualEvents : ClientStartEvent._SingleArray(), cancels : cancel._SingleArray() ); long tickStart = FastTick64.Now; long tickEnd = tickStart + this.TimeSpan; var sendData = new MemoryBuffer <byte>(); sendData.WriteBool8(dir == Direction.Recv); sendData.WriteUInt64(SessionId); sendData.WriteSInt64(TimeSpan); await st.SendAsync(sendData); if (dir == Direction.Recv) { RefInt totalRecvSize = new RefInt(); while (true) { long now = FastTick64.Now; if (now >= tickEnd) { break; } await TaskUtil.WaitObjectsAsync( tasks : st.FastReceiveAsync(totalRecvSize : totalRecvSize)._SingleArray(), timeout : (int)(tickEnd - now), exceptions : ExceptionWhen.TaskException | ExceptionWhen.CancelException); ret.NumBytesDownload += totalRecvSize; } } else { attachHandle.SetStreamReceiveTimeout(Timeout.Infinite); while (true) { long now = FastTick64.Now; if (now >= tickEnd) { break; } /*await WebSocketHelper.WaitObjectsAsync( * tasks: st.FastSendAsync(SendData, flush: true).ToSingleArray(), * timeout: (int)(tick_end - now), * exceptions: ExceptionWhen.TaskException | ExceptionWhen.CancelException);*/ await st.FastSendAsync(SendData, flush : true); } Task recvResult = Task.Run(async() => { var recvMemory = await st.ReceiveAllAsync(8); MemoryBuffer <byte> recvMemoryBuf = recvMemory; ret.NumBytesUpload = recvMemoryBuf.ReadSInt64(); st.Disconnect(); }); Task sendSurprise = Task.Run(async() => { byte[] surprise = new byte[260]; surprise.AsSpan().Fill((byte)'!'); while (true) { await st.SendAsync(surprise); await TaskUtil.WaitObjectsAsync( manualEvents: sock.Pipe.OnDisconnectedEvent._SingleArray(), timeout: 200); } }); await WhenAll.Await(false, recvResult, sendSurprise); await recvResult; } st.Disconnect(); return(ret); } catch (Exception ex) { ExceptionQueue !.Add(ex); throw; } } } }