| | | 1 | | using System.IO.Pipes; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | |
| | | 4 | | namespace NLightning.Daemon.Services.Ipc; |
| | | 5 | | |
| | | 6 | | using Contracts.Utilities; |
| | | 7 | | using Daemon.Ipc.Interfaces; |
| | | 8 | | using Domain.Client.Constants; |
| | | 9 | | using Domain.Client.Interfaces; |
| | | 10 | | using Factories; |
| | | 11 | | using Transport.Ipc; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Hosted service that listens to on a named pipe and processes IPC requests using injected components. |
| | | 15 | | /// </summary> |
| | | 16 | | internal sealed class NamedPipeIpcService : INamedPipeIpcService |
| | | 17 | | { |
| | | 18 | | private readonly ILogger<NamedPipeIpcService> _logger; |
| | | 19 | | private readonly IIpcAuthenticator _authenticator; |
| | | 20 | | private readonly IIpcFraming _framing; |
| | | 21 | | private readonly IIpcRequestRouter _router; |
| | | 22 | | private readonly string _pipeName; |
| | | 23 | | private readonly string _cookiePath; |
| | | 24 | | |
| | | 25 | | private CancellationTokenSource? _cts; |
| | | 26 | | private Task? _listenerTask; |
| | | 27 | | |
| | 0 | 28 | | public NamedPipeIpcService(IIpcAuthenticator authenticator, string configPath, IIpcFraming framing, |
| | 0 | 29 | | ILogger<NamedPipeIpcService> logger, IIpcRequestRouter router) |
| | | 30 | | { |
| | 0 | 31 | | _logger = logger; |
| | 0 | 32 | | _authenticator = authenticator; |
| | 0 | 33 | | _framing = framing; |
| | 0 | 34 | | _router = router; |
| | | 35 | | |
| | 0 | 36 | | _pipeName = NodeUtils.GetNamedPipeFilePath(configPath); |
| | 0 | 37 | | _cookiePath = NodeUtils.GetCookieFilePath(configPath); |
| | 0 | 38 | | } |
| | | 39 | | |
| | | 40 | | public Task StartAsync(CancellationToken cancellationToken) |
| | | 41 | | { |
| | 0 | 42 | | _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | | 43 | | |
| | 0 | 44 | | EnsureCookieExists(); |
| | | 45 | | |
| | 0 | 46 | | _listenerTask = ListenToIpcClientAsync(cancellationToken); |
| | | 47 | | |
| | 0 | 48 | | return Task.CompletedTask; |
| | | 49 | | } |
| | | 50 | | |
| | | 51 | | public async Task StopAsync() |
| | | 52 | | { |
| | 0 | 53 | | if (_cts is null) |
| | 0 | 54 | | throw new InvalidOperationException("Service is not running"); |
| | | 55 | | |
| | 0 | 56 | | await _cts.CancelAsync(); |
| | | 57 | | |
| | 0 | 58 | | if (_listenerTask is not null) |
| | | 59 | | { |
| | | 60 | | try |
| | | 61 | | { |
| | 0 | 62 | | await _listenerTask; |
| | 0 | 63 | | } |
| | 0 | 64 | | catch (OperationCanceledException) |
| | | 65 | | { |
| | | 66 | | // Expected during cancellation |
| | 0 | 67 | | } |
| | | 68 | | } |
| | 0 | 69 | | } |
| | | 70 | | |
| | | 71 | | private async Task ListenToIpcClientAsync(CancellationToken cancellationToken) |
| | | 72 | | { |
| | | 73 | | try |
| | | 74 | | { |
| | 0 | 75 | | while (!cancellationToken.IsCancellationRequested) |
| | | 76 | | { |
| | | 77 | | try |
| | | 78 | | { |
| | 0 | 79 | | var server = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 10, |
| | 0 | 80 | | PipeTransmissionMode.Byte, |
| | 0 | 81 | | PipeOptions.Asynchronous); |
| | 0 | 82 | | await server.WaitForConnectionAsync(cancellationToken); |
| | | 83 | | |
| | 0 | 84 | | _ = Task.Run(() => HandleClientAsync(server, cancellationToken), cancellationToken); |
| | 0 | 85 | | } |
| | 0 | 86 | | catch (Exception ex) when (!cancellationToken.IsCancellationRequested) |
| | | 87 | | { |
| | 0 | 88 | | _logger.LogError(ex, "IPC server accept loop error"); |
| | 0 | 89 | | await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); |
| | | 90 | | } |
| | | 91 | | } |
| | 0 | 92 | | } |
| | 0 | 93 | | catch (OperationCanceledException) |
| | | 94 | | { |
| | 0 | 95 | | _logger.LogInformation("IPC server loop cancelled"); |
| | 0 | 96 | | } |
| | 0 | 97 | | catch (Exception ex) |
| | | 98 | | { |
| | 0 | 99 | | _logger.LogError(ex, "Fatal error in IPC server loop"); |
| | 0 | 100 | | } |
| | 0 | 101 | | } |
| | | 102 | | |
| | | 103 | | private async Task HandleClientAsync(NamedPipeServerStream stream, CancellationToken ct) |
| | | 104 | | { |
| | | 105 | | try |
| | | 106 | | { |
| | 0 | 107 | | var request = await _framing.ReadAsync(stream, ct); |
| | | 108 | | |
| | 0 | 109 | | if (!await _authenticator.ValidateAsync(request.AuthToken, ct)) |
| | | 110 | | { |
| | 0 | 111 | | var err = IpcErrorFactory.CreateErrorEnvelope(request, ErrorCodes.AuthenticationFailure, |
| | 0 | 112 | | "Authentication failed."); |
| | 0 | 113 | | await _framing.WriteAsync(stream, err, ct); |
| | 0 | 114 | | return; |
| | | 115 | | } |
| | | 116 | | |
| | 0 | 117 | | var response = await _router.RouteAsync(request, ct); |
| | 0 | 118 | | await _framing.WriteAsync(stream, response, ct); |
| | 0 | 119 | | } |
| | 0 | 120 | | catch (Exception ex) |
| | | 121 | | { |
| | 0 | 122 | | _logger.LogError(ex, "IPC client handling failed"); |
| | | 123 | | try |
| | | 124 | | { |
| | | 125 | | // Try to write a generic error if we still can read an envelope |
| | 0 | 126 | | var env = new IpcEnvelope { Version = 1, CorrelationId = Guid.NewGuid(), Kind = IpcEnvelopeKind.Error }; |
| | 0 | 127 | | var err = IpcErrorFactory.CreateErrorEnvelope(env, ErrorCodes.ServerError, ex.Message); |
| | 0 | 128 | | await _framing.WriteAsync(stream, err, ct); |
| | 0 | 129 | | } |
| | 0 | 130 | | catch |
| | | 131 | | { |
| | | 132 | | // ignore |
| | 0 | 133 | | } |
| | | 134 | | } |
| | | 135 | | finally |
| | | 136 | | { |
| | 0 | 137 | | try { await stream.DisposeAsync(); } |
| | 0 | 138 | | catch |
| | | 139 | | { |
| | | 140 | | //ignore |
| | 0 | 141 | | } |
| | | 142 | | } |
| | 0 | 143 | | } |
| | | 144 | | |
| | | 145 | | private void EnsureCookieExists() |
| | | 146 | | { |
| | | 147 | | try |
| | | 148 | | { |
| | 0 | 149 | | var dir = Path.GetDirectoryName(_cookiePath); |
| | 0 | 150 | | if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) |
| | 0 | 151 | | Directory.CreateDirectory(dir); |
| | | 152 | | |
| | 0 | 153 | | if (File.Exists(_cookiePath)) |
| | 0 | 154 | | return; |
| | | 155 | | |
| | 0 | 156 | | var token = Convert.ToBase64String(Guid.NewGuid().ToByteArray()); |
| | 0 | 157 | | File.WriteAllText(_cookiePath, token); |
| | 0 | 158 | | } |
| | 0 | 159 | | catch (Exception ex) |
| | | 160 | | { |
| | 0 | 161 | | _logger.LogError(ex, "Failed to ensure IPC cookie exists at {Path}", _cookiePath); |
| | 0 | 162 | | throw; |
| | | 163 | | } |
| | 0 | 164 | | } |
| | | 165 | | } |