From c042007803f3e4291a75d29ead84a2230f89b205 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 18 Nov 2022 14:18:56 -0600 Subject: add Enabled option --- src/slskd/Core/Options.cs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 3a61e376..368b5ca0 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -389,14 +389,23 @@ namespace slskd public class RelayOptions : IValidatableObject { /// - /// Gets the application operation mode. + /// Gets a value indicating whether the relay is enabled. + /// + [Argument('r', "relay")] + [EnvironmentVariable("RELAY")] + [Description("enable relay")] + [RequiresRestart] + public bool Enabled { get; init; } = false; + + /// + /// Gets the relay operation mode. /// [Argument('m', "relay-operation-mode")] [EnvironmentVariable("RELAY_OPERATION_MODE")] [Description("relay operation mode; controller, agent")] [RequiresRestart] [Enum(typeof(OperationMode))] - public string Mode { get; init; } = slskd.Relay.OperationMode.Controller.ToString().ToLowerInvariant(); + public string Mode { get; init; } = OperationMode.Controller.ToString().ToLowerInvariant(); /// /// Gets the controller configuration. @@ -414,7 +423,7 @@ namespace slskd var results = new List(); var modeResults = new List(); - if (mode == slskd.Relay.OperationMode.Agent && !Validator.TryValidateObject(Controller, new ValidationContext(Controller), modeResults, validateAllProperties: true)) + if (mode == OperationMode.Agent && !Validator.TryValidateObject(Controller, new ValidationContext(Controller), modeResults, validateAllProperties: true)) { results.Add(new CompositeValidationResult("Controller", modeResults)); } -- cgit v1.2.3 From cb22565ef6a30f00d3ddac0f92ab69abe84bc6d0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 18 Nov 2022 14:19:10 -0600 Subject: move RelayClientState --- src/slskd/Relay/RelayClientState.cs | 27 --------------------------- src/slskd/Relay/Types/RelayClientState.cs | 27 +++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 27 deletions(-) delete mode 100644 src/slskd/Relay/RelayClientState.cs create mode 100644 src/slskd/Relay/Types/RelayClientState.cs (limited to 'src') diff --git a/src/slskd/Relay/RelayClientState.cs b/src/slskd/Relay/RelayClientState.cs deleted file mode 100644 index def25411..00000000 --- a/src/slskd/Relay/RelayClientState.cs +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Relay -{ - public enum RelayClientState - { - Disconnected, - Connected, - Connecting, - Reconnecting, - } -} diff --git a/src/slskd/Relay/Types/RelayClientState.cs b/src/slskd/Relay/Types/RelayClientState.cs new file mode 100644 index 00000000..def25411 --- /dev/null +++ b/src/slskd/Relay/Types/RelayClientState.cs @@ -0,0 +1,27 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Relay +{ + public enum RelayClientState + { + Disconnected, + Connected, + Connecting, + Reconnecting, + } +} -- cgit v1.2.3 From 8c07bd366bcb0b897f1ae8ad9ae711d083114dc6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 18 Nov 2022 14:22:52 -0600 Subject: only configure relay service if enabled --- src/slskd/Relay/RelayService.cs | 47 ++++++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs index 2e986c84..79f9f143 100644 --- a/src/slskd/Relay/RelayService.cs +++ b/src/slskd/Relay/RelayService.cs @@ -716,32 +716,35 @@ namespace slskd.Relay return; } - var mode = options.Relay.Mode.ToEnum(); - - if (mode == OperationMode.Controller) - { - State.SetValue(state => state with - { - Mode = mode, - Agents = RegisteredAgents, - }); - } - else + if (options.Relay.Enabled) { - // the controller changed. disconnect and throw away the client and create a new one - Client = new RelayClient(Shares, OptionsMonitor, HttpClientFactory); - Client.StateMonitor.OnChange(clientState - => State.SetValue(state => state with { Controller = state.Controller with { State = clientState.Current } })); + var mode = options.Relay.Mode.ToEnum(); - State.SetValue(state => state with + if (mode == OperationMode.Controller) { - Mode = mode, - Controller = new RelayControllerState() + State.SetValue(state => state with + { + Mode = mode, + Agents = RegisteredAgents, + }); + } + else + { + // the controller changed. disconnect and throw away the client and create a new one + Client = new RelayClient(Shares, OptionsMonitor, HttpClientFactory); + Client.StateMonitor.OnChange(clientState + => State.SetValue(state => state with { Controller = state.Controller with { State = clientState.Current } })); + + State.SetValue(state => state with { - Address = options.Relay.Controller.Address, - State = Client.StateMonitor.CurrentValue, - }, - }); + Mode = mode, + Controller = new RelayControllerState() + { + Address = options.Relay.Controller.Address, + State = Client.StateMonitor.CurrentValue, + }, + }); + } } LastOptionsHash = optionsHash; -- cgit v1.2.3 From 5d83002177a489dbff8ec00fa9f9f24c96043289 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 18 Nov 2022 14:30:53 -0600 Subject: only connect agent if relay is enabled --- src/slskd/Application.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 531355a5..3c0c1e7f 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -398,14 +398,14 @@ namespace slskd { Log.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); } - else if (OptionsAtStartup.Relay.Mode.ToEnum() == OperationMode.Agent) + else if (OptionsAtStartup.Relay.Enabled && OptionsAtStartup.Relay.Mode.ToEnum() == OperationMode.Agent) { Log.Information("Running in Agent relay mode; not connecting to the Soulseek server."); await Relay.Client.StartAsync(cancellationToken); } else { - if (OptionsAtStartup.Relay.Mode.ToEnum() == OperationMode.Debug) + if (OptionsAtStartup.Relay.Enabled && OptionsAtStartup.Relay.Mode.ToEnum() == OperationMode.Debug) { Log.Warning("Running in Debug relay mode; connecting to controller"); _ = Relay.Client.StartAsync(cancellationToken); -- cgit v1.2.3 From 44d083fb4d78f4ecd9b1e880b8a2b20783f48070 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 18 Nov 2022 15:03:29 -0600 Subject: prevent actions when disabled --- src/slskd/Relay/API/Controllers/RelayController.cs | 26 +++++++++++++++- src/slskd/Relay/API/Hubs/RelayHub.cs | 36 +++++++++++++++------- 2 files changed, 50 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index 952507ad..cd688306 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -39,18 +39,27 @@ namespace slskd.Relay public class RelayController : ControllerBase { public RelayController( - IRelayService relayService) + IRelayService relayService, + OptionsAtStartup optionsAtStartup) { Relay = relayService; + OptionsAtStartup = optionsAtStartup; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IRelayService Relay { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private OperationMode OperationMode => OptionsAtStartup.Relay.Mode.ToEnum(); [HttpPut("")] [Authorize(Policy = AuthPolicy.Any)] public async Task Connect() { + if (!OptionsAtStartup.Relay.Enabled || !new[] { OperationMode.Agent, OperationMode.Debug }.Contains(OperationMode)) + { + return Forbid(); + } + await Relay.Client.StartAsync(); return Ok(); } @@ -59,6 +68,11 @@ namespace slskd.Relay [Authorize(Policy = AuthPolicy.Any)] public async Task Disconnect() { + if (!OptionsAtStartup.Relay.Enabled || !new[] { OperationMode.Agent, OperationMode.Debug }.Contains(OperationMode)) + { + return Forbid(); + } + await Relay.Client.StopAsync(); return NoContent(); } @@ -75,6 +89,11 @@ namespace slskd.Relay [Authorize(Policy = AuthPolicy.Any)] public async Task UploadFile(string token) { + if (!OptionsAtStartup.Relay.Enabled || !new[] { OperationMode.Controller, OperationMode.Debug }.Contains(OperationMode)) + { + return Forbid(); + } + if (!Guid.TryParse(token, out var guid)) { return BadRequest("Token is not in a valid format"); @@ -159,6 +178,11 @@ namespace slskd.Relay [Authorize(Policy = AuthPolicy.Any)] public async Task UploadShares(string token) { + if (!OptionsAtStartup.Relay.Enabled || !new[] { OperationMode.Controller, OperationMode.Debug }.Contains(OperationMode)) + { + return Forbid(); + } + if (!Guid.TryParse(token, out var guid)) { return BadRequest("Token is not a valid Guid"); diff --git a/src/slskd/Relay/API/Hubs/RelayHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs index ab14e064..99cd3839 100644 --- a/src/slskd/Relay/API/Hubs/RelayHub.cs +++ b/src/slskd/Relay/API/Hubs/RelayHub.cs @@ -18,6 +18,8 @@ namespace slskd.Relay { using System; + using System.Linq; + using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http.Features; @@ -63,14 +65,20 @@ namespace slskd.Relay /// Initializes a new instance of the class. /// /// + /// public RelayHub( - IRelayService relayService) + IRelayService relayService, + OptionsAtStartup optionsAtStartup) { Relay = relayService; + OptionsAtStartup = optionsAtStartup; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IRelayService Relay { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private OperationMode OperationMode => OptionsAtStartup.Relay.Mode.ToEnum(); + private IPAddress RemoteIpAddress => Context.Features.Get().RemoteIpAddress; /// /// Executed when a new connection is established. @@ -78,9 +86,15 @@ namespace slskd.Relay /// public override async Task OnConnectedAsync() { + if (!OptionsAtStartup.Relay.Enabled || !new[] { OperationMode.Controller, OperationMode.Debug }.Contains(OperationMode)) + { + Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, RemoteIpAddress); + Context.Abort(); + } + var token = Relay.GenerateAuthenticationChallengeToken(Context.ConnectionId); - Log.Information("Agent connection {Id} established. Sending authentication challenge {Token}...", Context.ConnectionId, token); + Log.Information("Agent connection {Id} from {IP} established. Sending authentication challenge {Token}...", Context.ConnectionId, RemoteIpAddress, token); await Clients.Caller.Challenge(token); } @@ -93,7 +107,7 @@ namespace slskd.Relay { if (Relay.TryDeregisterAgent(Context.ConnectionId, out var record)) { - Log.Warning("Agent {Agent} (connection {Id}) disconnected", record.Agent.Name, Context.ConnectionId); + Log.Warning("Agent {Agent} (connection {Id}) from {IP} disconnected", record.Agent.Name, Context.ConnectionId, RemoteIpAddress); Relay.TryDeregisterAgent(record.Agent.Name, out _); } @@ -110,7 +124,7 @@ namespace slskd.Relay { if (!Relay.TryValidateAuthenticationCredential(Context.ConnectionId, agent, challengeResponse)) { - Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); + Log.Information("Agent connection {Id} from {IP} authentication failed", Context.ConnectionId, RemoteIpAddress); Relay.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! throw new UnauthorizedAccessException(); } @@ -118,7 +132,7 @@ namespace slskd.Relay var remoteIp = Context.Features.Get().RemoteIpAddress.ToString(); var record = new Agent { Name = agent, IPAddress = remoteIp }; - Log.Information("Agent connection {Id} ({IP}) authenticated as agent {Agent}", Context.ConnectionId, remoteIp, agent); + Log.Information("Agent connection {Id} from {IP} authenticated as agent {Agent}", Context.ConnectionId, remoteIp, agent); Relay.RegisterAgent(Context.ConnectionId, record); } @@ -132,12 +146,12 @@ namespace slskd.Relay if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { // this can happen if the agent attempts to upload before logging in - Log.Information("Agent connection {Id} requested a share upload token, but is not registered.", Context.ConnectionId); + Log.Information("Agent connection {Id} from {IP} requested a share upload token, but is not registered.", Context.ConnectionId, RemoteIpAddress); throw new UnauthorizedAccessException(); } var token = Relay.GenerateShareUploadToken(record.Agent.Name); - Log.Information("Agent {Agent} (connection {Id}) requested share upload token {Token}", record.Agent.Name, record.ConnectionId, token); + Log.Information("Agent {Agent} (connection {Id}) from {IP} requested share upload token {Token}", record.Agent.Name, record.ConnectionId, RemoteIpAddress, token); return token; } @@ -151,11 +165,11 @@ namespace slskd.Relay { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { - Log.Warning("Agent connection {Id} attempted to report a failed upload, but is not registered.", Context.ConnectionId); + Log.Warning("Agent connection {Id} from {IP} attempted to report a failed upload, but is not registered.", Context.ConnectionId, RemoteIpAddress); throw new UnauthorizedAccessException(); } - Log.Warning("Agent {Agent} (connection {ConnectionId}) reported upload failure for {Id}: {Message}", id, exception.Message); + Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", id, exception.Message, RemoteIpAddress); Relay.NotifyFileStreamException(id, exception); } @@ -171,11 +185,11 @@ namespace slskd.Relay { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { - Log.Warning("Agent connection {Id} attempted to return file information, but is not registered.", Context.ConnectionId); + Log.Warning("Agent connection {Id} from {IP} attempted to return file information, but is not registered.", Context.ConnectionId, RemoteIpAddress); throw new UnauthorizedAccessException(); } - Log.Information("Agent {Agent} (connection {ConnectionId}) returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, id, exists, length); + Log.Information("Agent {Agent} (connection {ConnectionId}) from {IP} returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, RemoteIpAddress, id, exists, length); Relay.HandleFileInfoResponse(record.Agent.Name, id, (exists, length)); } -- cgit v1.2.3 From 8c67a655322fc787ef8677ebbded1596dab36b4d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 18 Nov 2022 15:31:35 -0600 Subject: log controller mode --- src/slskd/Application.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 3c0c1e7f..0c7815e5 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -410,6 +410,10 @@ namespace slskd Log.Warning("Running in Debug relay mode; connecting to controller"); _ = Relay.Client.StartAsync(cancellationToken); } + else + { + Log.Information("Running in Controller relay mode. Listening for incoming Agent connections."); + } await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); } -- cgit v1.2.3