using System.Net; using System.Net.Security; using System.Net.WebSockets; using System.Security.Cryptography.X509Certificates; using Microsoft.AspNetCore.Server.Kestrel.Https; using PCC2.AssemblyInject.Interfaces; using PCC2.Backend.Events; using PCC2.EventBus; using PCC2.Networking.KestrelSsl; namespace PCC2.Backend; internal class Pcc2Listener(IAsyncEventBus eventBus, ILogger logger, ILogger kwsLogger) : IAssemblyInjectASyncInitStarStop { private X509Certificate2? ServerCerSelect(string? sni) { throw new NotImplementedException(); } private bool ClientCerValidate(X509Certificate2 clientCert, X509Chain? arg2, SslPolicyErrors arg3) { throw new NotImplementedException(); } private Task ConnectHandler(X509Certificate2? clientCert, WebSocket ws) { throw new NotImplementedException(); } // ============================================================== private KestrelSslListener? _listener; private ListenerStatus _status; private async Task SetAndPublishListenStatus(ListenerStatus status) { _status = status; await eventBus.PublishAsync(new ListenerStatusTellEvent(status)); } public Task InitAsync() { eventBus.Subscript(async delegate { await StopAsync(); await StartAsync(); }); eventBus.Subscript(async delegate { await eventBus.PublishAsync(new ListenerStatusTellEvent(_status)); }); return Task.CompletedTask; } public async Task StartAsync() { if (_listener != null) return; var ep = LoadListenEndPointSetting(); if (ep == null) { await SetAndPublishListenStatus(ListenerStatus.NotStart); return; } await SetAndPublishListenStatus(ListenerStatus.Starting); _listener = new KestrelSslListener(ep, ServerCerSelect, ClientCerValidate, ConnectHandler, ClientCertificateMode.RequireCertificate, kwsLogger); try { await _listener.StartAsync(); await SetAndPublishListenStatus(ListenerStatus.Started); } catch (Exception ex) { logger.LogError(ex, nameof(StartAsync)); await SetAndPublishListenStatus(ListenerStatus.StartFail); } } public async Task StopAsync() { if (_listener == null) return; await SetAndPublishListenStatus(ListenerStatus.Stopping); try { await _listener.StopAsync(); await SetAndPublishListenStatus(ListenerStatus.Stopped); } catch (Exception ex) { logger.LogError(ex, nameof(StopAsync)); await SetAndPublishListenStatus(ListenerStatus.StopFail); } _listener = null; } private IPEndPoint? LoadListenEndPointSetting() { var settings = GetSettings(); var ip = settings.ListenAddress; var port = settings.ListenPort; if (ip == null || port == null || IPAddress.TryParse(ip, out var address) == false) return null; return new IPEndPoint(address, port.Value); } }