diff --git a/src/MikrotikInstaller.App/ViewModels/Steps/LanStepViewModel.cs b/src/MikrotikInstaller.App/ViewModels/Steps/LanStepViewModel.cs index 4c14f6a..bb35720 100644 --- a/src/MikrotikInstaller.App/ViewModels/Steps/LanStepViewModel.cs +++ b/src/MikrotikInstaller.App/ViewModels/Steps/LanStepViewModel.cs @@ -19,6 +19,7 @@ public partial class LanStepViewModel : WizardStepViewModelBase description: "Wähle, welche Anschlüsse zu deinem Heimnetzwerk gehören sollen, und lege den IP-Adressbereich fest. Die Vorgaben passen für die meisten Haushalte.") { _session = session; + Lease.PropertyChanged += (_, _) => SaveToSession(); } public ObservableCollection AvailableInterfaces { get; } = []; @@ -45,8 +46,14 @@ public partial class LanStepViewModel : WizardStepViewModelBase private string _secondaryDns = "8.8.8.8"; // Experten-Felder — nur im Experten-Modus sichtbar, leer bedeutet: RouterOS-Standardverhalten. + public LeaseTimeEditor Lease { get; } = new(); + + /// Hinweis, dass die Felder mit dem vorhandenen Heimnetz des Routers vorbelegt wurden (Mac v1.3.0). [ObservableProperty] - private string _dhcpLeaseTime = string.Empty; + private string? _prefillMessage; + + /// Für welche Verbindung schon vorgeladen wurde — nach einem Gerätewechsel erneut. + private object? _prefilledFor; [ObservableProperty] private string _domainName = string.Empty; @@ -64,23 +71,70 @@ public partial class LanStepViewModel : WizardStepViewModelBase /// Bei "Backup wiederherstellen" wird direkt zur Zusammenfassung gesprungen, ohne die Konfigurations-Schritte. public override bool ShouldSkip => _session.SelectedArea == AppArea.BackupManagement; - public override Task OnActivatedAsync() + public override async Task OnActivatedAsync() { OnPropertyChanged(nameof(IsExpertMode)); + var existing = await LoadExistingLanOnceAsync(); + var previouslySelected = AvailableInterfaces.Where(i => i.IsSelected).Select(i => i.Name).ToHashSet(); + var keepSelection = existing is null && AvailableInterfaces.Count > 0; + AvailableInterfaces.Clear(); var candidates = (_session.Device?.Interfaces ?? []).Where( i => i.Kind == InterfaceKind.Ethernet && i.Name != _session.WanInterfaceName); foreach (var iface in candidates) { - var item = new SelectableInterface(iface.Name, isSelected: true); + var isSelected = existing is { MemberInterfaces.Count: > 0 } + ? existing.MemberInterfaces.Contains(iface.Name) + : !keepSelection || previouslySelected.Contains(iface.Name); + var item = new SelectableInterface(iface.Name, isSelected); item.PropertyChanged += (_, _) => SaveToSession(); AvailableInterfaces.Add(item); } SaveToSession(); - return Task.CompletedTask; + } + + /// + /// Belegt die Felder einmal je Verbindung mit dem Heimnetz vor, das schon auf dem Router eingerichtet + /// ist, statt mit Standardwerten (Mac v1.3.0). Ein Anwenden aktualisiert dann die vorhandenen Einträge. + /// + private async Task LoadExistingLanOnceAsync() + { + if (_session.Client is not { } client || ReferenceEquals(_prefilledFor, client)) + { + return null; + } + + _prefilledFor = client; + var existing = await ExistingLanReader.ReadAsync(client); + if (existing is null) + { + PrefillMessage = null; + return null; + } + + BridgeName = existing.BridgeName; + var parts = existing.RouterAddressCidr.Split('/'); + RouterAddress = parts[0]; + PrefixLength = int.TryParse(parts.ElementAtOrDefault(1), out var prefix) ? prefix : PrefixLength; + if (existing.DhcpPoolStart.Length > 0) + { + DhcpPoolStart = existing.DhcpPoolStart; + DhcpPoolEnd = existing.DhcpPoolEnd; + } + + if (existing.PrimaryDnsServer.Length > 0) + { + PrimaryDns = existing.PrimaryDnsServer; + SecondaryDns = existing.SecondaryDnsServer ?? string.Empty; + } + + Lease.Load(existing.DhcpLeaseTime); + DomainName = existing.DomainName ?? string.Empty; + PrefillMessage = $"Vorhandenes Heimnetz „{existing.BridgeName}“ ({existing.RouterAddressCidr}) vom Router übernommen. Beim Anwenden werden diese Einträge aktualisiert statt neu angelegt."; + return existing; } partial void OnBridgeNameChanged(string value) => SaveToSession(); @@ -97,7 +151,6 @@ public partial class LanStepViewModel : WizardStepViewModelBase partial void OnSecondaryDnsChanged(string value) => SaveToSession(); - partial void OnDhcpLeaseTimeChanged(string value) => SaveToSession(); partial void OnDomainNameChanged(string value) => SaveToSession(); @@ -171,7 +224,7 @@ public partial class LanStepViewModel : WizardStepViewModelBase DhcpPoolEnd, PrimaryDns, string.IsNullOrWhiteSpace(SecondaryDns) ? null : SecondaryDns, - string.IsNullOrWhiteSpace(DhcpLeaseTime) ? null : DhcpLeaseTime, + Lease.Value, string.IsNullOrWhiteSpace(DomainName) ? null : DomainName, string.IsNullOrWhiteSpace(NtpServer) ? null : NtpServer); diff --git a/src/MikrotikInstaller.App/ViewModels/Steps/LeaseTimeEditor.cs b/src/MikrotikInstaller.App/ViewModels/Steps/LeaseTimeEditor.cs new file mode 100644 index 0000000..53ecaf3 --- /dev/null +++ b/src/MikrotikInstaller.App/ViewModels/Steps/LeaseTimeEditor.cs @@ -0,0 +1,30 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using MikrotikInstaller.Core.Configuration; + +namespace MikrotikInstaller.App.ViewModels.Steps; + +/// Eingabe der DHCP-Lease-Zeit als Jahre/Tage/Stunden (Mac v1.11.0), 0/0/0 = RouterOS-Standard. +public partial class LeaseTimeEditor : ObservableObject +{ + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(Value))] + private int _years; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(Value))] + private int _days; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(Value))] + private int _hours; + + /// RouterOS-Schreibweise oder null. + public string? Value => new LeaseTime(Math.Max(Years, 0), Math.Max(Days, 0), Math.Max(Hours, 0)).ToRouterOs(); + + /// Übernimmt einen vom Router gelesenen Wert ohne Kürzung. + public void Load(string? routerOsDuration) + { + var parsed = LeaseTime.Parse(routerOsDuration); + (Years, Days, Hours) = (parsed.Years, parsed.Days, parsed.Hours); + } +} diff --git a/src/MikrotikInstaller.App/ViewModels/Steps/VlanEntry.cs b/src/MikrotikInstaller.App/ViewModels/Steps/VlanEntry.cs index e470036..9742b05 100644 --- a/src/MikrotikInstaller.App/ViewModels/Steps/VlanEntry.cs +++ b/src/MikrotikInstaller.App/ViewModels/Steps/VlanEntry.cs @@ -31,8 +31,13 @@ public partial class VlanEntry : ObservableObject [ObservableProperty] private string _dnsServerOverride = string.Empty; - [ObservableProperty] - private string _dhcpLeaseTime = string.Empty; + /// DHCP-Lease-Zeit als Jahre/Tage/Stunden; Änderungen melden sich als Änderung von . + public LeaseTimeEditor Lease { get; } = new(); + + public VlanEntry() + { + Lease.PropertyChanged += (_, _) => OnPropertyChanged(nameof(Lease)); + } /// /// Anschlüsse, die zur Auswahl stehen, um sie fest (untagged/portbasiert) diesem VLAN zuzuordnen. diff --git a/src/MikrotikInstaller.App/ViewModels/Steps/VlanStepViewModel.cs b/src/MikrotikInstaller.App/ViewModels/Steps/VlanStepViewModel.cs index de66951..20bf821 100644 --- a/src/MikrotikInstaller.App/ViewModels/Steps/VlanStepViewModel.cs +++ b/src/MikrotikInstaller.App/ViewModels/Steps/VlanStepViewModel.cs @@ -190,7 +190,7 @@ public partial class VlanStepViewModel : WizardStepViewModelBase v.PoolEnd, v.IsolateFromLan, string.IsNullOrWhiteSpace(v.DnsServerOverride) ? null : v.DnsServerOverride, - string.IsNullOrWhiteSpace(v.DhcpLeaseTime) ? null : v.DhcpLeaseTime, + v.Lease.Value, v.AccessPortOptions.Where(p => p.IsSelected).Select(p => p.Name).ToList())) .ToList(); diff --git a/src/MikrotikInstaller.App/Views/Controls/LeaseTimePicker.xaml b/src/MikrotikInstaller.App/Views/Controls/LeaseTimePicker.xaml new file mode 100644 index 0000000..053d787 --- /dev/null +++ b/src/MikrotikInstaller.App/Views/Controls/LeaseTimePicker.xaml @@ -0,0 +1,14 @@ + + + + + + + + + + + diff --git a/src/MikrotikInstaller.App/Views/Controls/LeaseTimePicker.xaml.cs b/src/MikrotikInstaller.App/Views/Controls/LeaseTimePicker.xaml.cs new file mode 100644 index 0000000..d41086d --- /dev/null +++ b/src/MikrotikInstaller.App/Views/Controls/LeaseTimePicker.xaml.cs @@ -0,0 +1,11 @@ +using System.Windows.Controls; + +namespace MikrotikInstaller.App.Views.Controls; + +public partial class LeaseTimePicker : UserControl +{ + public LeaseTimePicker() + { + InitializeComponent(); + } +} diff --git a/src/MikrotikInstaller.App/Views/Steps/LanStepView.xaml b/src/MikrotikInstaller.App/Views/Steps/LanStepView.xaml index 6eb722b..29d6052 100644 --- a/src/MikrotikInstaller.App/Views/Steps/LanStepView.xaml +++ b/src/MikrotikInstaller.App/Views/Steps/LanStepView.xaml @@ -1,4 +1,4 @@ - + + @@ -92,10 +95,10 @@ - - + + - + diff --git a/src/MikrotikInstaller.App/Views/Steps/VlanStepView.xaml b/src/MikrotikInstaller.App/Views/Steps/VlanStepView.xaml index 61f0efe..06ad70e 100644 --- a/src/MikrotikInstaller.App/Views/Steps/VlanStepView.xaml +++ b/src/MikrotikInstaller.App/Views/Steps/VlanStepView.xaml @@ -1,4 +1,4 @@ - - - + + + + diff --git a/src/MikrotikInstaller.Core.Tests/Configuration/LanConfiguratorTests.cs b/src/MikrotikInstaller.Core.Tests/Configuration/LanConfiguratorTests.cs index 1c8701e..85e6818 100644 --- a/src/MikrotikInstaller.Core.Tests/Configuration/LanConfiguratorTests.cs +++ b/src/MikrotikInstaller.Core.Tests/Configuration/LanConfiguratorTests.cs @@ -60,11 +60,38 @@ public class LanConfiguratorTests } Assert.Contains(client.AddCalls, c => c.Path == "/ip/dhcp-server" && c.Parameters["lease-time"] == "1d"); - Assert.Contains(client.AddCalls, c => c.Path == "/ip/dhcp-server/network" && c.Parameters["domain-name"] == "heim.lan"); + Assert.Contains(client.AddCalls, c => c.Path == "/ip/dhcp-server/network" && c.Parameters["domain"] == "heim.lan"); Assert.Contains(client.ExecuteCalls, c => c.Path == "/system/ntp/client/set" && c.Parameters!["enabled"] == "yes" && c.Parameters["servers"] == "pool.ntp.org"); } + [Fact] + public async Task BuildActions_ExistingConfiguration_UpdatesInsteadOfDuplicating() + { + var client = new RecordingRouterOsClient(); + client.GetResponses["/interface/bridge"] = [new Dictionary { [".id"] = "*B", ["name"] = "bridge-lan" }]; + client.GetResponses["/interface/bridge/port"] = + [ + new Dictionary { [".id"] = "*P2", ["bridge"] = "bridge-lan", ["interface"] = "ether2" }, + new Dictionary { [".id"] = "*P3", ["bridge"] = "bridge-alt", ["interface"] = "ether3" }, + ]; + client.GetResponses["/ip/dhcp-server"] = [new Dictionary { [".id"] = "*D", ["name"] = "defconf", ["interface"] = "bridge-lan", ["address-pool"] = "default-dhcp", ["disabled"] = "false" }]; + + foreach (var action in LanConfigurator.BuildActions(DefaultSettings())) + { + await action.ApplyAsync(client, CancellationToken.None); + } + + Assert.DoesNotContain(client.AddCalls, c => c.Path is "/interface/bridge" or "/interface/bridge/port" or "/ip/dhcp-server"); + // ether3 hing in einer anderen Bridge und wird umgehängt. + Assert.Contains(client.SetCalls, c => c.Path == "/interface/bridge/port" && c.Id == "*P3" && c.Parameters["bridge"] == "bridge-lan"); + Assert.DoesNotContain(client.SetCalls, c => c.Id == "*P2"); + // Der vorhandene DHCP-Server behält seinen Namen, bekommt aber den neuen Pool. + var dhcp = Assert.Single(client.SetCalls, c => c.Path == "/ip/dhcp-server"); + Assert.Equal("pool-bridge-lan", dhcp.Parameters["address-pool"]); + Assert.False(dhcp.Parameters.ContainsKey("name")); + } + [Fact] public void BuildFriendlySummary_MentionsNetworkAndMemberInterfaces() { diff --git a/src/MikrotikInstaller.Core.Tests/Configuration/LeaseTimeAndExistingLanTests.cs b/src/MikrotikInstaller.Core.Tests/Configuration/LeaseTimeAndExistingLanTests.cs new file mode 100644 index 0000000..aa491bb --- /dev/null +++ b/src/MikrotikInstaller.Core.Tests/Configuration/LeaseTimeAndExistingLanTests.cs @@ -0,0 +1,60 @@ +using MikrotikInstaller.Core.Configuration; + +namespace MikrotikInstaller.Core.Tests.Configuration; + +public class LeaseTimeAndExistingLanTests +{ + [Theory] + [InlineData(0, 0, 0, null)] + [InlineData(0, 1, 0, "1d")] + [InlineData(0, 0, 12, "12h")] + [InlineData(1, 2, 3, "367d3h")] + public void ToRouterOs_FormatsDuration(int years, int days, int hours, string? expected) => + Assert.Equal(expected, new LeaseTime(years, days, hours).ToRouterOs()); + + [Theory] + [InlineData("1d00:00:00", 0, 1, 0)] + [InlineData("3w2d", 0, 23, 0)] + [InlineData("10m", 0, 0, 1)] + [InlineData("12:00:00", 0, 0, 12)] + [InlineData("367d3h", 1, 2, 3)] + [InlineData("", 0, 0, 0)] + public void Parse_ReadsRouterOsDurationsWithoutTruncation(string text, int years, int days, int hours) => + Assert.Equal(new LeaseTime(years, days, hours), LeaseTime.Parse(text)); + + [Fact] + public async Task ExistingLanReader_ReadsBridgeAddressPoolDnsAndMembers() + { + var client = new RecordingRouterOsClient(); + client.GetResponses["/interface/bridge"] = [new Dictionary { ["name"] = "bridge" }]; + client.GetResponses["/ip/address"] = + [ + new Dictionary { ["address"] = "203.0.113.5/24", ["interface"] = "ether1" }, + new Dictionary { ["address"] = "10.0.0.1/24", ["interface"] = "bridge" }, + ]; + client.GetResponses["/interface/bridge/port"] = + [ + new Dictionary { ["bridge"] = "bridge", ["interface"] = "ether2" }, + new Dictionary { ["bridge"] = "bridge", ["interface"] = "wlan1" }, + ]; + client.GetResponses["/ip/dhcp-server"] = [new Dictionary { ["interface"] = "bridge", ["address-pool"] = "dhcp", ["lease-time"] = "3w" }]; + client.GetResponses["/ip/pool"] = [new Dictionary { ["name"] = "dhcp", ["ranges"] = "10.0.0.10-10.0.0.200" }]; + client.GetResponses["/ip/dhcp-server/network"] = [new Dictionary { ["address"] = "10.0.0.0/24", ["domain"] = "heim.lan" }]; + client.GetResponses["/ip/dns"] = [new Dictionary { ["servers"] = "9.9.9.9,1.1.1.1" }]; + + var lan = await ExistingLanReader.ReadAsync(client); + + Assert.NotNull(lan); + Assert.Equal("bridge", lan.BridgeName); + Assert.Equal("10.0.0.1/24", lan.RouterAddressCidr); + Assert.Equal(["ether2", "wlan1"], lan.MemberInterfaces); + Assert.Equal(("10.0.0.10", "10.0.0.200"), (lan.DhcpPoolStart, lan.DhcpPoolEnd)); + Assert.Equal(("9.9.9.9", "1.1.1.1"), (lan.PrimaryDnsServer, lan.SecondaryDnsServer)); + Assert.Equal("3w", lan.DhcpLeaseTime); + Assert.Equal("heim.lan", lan.DomainName); + } + + [Fact] + public async Task ExistingLanReader_NoBridgeWithAddress_ReturnsNull() => + Assert.Null(await ExistingLanReader.ReadAsync(new RecordingRouterOsClient())); +} diff --git a/src/MikrotikInstaller.Core/Configuration/ExistingLanReader.cs b/src/MikrotikInstaller.Core/Configuration/ExistingLanReader.cs new file mode 100644 index 0000000..2f5d58e --- /dev/null +++ b/src/MikrotikInstaller.Core/Configuration/ExistingLanReader.cs @@ -0,0 +1,69 @@ +using MikrotikInstaller.Core.Connectivity; + +namespace MikrotikInstaller.Core.Configuration; + +/// +/// Liest ein bereits vorhandenes Heimnetz vom Router (erste Bridge mit IP-Adresse samt DHCP-Server, Pool, +/// Netzwerk und DNS), damit der LAN-Schritt mit den echten Werten statt mit Standardwerten startet +/// (Mac v1.3.0, Mac-Gitea #30). Null, wenn es keine Bridge mit Adresse gibt (z. B. werksneues Gerät ohne Standardkonfiguration). +/// +public static class ExistingLanReader +{ + public static async Task ReadAsync(IRouterOsClient client, CancellationToken cancellationToken = default) + { + var bridges = (await TryGetAsync(client, "/interface/bridge", cancellationToken)) + .Select(row => row.GetValueOrDefault("name")).OfType().ToHashSet(); + var address = (await TryGetAsync(client, "/ip/address", cancellationToken)) + .FirstOrDefault(row => row.GetValueOrDefault("interface") is { } iface && bridges.Contains(iface) + && row.GetValueOrDefault("address")?.Contains('/') == true); + if (address is null) + { + return null; + } + + var bridgeName = address["interface"]; + var routerAddressCidr = address["address"]; + var routerIp = routerAddressCidr.Split('/')[0]; + + var members = (await TryGetAsync(client, "/interface/bridge/port", cancellationToken)) + .Where(row => row.GetValueOrDefault("bridge") == bridgeName) + .Select(row => row.GetValueOrDefault("interface")).OfType().ToList(); + + var dhcpServer = (await TryGetAsync(client, "/ip/dhcp-server", cancellationToken)) + .FirstOrDefault(row => row.GetValueOrDefault("interface") == bridgeName); + var pool = dhcpServer?.GetValueOrDefault("address-pool") is { } poolName + ? (await TryGetAsync(client, "/ip/pool", cancellationToken)).FirstOrDefault(row => row.GetValueOrDefault("name") == poolName) + : null; + var firstRange = pool?.GetValueOrDefault("ranges")?.Split(',')[0].Split('-'); + + var network = (await TryGetAsync(client, "/ip/dhcp-server/network", cancellationToken)) + .FirstOrDefault(row => row.GetValueOrDefault("address") is { } cidr && IpNetworkHelper.Contains(cidr, routerIp)); + var dnsServers = (await TryGetAsync(client, "/ip/dns", cancellationToken)).FirstOrDefault()?.GetValueOrDefault("servers")? + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? []; + + return new LanSettings( + bridgeName, + members, + routerAddressCidr, + firstRange is { Length: 2 } ? firstRange[0] : string.Empty, + firstRange is { Length: 2 } ? firstRange[1] : string.Empty, + dnsServers.ElementAtOrDefault(0) ?? string.Empty, + dnsServers.ElementAtOrDefault(1), + dhcpServer?.GetValueOrDefault("lease-time"), + network?.GetValueOrDefault("domain"), + NtpServer: null); + } + + private static async Task>> TryGetAsync( + IRouterOsClient client, string path, CancellationToken cancellationToken) + { + try + { + return await client.GetAsync(path, cancellationToken); + } + catch (RouterOsException) + { + return []; + } + } +} diff --git a/src/MikrotikInstaller.Core/Configuration/LanConfigurator.cs b/src/MikrotikInstaller.Core/Configuration/LanConfigurator.cs index 93d53ea..9bfbd59 100644 --- a/src/MikrotikInstaller.Core/Configuration/LanConfigurator.cs +++ b/src/MikrotikInstaller.Core/Configuration/LanConfigurator.cs @@ -3,6 +3,8 @@ namespace MikrotikInstaller.Core.Configuration; /// /// Erzeugt aus den Wizard-Eingaben zum Heimnetzwerk die anzuwendenden RouterOS-Änderungen: /// Bridge mit den gewählten Schnittstellen, IP-Adresse, DHCP-Server und DNS-Weiterleitung. +/// Jeder Schritt legt an oder aktualisiert (), damit der Assistent auch auf +/// einem bereits eingerichteten Gerät mit vorgeladenem Heimnetz funktioniert. /// public static class LanConfigurator { @@ -16,41 +18,42 @@ public static class LanConfigurator actions.Add(new ConfigurationAction( $"Netzwerk-Bridge „{settings.BridgeName}\" für dein Heimnetzwerk anlegen", - (client, ct) => client.AddAsync("/interface/bridge", new Dictionary - { - ["name"] = settings.BridgeName, - }, ct))); + (client, ct) => RouterOsUpsert.UpsertAsync( + client, "/interface/bridge", Match("name", settings.BridgeName), Match("name", settings.BridgeName), cancellationToken: ct))); foreach (var interfaceName in settings.MemberInterfaces) { actions.Add(new ConfigurationAction( $"Schnittstelle „{interfaceName}\" dem Heimnetzwerk hinzufügen", - (client, ct) => client.AddAsync("/interface/bridge/port", new Dictionary - { - ["bridge"] = settings.BridgeName, - ["interface"] = interfaceName, - }, ct))); + // Ein Anschluss kann nur in einer Bridge sein — steckt er schon in einer anderen, wird er umgehängt. + (client, ct) => RouterOsUpsert.UpsertAsync( + client, + "/interface/bridge/port", + Match("interface", interfaceName), + new Dictionary { ["bridge"] = settings.BridgeName, ["interface"] = interfaceName }, + cancellationToken: ct))); } actions.Add(new ConfigurationAction( $"IP-Adresse {settings.RouterAddressCidr} auf „{settings.BridgeName}\" einrichten", - (client, ct) => client.AddAsync("/ip/address", new Dictionary - { - ["address"] = settings.RouterAddressCidr, - ["interface"] = settings.BridgeName, - }, ct))); + (client, ct) => RouterOsUpsert.UpsertAsync( + client, + "/ip/address", + Match("interface", settings.BridgeName), + new Dictionary { ["address"] = settings.RouterAddressCidr, ["interface"] = settings.BridgeName }, + cancellationToken: ct))); actions.Add(new ConfigurationAction( $"IP-Adressbereich {settings.DhcpPoolStart}-{settings.DhcpPoolEnd} für Geräte in deinem Netzwerk reservieren", - (client, ct) => client.AddAsync("/ip/pool", new Dictionary - { - ["name"] = poolName, - ["ranges"] = $"{settings.DhcpPoolStart}-{settings.DhcpPoolEnd}", - }, ct))); + (client, ct) => RouterOsUpsert.UpsertAsync( + client, + "/ip/pool", + Match("name", poolName), + new Dictionary { ["name"] = poolName, ["ranges"] = $"{settings.DhcpPoolStart}-{settings.DhcpPoolEnd}" }, + cancellationToken: ct))); var dhcpServerParameters = new Dictionary { - ["name"] = dhcpServerName, ["interface"] = settings.BridgeName, ["address-pool"] = poolName, ["disabled"] = "no", @@ -62,7 +65,9 @@ public static class LanConfigurator actions.Add(new ConfigurationAction( $"DHCP-Server auf „{settings.BridgeName}\" aktivieren, damit Geräte automatisch eine Adresse bekommen", - (client, ct) => client.AddAsync("/ip/dhcp-server", dhcpServerParameters, ct))); + // Ein vorhandener DHCP-Server auf der Bridge (z. B. "defconf") behält seinen Namen. + (client, ct) => RouterOsUpsert.UpsertAsync( + client, "/ip/dhcp-server", Match("interface", settings.BridgeName), dhcpServerParameters, Match("name", dhcpServerName), ct))); var networkParameters = new Dictionary { @@ -72,12 +77,13 @@ public static class LanConfigurator }; if (!string.IsNullOrWhiteSpace(settings.DomainName)) { - networkParameters["domain-name"] = settings.DomainName; + // RouterOS heißt das Feld "domain" (nicht "domain-name"). + networkParameters["domain"] = settings.DomainName; } actions.Add(new ConfigurationAction( $"Netzwerk-Einstellungen (Gateway {routerAddress}, DNS) für das Heimnetzwerk hinterlegen", - (client, ct) => client.AddAsync("/ip/dhcp-server/network", networkParameters, ct))); + (client, ct) => RouterOsUpsert.UpsertAsync(client, "/ip/dhcp-server/network", Match("address", networkCidr), networkParameters, cancellationToken: ct))); var upstreamDns = settings.SecondaryDnsServer is null ? settings.PrimaryDnsServer @@ -105,6 +111,8 @@ public static class LanConfigurator return actions; } + private static Dictionary Match(string key, string value) => new() { [key] = value }; + /// Kurze, laientaugliche Zusammenfassung für den Zusammenfassungs-Schritt (keine RouterOS-Fachbegriffe). public static IReadOnlyList BuildFriendlySummary(LanSettings settings) { diff --git a/src/MikrotikInstaller.Core/Configuration/LeaseTime.cs b/src/MikrotikInstaller.Core/Configuration/LeaseTime.cs new file mode 100644 index 0000000..aa86071 --- /dev/null +++ b/src/MikrotikInstaller.Core/Configuration/LeaseTime.cs @@ -0,0 +1,67 @@ +using System.Text.RegularExpressions; + +namespace MikrotikInstaller.Core.Configuration; + +/// +/// DHCP-Lease-Zeit als Jahre/Tage/Stunden (Mac v1.11.0) statt RouterOS-Kurzschreibweise. Ein Jahr = 365 Tage. +/// liest jede RouterOS-Dauer ("1w2d", "3d12:00:00", "10m") ohne Kürzung ein — der +/// Mac-Assistent kürzte vorhandene Werte über einer Woche fälschlich auf 7 Tage. +/// +public readonly partial record struct LeaseTime(int Years, int Days, int Hours) +{ + /// RouterOS-Schreibweise, null bei 0 (= RouterOS-Standardwert verwenden). + public string? ToRouterOs() + { + var totalDays = (Years * 365) + Days; + var text = (totalDays > 0 ? $"{totalDays}d" : string.Empty) + (Hours > 0 ? $"{Hours}h" : string.Empty); + return text.Length == 0 ? null : text; + } + + public static LeaseTime Parse(string? routerOsDuration) + { + if (string.IsNullOrWhiteSpace(routerOsDuration)) + { + return default; + } + + var total = TimeSpan.Zero; + var rest = routerOsDuration.Trim(); + + // Anhängende Uhrzeit-Schreibweise "hh:mm:ss" (z. B. "1d00:00:00"). + var clock = ClockPattern().Match(rest); + if (clock.Success) + { + total += new TimeSpan(int.Parse(clock.Groups["h"].Value), int.Parse(clock.Groups["m"].Value), int.Parse(clock.Groups["s"].Value)); + rest = rest[..clock.Index]; + } + + foreach (Match unit in UnitPattern().Matches(rest)) + { + var value = int.Parse(unit.Groups["value"].Value); + total += unit.Groups["unit"].Value switch + { + "w" => TimeSpan.FromDays(7 * value), + "d" => TimeSpan.FromDays(value), + "h" => TimeSpan.FromHours(value), + "m" => TimeSpan.FromMinutes(value), + _ => TimeSpan.FromSeconds(value), + }; + } + + var days = (int)total.TotalDays; + // Minuten/Sekunden auf ganze Stunden runden, aber nie auf 0 fallen lassen (z. B. "10m" → 1 Stunde). + var hours = (int)Math.Round(total.TotalHours - (days * 24), MidpointRounding.AwayFromZero); + if (days == 0 && hours == 0 && total > TimeSpan.Zero) + { + hours = 1; + } + + return new LeaseTime(days / 365, days % 365, hours); + } + + [GeneratedRegex(@"(?\d+):(?\d{2}):(?\d{2})$")] + private static partial Regex ClockPattern(); + + [GeneratedRegex(@"(?\d+)(?[wdhms])")] + private static partial Regex UnitPattern(); +} diff --git a/src/MikrotikInstaller.Core/Configuration/RouterOsUpsert.cs b/src/MikrotikInstaller.Core/Configuration/RouterOsUpsert.cs new file mode 100644 index 0000000..2b7175a --- /dev/null +++ b/src/MikrotikInstaller.Core/Configuration/RouterOsUpsert.cs @@ -0,0 +1,44 @@ +using MikrotikInstaller.Core.Connectivity; + +namespace MikrotikInstaller.Core.Configuration; + +/// +/// Anlegen oder aktualisieren: Damit der Assistent auch auf einem bereits eingerichteten Gerät (z. B. +/// mit vorgeladenem LAN, Mac v1.3.0) erneut angewendet werden kann, ohne an „already have such name“ +/// zu scheitern oder Einträge zu verdoppeln. +/// +public static class RouterOsUpsert +{ + /// Felder, an denen ein vorhandener Eintrag erkannt wird. + /// Werte, die der Eintrag danach tragen soll. + /// Zusätzliche Felder nur beim Neuanlegen (z. B. ein Name, der einen vorhandenen Eintrag nicht umbenennen soll). + public static async Task UpsertAsync( + IRouterOsClient client, + string path, + IReadOnlyDictionary match, + IReadOnlyDictionary parameters, + IReadOnlyDictionary? addOnly = null, + CancellationToken cancellationToken = default) + { + var rows = await client.GetAsync(path, cancellationToken); + var existing = rows.FirstOrDefault(row => match.All(kv => row.GetValueOrDefault(kv.Key) == kv.Value)); + + if (existing is null) + { + var all = new Dictionary(parameters); + foreach (var (key, value) in addOnly ?? new Dictionary()) + { + all[key] = value; + } + + await client.AddAsync(path, all, cancellationToken); + return; + } + + var changes = parameters.Where(kv => existing.GetValueOrDefault(kv.Key) != kv.Value).ToDictionary(); + if (changes.Count > 0 && existing.GetValueOrDefault(".id") is { } id) + { + await client.SetAsync(path, id, changes, cancellationToken); + } + } +} diff --git a/src/MikrotikInstaller.Core/Connectivity/Demo/DemoRouterOsClient.cs b/src/MikrotikInstaller.Core/Connectivity/Demo/DemoRouterOsClient.cs index bd2b2af..12e5506 100644 --- a/src/MikrotikInstaller.Core/Connectivity/Demo/DemoRouterOsClient.cs +++ b/src/MikrotikInstaller.Core/Connectivity/Demo/DemoRouterOsClient.cs @@ -211,10 +211,18 @@ public sealed class DemoRouterOsClient : IRouterOsClient // Ab hier: Beispieldaten für die IST-Zustand-Analyse (bereits vorhandene Konfiguration eines // simulierten Bestandsgeräts), damit sich der neue Analyse-Schritt über den Testzugang // gefahrlos durchklicken lässt. + ["/interface/bridge"] = + [ + new() { [".id"] = "*B1", ["name"] = "bridge-lan", ["vlan-filtering"] = "false" }, + ], ["/interface/bridge/port"] = [ - new() { ["bridge"] = "bridge-lan", ["interface"] = "ether2" }, - new() { ["bridge"] = "bridge-lan", ["interface"] = "ether3" }, + new() { [".id"] = "*BP1", ["bridge"] = "bridge-lan", ["interface"] = "ether2" }, + new() { [".id"] = "*BP2", ["bridge"] = "bridge-lan", ["interface"] = "ether3" }, + ], + ["/ip/dns"] = + [ + new() { ["servers"] = "1.1.1.1,9.9.9.9", ["allow-remote-requests"] = "true" }, ], ["/interface/vlan"] = [