mirror of
https://github.com/alexhopeoconnor/dnsmasq-webui.git
synced 2026-10-04 04:18:13 +10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b22e4fb7d | ||
|
|
a3cc3968af | ||
|
|
8ed66cdf48 | ||
|
|
a776f445b6 | ||
|
|
b0ce7afb58 | ||
|
|
2cfbaf000c | ||
|
|
f8754d8d6e | ||
|
|
71a8a61cb3 | ||
|
|
bf1f6a0d82 | ||
|
|
91beb9d181 | ||
|
|
4e122ba439 | ||
|
|
6a7c0f62e1 | ||
|
|
f22b039e74 | ||
|
|
906e222ec1 | ||
|
|
ecd9e5cc7b | ||
|
|
e7c2560d07 | ||
|
|
439192058e | ||
|
|
7965fc669b | ||
|
|
dfee96650b | ||
|
|
cefc488712 | ||
|
|
5ac2006b80 | ||
|
|
1bdd176c18 | ||
|
|
b70aa02017 | ||
|
|
d06d6ef6c9 | ||
|
|
1dffdcf2ed | ||
|
|
3ae556168e | ||
|
|
b44dde2c77 | ||
|
|
23bf6bb9e0 | ||
|
|
dfb0b94e4a | ||
|
|
4317efff68 |
@@ -29,22 +29,22 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
-v "${{ github.workspace }}:/src" -w /src \
|
-v "${{ github.workspace }}:/src" -w /src \
|
||||||
mcr.microsoft.com/dotnet/sdk:9.0 \
|
mcr.microsoft.com/dotnet/sdk:10.0 \
|
||||||
./scripts/publish-self-contained.sh ${{ matrix.rid }}
|
./scripts/publish-self-contained.sh ${{ matrix.rid }} ${{ github.ref_name }}
|
||||||
|
|
||||||
- name: Setup .NET
|
- name: Setup .NET
|
||||||
if: matrix.rid == 'linux-musl-x64' || matrix.rid == 'linux-musl-arm64'
|
if: matrix.rid == 'linux-musl-x64' || matrix.rid == 'linux-musl-arm64'
|
||||||
uses: actions/setup-dotnet@v4
|
uses: actions/setup-dotnet@v4
|
||||||
with:
|
with:
|
||||||
dotnet-version: '9.0.x'
|
dotnet-version: '10.0.x'
|
||||||
|
|
||||||
- name: Publish for ${{ matrix.rid }} (musl on host)
|
- name: Publish for ${{ matrix.rid }} (musl on host)
|
||||||
if: matrix.rid == 'linux-musl-x64' || matrix.rid == 'linux-musl-arm64'
|
if: matrix.rid == 'linux-musl-x64' || matrix.rid == 'linux-musl-arm64'
|
||||||
run: ./scripts/publish-self-contained.sh ${{ matrix.rid }}
|
run: ./scripts/publish-self-contained.sh ${{ matrix.rid }} ${{ github.ref_name }}
|
||||||
|
|
||||||
- name: Zip publish output
|
- name: Zip publish output
|
||||||
run: |
|
run: |
|
||||||
PUBLISH_DIR="src/DnsmasqWebUI/bin/Release/net9.0/${{ matrix.rid }}/publish"
|
PUBLISH_DIR="src/DnsmasqWebUI/bin/Release/net10.0/${{ matrix.rid }}/publish"
|
||||||
(cd "$PUBLISH_DIR" && zip -r "../../../../../../../dnsmasq-webui-${{ matrix.rid }}.zip" .)
|
(cd "$PUBLISH_DIR" && zip -r "../../../../../../../dnsmasq-webui-${{ matrix.rid }}.zip" .)
|
||||||
|
|
||||||
- name: Upload artifact
|
- name: Upload artifact
|
||||||
|
|||||||
+2
-1
@@ -43,6 +43,7 @@ testdata-mount/
|
|||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
# User-specific
|
# User-specific / runtime
|
||||||
appsettings.*.local.json
|
appsettings.*.local.json
|
||||||
|
appsettings.Overrides.json
|
||||||
*.local
|
*.local
|
||||||
|
|||||||
+7
-8
@@ -3,12 +3,12 @@
|
|||||||
# For dnsmasq on the host, use the self-contained publish (scripts/publish-self-contained.sh)
|
# For dnsmasq on the host, use the self-contained publish (scripts/publish-self-contained.sh)
|
||||||
# or run the app on the host; see DnsmasqOptions XML doc for permissions and ReloadCommand scope.
|
# or run the app on the host; see DnsmasqOptions XML doc for permissions and ReloadCommand scope.
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base
|
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
EXPOSE 8081
|
EXPOSE 8081
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
|
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY ["src/DnsmasqWebUI/DnsmasqWebUI.csproj", "src/DnsmasqWebUI/"]
|
COPY ["src/DnsmasqWebUI/DnsmasqWebUI.csproj", "src/DnsmasqWebUI/"]
|
||||||
RUN dotnet restore "src/DnsmasqWebUI/DnsmasqWebUI.csproj"
|
RUN dotnet restore "src/DnsmasqWebUI/DnsmasqWebUI.csproj"
|
||||||
@@ -19,15 +19,14 @@ RUN dotnet build "DnsmasqWebUI.csproj" -c Release -o /app/build
|
|||||||
FROM build AS publish
|
FROM build AS publish
|
||||||
RUN dotnet publish "DnsmasqWebUI.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
RUN dotnet publish "DnsmasqWebUI.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
||||||
|
|
||||||
FROM base AS app
|
FROM base AS final
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV ASPNETCORE_URLS=http://+:8080
|
ENV ASPNETCORE_URLS=http://+:8080
|
||||||
COPY --from=publish /app/publish .
|
# Slow, rarely-changing steps first (stay cached when only .NET code changes)
|
||||||
|
|
||||||
FROM app AS final
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends dnsmasq procps \
|
RUN apt-get update && apt-get install -y --no-install-recommends dnsmasq procps \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
COPY scripts/entrypoint.sh .
|
COPY scripts/entrypoint.sh scripts/dnsmasq-status.sh .
|
||||||
COPY scripts/dnsmasq-status.sh .
|
|
||||||
RUN chmod +x entrypoint.sh dnsmasq-status.sh
|
RUN chmod +x entrypoint.sh dnsmasq-status.sh
|
||||||
|
# .NET publish last - only this layer invalidates when code changes
|
||||||
|
COPY --from=publish /app/publish .
|
||||||
ENTRYPOINT ["./entrypoint.sh"]
|
ENTRYPOINT ["./entrypoint.sh"]
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ The recommended way to get a prebuilt binary is the **install script**. It picks
|
|||||||
curl -sSL https://raw.githubusercontent.com/alexhopeoconnor/dnsmasq-webui/master/scripts/install.sh | sh
|
curl -sSL https://raw.githubusercontent.com/alexhopeoconnor/dnsmasq-webui/master/scripts/install.sh | sh
|
||||||
```
|
```
|
||||||
|
|
||||||
**From a git clone** (repo is detected from `git remote origin`):
|
**From a git clone:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./scripts/install.sh
|
./scripts/install.sh
|
||||||
@@ -102,8 +102,6 @@ sudo ./scripts/install.sh --uninstall --purge --system # Also remove /opt/dnsm
|
|||||||
./scripts/install.sh --version v1.0.0
|
./scripts/install.sh --version v1.0.0
|
||||||
```
|
```
|
||||||
|
|
||||||
**Installing from a fork:** Pass the repo explicitly: `./scripts/install.sh --repo owner/dnsmasq-webui` or set `GITHUB_REPO=owner/dnsmasq-webui`. The default repo is `alexhopeoconnor/dnsmasq-webui`.
|
|
||||||
|
|
||||||
**If the binary fails to run** (e.g. `TypeLoadException` or glibc errors): use the install script with `--build-from-source` so the app is built for your machine. This requires the .NET SDK and a **git clone** (it does not work when installing via `curl ... | sh`). Clone the repo, then run `./scripts/install.sh --build-from-source`. The script checks that .NET is installed, detects your OS/arch, and builds (on Ubuntu it may use a distro-specific RID for a better match). Other distros use the portable RID and may still hit runtime issues; building from source on the target machine is the most reliable.
|
**If the binary fails to run** (e.g. `TypeLoadException` or glibc errors): use the install script with `--build-from-source` so the app is built for your machine. This requires the .NET SDK and a **git clone** (it does not work when installing via `curl ... | sh`). Clone the repo, then run `./scripts/install.sh --build-from-source`. The script checks that .NET is installed, detects your OS/arch, and builds (on Ubuntu it may use a distro-specific RID for a better match). Other distros use the portable RID and may still hit runtime issues; building from source on the target machine is the most reliable.
|
||||||
|
|
||||||
**Configuration:** Set at least `Dnsmasq__MainConfigPath` to your main dnsmasq config. See [Configuration](#configuration) for all options.
|
**Configuration:** Set at least `Dnsmasq__MainConfigPath` to your main dnsmasq config. See [Configuration](#configuration) for all options.
|
||||||
@@ -238,7 +236,6 @@ All scripts live under `scripts/` and are intended for Linux (WSL may work but i
|
|||||||
|
|
||||||
| Option | Description |
|
| Option | Description |
|
||||||
|--------|-------------|
|
|--------|-------------|
|
||||||
| `--repo OWNER/REPO` | GitHub owner/repo (or set `GITHUB_REPO`). When run from a clone, repo is detected from `git remote origin`. Default repo: `alexhopeoconnor/dnsmasq-webui`. |
|
|
||||||
| `--list` | List available releases (tag, name, published_at) and exit. |
|
| `--list` | List available releases (tag, name, published_at) and exit. |
|
||||||
| `--version TAG` | Install from release TAG (e.g. v1.0.0). Default: latest. |
|
| `--version TAG` | Install from release TAG (e.g. v1.0.0). Default: latest. |
|
||||||
| `--update` | Reinstall latest into the default user directory (~/.local/share/dnsmasq-webui). |
|
| `--update` | Reinstall latest into the default user directory (~/.local/share/dnsmasq-webui). |
|
||||||
@@ -291,18 +288,14 @@ Invalid combinations (script errors with a clear message): `--purge` without `--
|
|||||||
Script lists release tags and dates; list-only mode cannot be combined with install/uninstall so you do not accidentally change the system.
|
Script lists release tags and dates; list-only mode cannot be combined with install/uninstall so you do not accidentally change the system.
|
||||||
**Command:** `./scripts/install.sh --list`
|
**Command:** `./scripts/install.sh --list`
|
||||||
|
|
||||||
10. **Install from a fork or a specific GitHub repo** instead of the default.
|
10. **Install a specific release tag** (e.g. an older or pinned version) instead of latest.
|
||||||
You pass the repo; script uses it for the API. Without a clone or `--repo`/GITHUB_REPO it errors so you fix the command instead of getting a confusing API failure.
|
|
||||||
**Command:** `./scripts/install.sh --repo owner/dnsmasq-webui` or `GITHUB_REPO=owner/dnsmasq-webui ./scripts/install.sh`
|
|
||||||
|
|
||||||
11. **Install a specific release tag** (e.g. an older or pinned version) instead of latest.
|
|
||||||
Script fetches that tag's release and the asset for your RID. If no asset matches your OS/arch it errors and prints the asset names so you can pick another tag or report a missing build.
|
Script fetches that tag's release and the asset for your RID. If no asset matches your OS/arch it errors and prints the asset names so you can pick another tag or report a missing build.
|
||||||
**Command:** `./scripts/install.sh --version v1.0.0`
|
**Command:** `./scripts/install.sh --version v1.0.0`
|
||||||
|
|
||||||
**Examples:**
|
**Examples:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Install latest (from clone: repo auto-detected; from curl: uses alexhopeoconnor/dnsmasq-webui by default, or use --repo)
|
# Install latest
|
||||||
./scripts/install.sh
|
./scripts/install.sh
|
||||||
|
|
||||||
# Update to latest release
|
# Update to latest release
|
||||||
@@ -329,8 +322,8 @@ sudo ./scripts/install.sh --uninstall --purge --system
|
|||||||
# Switch to another release (overwrites that dir)
|
# Switch to another release (overwrites that dir)
|
||||||
./scripts/install.sh --dir ~/.local/share/dnsmasq-webui --version v0.9.0
|
./scripts/install.sh --dir ~/.local/share/dnsmasq-webui --version v0.9.0
|
||||||
|
|
||||||
# List releases (from fork)
|
# List releases
|
||||||
./scripts/install.sh --repo alexhopeoconnor/dnsmasq-webui --list
|
./scripts/install.sh --list
|
||||||
```
|
```
|
||||||
|
|
||||||
**How the script works and avoids mistakes**
|
**How the script works and avoids mistakes**
|
||||||
@@ -351,7 +344,7 @@ sudo ./scripts/install.sh --uninstall --purge --system
|
|||||||
`--uninstall` removes only systemd units and symlinks unless you add `--purge`. With `--purge`, you must say *which* install to remove: default user dir (no extra flags), `--dir DIR`, or `--system` for /opt. That avoids accidentally deleting the wrong directory.
|
`--uninstall` removes only systemd units and symlinks unless you add `--purge`. With `--purge`, you must say *which* install to remove: default user dir (no extra flags), `--dir DIR`, or `--system` for /opt. That avoids accidentally deleting the wrong directory.
|
||||||
|
|
||||||
6. **Repo and release**
|
6. **Repo and release**
|
||||||
When not in a git clone, the script needs a repo (e.g. `REPO_DEFAULT` in the one-liner or `--repo` / `GITHUB_REPO`). It errors with a clear message instead of hitting the GitHub API with an empty repo. If no asset matches your OS/arch (RID), it prints the available asset names so you can pick a different release or report a missing build.
|
If no asset matches your OS/arch (RID), the script prints the available asset names so you can pick a different release or report a missing build.
|
||||||
|
|
||||||
7. **Dependencies**
|
7. **Dependencies**
|
||||||
The script requires `curl`, `jq`, and `unzip`. It checks for `jq` before calling the GitHub API and errors with an install hint. `--service` requires `systemctl` (systemd) and errors on non-systemd systems instead of writing a unit that won’t be used.
|
The script requires `curl`, `jq`, and `unzip`. It checks for `jq` before calling the GitHub API and errors with an install hint. `--service` requires `systemctl` (systemd) and errors on non-systemd systems instead of writing a unit that won’t be used.
|
||||||
@@ -392,7 +385,7 @@ sudo ./scripts/install.sh --uninstall --purge --system
|
|||||||
./scripts/publish-self-contained.sh --no-clean ubuntu.24.04-x64
|
./scripts/publish-self-contained.sh --no-clean ubuntu.24.04-x64
|
||||||
```
|
```
|
||||||
|
|
||||||
**Output:** `src/DnsmasqWebUI/bin/Release/net9.0/<RID>/publish/`
|
**Output:** `src/DnsmasqWebUI/bin/Release/net10.0/<RID>/publish/`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -477,9 +470,9 @@ sudo ./scripts/install.sh --uninstall --purge --system
|
|||||||
|
|
||||||
**Codebase overview:**
|
**Codebase overview:**
|
||||||
|
|
||||||
- **Entry and config:** `Program.cs` wires the host; configuration (e.g. `Dnsmasq__*`) is in `Configuration/` (`DnsmasqOptions`, `ApplicationOptions`). Options are validated at startup.
|
- **Entry and config:** `Program.cs` wires the host; configuration (e.g. `Dnsmasq__*`) lives in `Models/Config/` (`DnsmasqOptions`, `ApplicationOptions`, `DnsmasqOptionsValidator`). Options are validated at startup.
|
||||||
- **Config and hosts:** Services in `Services/` and `Services/Abstractions/` read and write dnsmasq config and hosts. A **managed** config file and optional managed hosts file are written by the app; the main config must include the managed file (e.g. via a final `conf-file=` line). Caches (`ConfigSetCache`, `HostsCache`) keep in-memory snapshots and refresh on file changes or staleness.
|
- **Infrastructure:** Under `Infrastructure/`: **Client/** (HTTP API clients and `Abstractions/`), **Services/** and **Services/Abstractions/** (caches, config/hosts/leases services, reload, hosted services), **Parsers/** (dnsmasq config and hosts line parsers), **Helpers/Config/** and **Helpers/Http/** (option keys, encoding, tooltips, JSON options). A **managed** config file and optional managed hosts file are written by the app; the main config must include the managed file (e.g. via a final `conf-file=` line). Caches (`ConfigSetCache`, `HostsCache`) keep in-memory snapshots and refresh on file changes or staleness.
|
||||||
- **Parsers and models:** `Parsers/` parses dnsmasq config lines and files (`DnsmasqConfIncludeParser`, `DnsmasqConfDirectiveParser`, etc.). Models in `Models/` represent config sets, config, sources, DHCP entries, hosts, leases.
|
- **Models:** `Models/Config/` (options, validators, `DnsmasqConfLine`); `Models/Contracts/` (snapshots and DTOs such as `ConfigSetSnapshot`, `HostsSnapshot`, `ManagedConfigContent`, `ProcessRunResult`, `ReloadResult`); `Models/Dnsmasq/` (status, `SaveWithReloadResult`, and `EffectiveConfig/` for effective config and sources); `Models/Client/`, `Models/Dhcp/`, `Models/Hosts/` (UI and API DTOs).
|
||||||
- **API and UI:** `Controllers/` expose API endpoints; `Components/` contains Blazor Server components for config editor, hosts, DHCP, Dnsmasq status, and app settings. Static assets in `wwwroot/`.
|
- **API and UI:** `Controllers/` expose API endpoints; `Components/` contains Blazor Server components for config editor, hosts, DHCP, Dnsmasq status, and app settings. Static assets in `wwwroot/`.
|
||||||
- **Tests:** `DnsmasqWebUI.Tests` contains unit tests for parsers, config set service, config, and related logic. Run with `dotnet test`.
|
- **Tests:** `DnsmasqWebUI.Tests` contains unit tests for parsers, config set service, config, and related logic. Run with `dotnet test`.
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
# Run the app with real dnsmasq and several DHCP clients so hosts/leases are real.
|
# Run the app with real dnsmasq and several DHCP clients so hosts/leases are real.
|
||||||
# Some clients also make periodic DNS requests so the DNS cache and logs show activity.
|
# Some clients also make periodic DNS requests so the DNS cache and logs show activity.
|
||||||
# Prepare mount: ./scripts/prepare-test-mount.sh [--prepare-only | --no-build | --recreate | --source DIR | --mount DIR]
|
# Prepare mount: ./scripts/prepare-test-mount.sh [--minimal-conf | --prepare-only | ...]
|
||||||
# Or set TESTDATA_MOUNT to override the data volume (default: ./testdata-mount).
|
# Or set TESTDATA_MOUNT to override the data volume (default: ./testdata-mount).
|
||||||
|
# Set TEST_DNSMASQ_CONF to override main config path (default: /data/dnsmasq-test.conf; use /data/dnsmasq-test-minimal.conf for minimal).
|
||||||
#
|
#
|
||||||
# No systemd in container (dnsmasq runs as a process from entrypoint, like most dnsmasq images).
|
# No systemd in container (dnsmasq runs as a process from entrypoint, like most dnsmasq images).
|
||||||
# StatusShowCommand/LogsCommand use ps so the Service status / Recent logs sections show something
|
# StatusShowCommand/LogsCommand use ps so the Service status / Recent logs sections show something
|
||||||
@@ -18,14 +19,18 @@ services:
|
|||||||
cap_add:
|
cap_add:
|
||||||
- NET_ADMIN
|
- NET_ADMIN
|
||||||
environment:
|
environment:
|
||||||
DNSMASQ_CONF: /data/dnsmasq-test.conf
|
DNSMASQ_CONF: ${TEST_DNSMASQ_CONF:-/data/dnsmasq-test.conf}
|
||||||
Dnsmasq__MainConfigPath: /data/dnsmasq-test.conf
|
Dnsmasq__MainConfigPath: ${TEST_DNSMASQ_CONF:-/data/dnsmasq-test.conf}
|
||||||
Dnsmasq__ManagedFileName: zz-dnsmasq-webui.conf
|
Dnsmasq__ManagedFileName: zz-dnsmasq-webui.conf
|
||||||
|
# No systemd in container: restart by killing and re-running dnsmasq (same as entrypoint.sh). Config path must match DNSMASQ_CONF/MainConfigPath.
|
||||||
|
Dnsmasq__RestartCommand: "pkill -x dnsmasq || true; sleep 1; dnsmasq --test --conf-file=${TEST_DNSMASQ_CONF:-/data/dnsmasq-test.conf} && dnsmasq --conf-file=${TEST_DNSMASQ_CONF:-/data/dnsmasq-test.conf}"
|
||||||
Dnsmasq__ReloadCommand: "pkill -HUP -x dnsmasq"
|
Dnsmasq__ReloadCommand: "pkill -HUP -x dnsmasq"
|
||||||
Dnsmasq__StatusCommand: "pgrep -x dnsmasq"
|
Dnsmasq__StatusCommand: "pgrep -x dnsmasq"
|
||||||
# Simulated systemctl status + real logs (dnsmasq logs to /data/dnsmasq.log via log-facility in dnsmasq-test.conf)
|
# Simulated systemctl status + real logs (dnsmasq logs to /data/dnsmasq.log via log-facility in dnsmasq-test.conf)
|
||||||
Dnsmasq__StatusShowCommand: "/app/dnsmasq-status.sh"
|
Dnsmasq__StatusShowCommand: "/app/dnsmasq-status.sh"
|
||||||
Dnsmasq__LogsCommand: "tail -n 100 /data/dnsmasq.log 2>/dev/null || echo '(no log file yet)'"
|
Dnsmasq__LogsCommand: "tail -n 100 /data/dnsmasq.log 2>/dev/null || echo '(no log file yet)'"
|
||||||
|
# Persist runtime log level across container restarts
|
||||||
|
RuntimeOverrides__FilePath: "/data/appsettings.Overrides.json"
|
||||||
volumes:
|
volumes:
|
||||||
- ${TESTDATA_MOUNT:-./testdata-mount}:/data
|
- ${TESTDATA_MOUNT:-./testdata-mount}:/data
|
||||||
networks:
|
networks:
|
||||||
|
|||||||
@@ -1,12 +1,22 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# Simulates "systemctl status dnsmasq" output when run in a container without systemd.
|
# Simulates "systemctl status dnsmasq" output when run in a container without systemd.
|
||||||
# Uses ps/pgrep. Memory is RSS. Uptime line omitted; Active line has break after semicolon with continuation indented.
|
# Uses ps/pgrep. Memory is RSS. Uptime line omitted; Active line has break after semicolon with continuation indented.
|
||||||
|
# When dnsmasq is not running, runs dnsmasq --test to show config/startup errors (use DNSMASQ_CONF for config path).
|
||||||
|
|
||||||
pid=$(pgrep -x dnsmasq)
|
pid=$(pgrep -x dnsmasq)
|
||||||
if [ -z "$pid" ]; then
|
if [ -z "$pid" ]; then
|
||||||
echo "● dnsmasq.service - dnsmasq - A lightweight DHCP and caching DNS server"
|
echo "● dnsmasq.service - dnsmasq - A lightweight DHCP and caching DNS server"
|
||||||
echo " Loaded: (container, no systemd)"
|
echo " Loaded: (container, no systemd)"
|
||||||
echo " Active: inactive (dead)"
|
echo " Active: inactive (dead)"
|
||||||
|
conf="${DNSMASQ_CONF:-/etc/dnsmasq.conf}"
|
||||||
|
if [ -f "$conf" ]; then
|
||||||
|
err=$(dnsmasq --test --conf-file="$conf" 2>&1)
|
||||||
|
if [ -n "$err" ]; then
|
||||||
|
echo ""
|
||||||
|
echo " Config test (dnsmasq --test):"
|
||||||
|
echo "$err" | sed 's/^/ /'
|
||||||
|
fi
|
||||||
|
fi
|
||||||
echo ""
|
echo ""
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|||||||
Executable
+253
@@ -0,0 +1,253 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Extract per-option HTML from the dnsmasq man page for use as field help in the web UI.
|
||||||
|
#
|
||||||
|
# Runs a temporary Python (BeautifulSoup) container to fetch the page, parse the OPTIONS
|
||||||
|
# <DL>/<DT>/<DD> blocks, and write one .html file per option. The container is removed
|
||||||
|
# when done. If the page URL or structure changes, pass a new --url.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# ./scripts/extract-option-help.sh [--url URL] [--output-dir DIR]
|
||||||
|
#
|
||||||
|
# Requires: Docker (python:3-slim image will be pulled if missing)
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
DEFAULT_URL="https://thekelleys.org.uk/dnsmasq/docs/dnsmasq-man.html"
|
||||||
|
DEFAULT_OUTPUT_DIR="src/DnsmasqWebUI/wwwroot/option-help"
|
||||||
|
URL="$DEFAULT_URL"
|
||||||
|
OUTPUT_DIR="$DEFAULT_OUTPUT_DIR"
|
||||||
|
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
--url) URL="$2"; shift 2 ;;
|
||||||
|
--output-dir) OUTPUT_DIR="$2"; shift 2 ;;
|
||||||
|
*) echo "Unknown option: $1" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
[[ "$OUTPUT_DIR" != /* ]] && OUTPUT_DIR="$PWD/$OUTPUT_DIR"
|
||||||
|
mkdir -p "$OUTPUT_DIR"
|
||||||
|
|
||||||
|
SCRIPT_FILE="$(mktemp)"
|
||||||
|
trap 'rm -f "$SCRIPT_FILE"' EXIT
|
||||||
|
|
||||||
|
# Embed Python script (uses requests + BeautifulSoup; runs inside container)
|
||||||
|
cat << 'PYTHON_SCRIPT' > "$SCRIPT_FILE"
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
|
||||||
|
try:
|
||||||
|
import requests
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
except ImportError:
|
||||||
|
sys.stderr.write("Installing requests and beautifulsoup4...\n")
|
||||||
|
import subprocess
|
||||||
|
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "requests", "beautifulsoup4"])
|
||||||
|
import requests
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
|
||||||
|
OUT_DIR = "/out"
|
||||||
|
URL = os.environ.get("URL", "https://thekelleys.org.uk/dnsmasq/docs/dnsmasq-man.html")
|
||||||
|
|
||||||
|
# One per line; keep in sync with DnsmasqOptionTooltips / EffectiveConfigSections.
|
||||||
|
OPTION_KEYS = [
|
||||||
|
"no-hosts",
|
||||||
|
"addn-hosts",
|
||||||
|
"hostsdir",
|
||||||
|
"read-ethers",
|
||||||
|
"server",
|
||||||
|
"local",
|
||||||
|
"rev-server",
|
||||||
|
"address",
|
||||||
|
"resolv-file",
|
||||||
|
"no-resolv",
|
||||||
|
"domain-needed",
|
||||||
|
"port",
|
||||||
|
"log-queries",
|
||||||
|
"strict-order",
|
||||||
|
"all-servers",
|
||||||
|
"auth-ttl",
|
||||||
|
"edns-packet-max",
|
||||||
|
"query-port",
|
||||||
|
"port-limit",
|
||||||
|
"min-port",
|
||||||
|
"max-port",
|
||||||
|
"dns-loop-detect",
|
||||||
|
"stop-dns-rebind",
|
||||||
|
"rebind-localhost-ok",
|
||||||
|
"clear-on-reload",
|
||||||
|
"expand-hosts",
|
||||||
|
"bogus-priv",
|
||||||
|
"rebind-domain-ok",
|
||||||
|
"bogus-nxdomain",
|
||||||
|
"ignore-address",
|
||||||
|
"alias",
|
||||||
|
"filter-rr",
|
||||||
|
"filterwin2k",
|
||||||
|
"filter-A",
|
||||||
|
"filter-AAAA",
|
||||||
|
"localise-queries",
|
||||||
|
"fast-dns-retry",
|
||||||
|
"ipset",
|
||||||
|
"nftset",
|
||||||
|
"domain",
|
||||||
|
"cname",
|
||||||
|
"mx-host",
|
||||||
|
"srv-host",
|
||||||
|
"ptr-record",
|
||||||
|
"txt-record",
|
||||||
|
"naptr-record",
|
||||||
|
"host-record",
|
||||||
|
"dynamic-host",
|
||||||
|
"interface-name",
|
||||||
|
"mx-target",
|
||||||
|
"localmx",
|
||||||
|
"selfmx",
|
||||||
|
"dhcp-authoritative",
|
||||||
|
"dhcp-rapid-commit",
|
||||||
|
"leasefile-ro",
|
||||||
|
"dhcp-script",
|
||||||
|
"dhcp-leasefile",
|
||||||
|
"dhcp-lease-max",
|
||||||
|
"dhcp-ttl",
|
||||||
|
"dhcp-range",
|
||||||
|
"dhcp-host",
|
||||||
|
"dhcp-option",
|
||||||
|
"dhcp-option-force",
|
||||||
|
"dhcp-match",
|
||||||
|
"dhcp-mac",
|
||||||
|
"dhcp-name-match",
|
||||||
|
"dhcp-ignore-names",
|
||||||
|
"dhcp-hostsfile",
|
||||||
|
"dhcp-optsfile",
|
||||||
|
"dhcp-hostsdir",
|
||||||
|
"dhcp-boot",
|
||||||
|
"dhcp-ignore",
|
||||||
|
"dhcp-vendorclass",
|
||||||
|
"dhcp-userclass",
|
||||||
|
"ra-param",
|
||||||
|
"slaac",
|
||||||
|
"enable-tftp",
|
||||||
|
"tftp-secure",
|
||||||
|
"tftp-no-fail",
|
||||||
|
"tftp-no-blocksize",
|
||||||
|
"tftp-root",
|
||||||
|
"pxe-prompt",
|
||||||
|
"pxe-service",
|
||||||
|
"dnssec",
|
||||||
|
"dnssec-check-unsigned",
|
||||||
|
"proxy-dnssec",
|
||||||
|
"trust-anchor",
|
||||||
|
"cache-rr",
|
||||||
|
"cache-size",
|
||||||
|
"local-ttl",
|
||||||
|
"no-negcache",
|
||||||
|
"neg-ttl",
|
||||||
|
"max-ttl",
|
||||||
|
"max-cache-ttl",
|
||||||
|
"min-cache-ttl",
|
||||||
|
"no-poll",
|
||||||
|
"bind-interfaces",
|
||||||
|
"bind-dynamic",
|
||||||
|
"log-debug",
|
||||||
|
"log-async",
|
||||||
|
"local-service",
|
||||||
|
"interface",
|
||||||
|
"listen-address",
|
||||||
|
"except-interface",
|
||||||
|
"auth-server",
|
||||||
|
"no-dhcp-interface",
|
||||||
|
"no-dhcpv4-interface",
|
||||||
|
"no-dhcpv6-interface",
|
||||||
|
"pid-file",
|
||||||
|
"user",
|
||||||
|
"group",
|
||||||
|
"log-facility",
|
||||||
|
"enable-dbus",
|
||||||
|
"enable-ubus",
|
||||||
|
"enable-ra",
|
||||||
|
"log-dhcp",
|
||||||
|
"keep-in-foreground",
|
||||||
|
"no-daemon",
|
||||||
|
"conntrack",
|
||||||
|
]
|
||||||
|
|
||||||
|
long_opt_re = re.compile(r"--([a-z][a-z0-9-]*)(?:=[^,\s]*)?", re.IGNORECASE)
|
||||||
|
|
||||||
|
def option_names_from_dt(dt):
|
||||||
|
return [m.group(1).lower() for m in long_opt_re.finditer(dt.get_text())]
|
||||||
|
|
||||||
|
def main():
|
||||||
|
r = requests.get(URL, timeout=30)
|
||||||
|
r.raise_for_status()
|
||||||
|
soup = BeautifulSoup(r.text, "html.parser")
|
||||||
|
h2 = None
|
||||||
|
for el in soup.find_all("h2"):
|
||||||
|
if el.get_text(strip=True).upper() == "OPTIONS":
|
||||||
|
h2 = el
|
||||||
|
break
|
||||||
|
if not h2:
|
||||||
|
sys.stderr.write("Could not find OPTIONS H2\n")
|
||||||
|
sys.exit(1)
|
||||||
|
dl = h2.find_next("dl")
|
||||||
|
if not dl:
|
||||||
|
sys.stderr.write("Could not find DL after OPTIONS\n")
|
||||||
|
sys.exit(1)
|
||||||
|
# Build option -> (dt_html, dd_html) from raw HTML; split by <dt> so we get one block per option.
|
||||||
|
raw_dl = str(dl)
|
||||||
|
option_to_block = {}
|
||||||
|
blocks = re.split(r"<dt\b", raw_dl, flags=re.IGNORECASE)
|
||||||
|
for block in blocks[1:]:
|
||||||
|
p_dt = block.find("</dt>") if "</dt>" in block.lower() else len(block) + 1
|
||||||
|
m_dd = re.search(r"<dd\b", block, re.IGNORECASE)
|
||||||
|
p_dd = m_dd.start() if m_dd else len(block) + 1
|
||||||
|
end_pos = min(p_dt, p_dd)
|
||||||
|
if end_pos > len(block):
|
||||||
|
continue
|
||||||
|
dt_part = block[:end_pos].strip()
|
||||||
|
rest = block[end_pos:]
|
||||||
|
if rest.lower().startswith("</dt>"):
|
||||||
|
rest = rest[6:].lstrip()
|
||||||
|
if ">" in dt_part:
|
||||||
|
dt_part = dt_part.split(">", 1)[1]
|
||||||
|
dt_html = "<dt>" + dt_part + "</dt>"
|
||||||
|
dd_match = re.search(r"<dd\b[^>]*>(.*)", rest, re.DOTALL | re.IGNORECASE)
|
||||||
|
dd_body = dd_match.group(1) if dd_match else ""
|
||||||
|
dd_body = re.split(r"</dd>|<dt\s|<dt>", dd_body, flags=re.IGNORECASE)[0].strip()
|
||||||
|
dd_html = "<dd>" + dd_body + "</dd>" if dd_body else "<dd></dd>"
|
||||||
|
soup_dt = BeautifulSoup(dt_html, "html.parser").find("dt")
|
||||||
|
if not soup_dt:
|
||||||
|
continue
|
||||||
|
for n in option_names_from_dt(soup_dt):
|
||||||
|
if n not in option_to_block:
|
||||||
|
option_to_block[n] = (dt_html, dd_html)
|
||||||
|
os.makedirs(OUT_DIR, exist_ok=True)
|
||||||
|
written = 0
|
||||||
|
for key in OPTION_KEYS:
|
||||||
|
norm = key.lower()
|
||||||
|
if norm not in option_to_block:
|
||||||
|
continue
|
||||||
|
dt_html, dd_html = option_to_block[norm]
|
||||||
|
frag = "\n".join([dt_html, dd_html])
|
||||||
|
safe = re.sub(r"[^a-z0-9-]", "", norm) or key
|
||||||
|
path = os.path.join(OUT_DIR, f"{safe}.html")
|
||||||
|
with open(path, "w", encoding="utf-8") as f:
|
||||||
|
f.write(frag)
|
||||||
|
written += 1
|
||||||
|
print(f"Wrote {written} files to {OUT_DIR}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
PYTHON_SCRIPT
|
||||||
|
|
||||||
|
echo "Fetching man page and extracting option help (Docker python:3-slim) ..."
|
||||||
|
docker run --rm \
|
||||||
|
-v "$OUTPUT_DIR:/out" \
|
||||||
|
-v "$SCRIPT_FILE:/script.py:ro" \
|
||||||
|
-e "URL=$URL" \
|
||||||
|
-e "PIP_ROOT_USER_ACTION=ignore" \
|
||||||
|
python:3-slim \
|
||||||
|
sh -c "pip install -q requests beautifulsoup4 && python /script.py"
|
||||||
|
|
||||||
|
echo "Done. Files in $OUTPUT_DIR"
|
||||||
+71
-92
@@ -1,12 +1,10 @@
|
|||||||
#!/usr/bin/env sh
|
#!/usr/bin/env sh
|
||||||
# Download and install dnsmasq-webui from a GitHub release. Picks the binary
|
# Download and install dnsmasq-webui from a GitHub release. Picks the binary
|
||||||
# matching the current OS/arch (RID). Run from a clone or via:
|
# matching the current OS/arch (RID). Run from a clone or via:
|
||||||
# curl -sSL https://raw.githubusercontent.com/alexhopeoconnor/dnsmasq-webui/main/scripts/install.sh | sh
|
# curl -sSL https://raw.githubusercontent.com/alexhopeoconnor/dnsmasq-webui/master/scripts/install.sh | sh
|
||||||
# When run from a clone, repo is detected from git remote origin.
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
GITHUB_REPO="${GITHUB_REPO:-}"
|
GITHUB_REPO="alexhopeoconnor/dnsmasq-webui"
|
||||||
REPO_DEFAULT="${REPO_DEFAULT:-alexhopeoconnor/dnsmasq-webui}"
|
|
||||||
|
|
||||||
RELEASE_TAG=""
|
RELEASE_TAG=""
|
||||||
LIST=false
|
LIST=false
|
||||||
@@ -37,10 +35,6 @@ usage() {
|
|||||||
echo "Download and install dnsmasq-webui from a GitHub release for this machine's OS/arch."
|
echo "Download and install dnsmasq-webui from a GitHub release for this machine's OS/arch."
|
||||||
echo "Supports install, update, and switch-release (re-run with same --dir and different --version)."
|
echo "Supports install, update, and switch-release (re-run with same --dir and different --version)."
|
||||||
echo ""
|
echo ""
|
||||||
echo "Repo (when not in a clone):"
|
|
||||||
echo " --repo OWNER/REPO GitHub owner/repo. Or set GITHUB_REPO. Or set REPO_DEFAULT in the script."
|
|
||||||
echo " When run inside a git clone with origin, repo is detected automatically."
|
|
||||||
echo ""
|
|
||||||
echo "Release:"
|
echo "Release:"
|
||||||
echo " --list List available releases (tag, name, published_at) and exit."
|
echo " --list List available releases (tag, name, published_at) and exit."
|
||||||
echo " --version TAG Install from release TAG (e.g. v1.0.0). Default: latest."
|
echo " --version TAG Install from release TAG (e.g. v1.0.0). Default: latest."
|
||||||
@@ -72,7 +66,7 @@ usage() {
|
|||||||
echo " sudo $0 --uninstall --purge --system # also remove /opt/dnsmasq-webui"
|
echo " sudo $0 --uninstall --purge --system # also remove /opt/dnsmasq-webui"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Examples:"
|
echo "Examples:"
|
||||||
echo " $0 # Install latest (clone: auto repo; curl: use REPO_DEFAULT or --repo)"
|
echo " $0 # Install latest"
|
||||||
echo " $0 --update # Reinstall latest to default dir (upgrade)"
|
echo " $0 --update # Reinstall latest to default dir (upgrade)"
|
||||||
echo " $0 --version v1.0.0 # Install v1.0.0 to default dir"
|
echo " $0 --version v1.0.0 # Install v1.0.0 to default dir"
|
||||||
echo " $0 --dir /opt/dnsmasq-webui # Install to custom dir"
|
echo " $0 --dir /opt/dnsmasq-webui # Install to custom dir"
|
||||||
@@ -90,25 +84,26 @@ usage() {
|
|||||||
exit 0
|
exit 0
|
||||||
}
|
}
|
||||||
|
|
||||||
# Trim whitespace and carriage return (e.g. from script downloaded on Windows or with CRLF).
|
|
||||||
trim_repo() {
|
|
||||||
echo "$1" | tr -d '\r' | sed 's/^[[:space:]]*//; s/[[:space:]]*$//'
|
|
||||||
}
|
|
||||||
|
|
||||||
# Build CONFIG_VARS_FILE from env (DNSMASQ_WEBUI_*) then --set lines. Call before do_install when installing.
|
# Build CONFIG_VARS_FILE from env (DNSMASQ_WEBUI_*) then --set lines. Call before do_install when installing.
|
||||||
# Result: key=value per line (env first, then --set so --set overrides). Safe for values with = in them.
|
# Result: key=value per line (env first, then --set so --set overrides). Safe for values with = in them.
|
||||||
collect_config() {
|
collect_config() {
|
||||||
CONFIG_VARS_FILE="$(mktemp)"
|
CONFIG_VARS_FILE="$(mktemp)"
|
||||||
export CONFIG_VARS_FILE
|
export CONFIG_VARS_FILE
|
||||||
# Env vars: strip DNSMASQ_WEBUI_ prefix; key=value per line
|
# Env vars: strip DNSMASQ_WEBUI_ prefix; key=value per line. set +e so grep (no match) / read (EOF) / [ -f ] do not trigger exit.
|
||||||
env | grep '^DNSMASQ_WEBUI_' | while IFS= read -r line; do
|
set +e
|
||||||
key="${line%%=*}"
|
env | grep '^DNSMASQ_WEBUI_' > "${CONFIG_VARS_FILE}.env" 2>/dev/null
|
||||||
key="${key#DNSMASQ_WEBUI_}"
|
if [ -f "${CONFIG_VARS_FILE}.env" ] && [ -s "${CONFIG_VARS_FILE}.env" ]; then
|
||||||
value="${line#*=}"
|
while IFS= read -r line; do
|
||||||
printf '%s=%s\n' "$key" "$value" >> "$CONFIG_VARS_FILE"
|
key="${line%%=*}"
|
||||||
done
|
key="${key#DNSMASQ_WEBUI_}"
|
||||||
|
value="${line#*=}"
|
||||||
|
printf '%s=%s\n' "$key" "$value" >> "$CONFIG_VARS_FILE"
|
||||||
|
done < "${CONFIG_VARS_FILE}.env"
|
||||||
|
fi
|
||||||
|
rm -f "${CONFIG_VARS_FILE}.env"
|
||||||
|
set -e
|
||||||
# --set lines (last occurrence of each key wins when systemd reads the file)
|
# --set lines (last occurrence of each key wins when systemd reads the file)
|
||||||
[ -s "$CONFIG_SET_FILE" ] && cat "$CONFIG_SET_FILE" >> "$CONFIG_VARS_FILE"
|
[ -s "$CONFIG_SET_FILE" ] && cat "$CONFIG_SET_FILE" >> "$CONFIG_VARS_FILE" || true
|
||||||
}
|
}
|
||||||
|
|
||||||
# Write env file for the app/service. $1 = path. Adds ASPNETCORE_URLS=http://0.0.0.0:8080 if not in config (for service).
|
# Write env file for the app/service. $1 = path. Adds ASPNETCORE_URLS=http://0.0.0.0:8080 if not in config (for service).
|
||||||
@@ -139,30 +134,6 @@ write_env_file() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
# Detect owner/repo from git remote, REPO_DEFAULT, or require --repo/GITHUB_REPO.
|
|
||||||
detect_repo() {
|
|
||||||
if [ -n "$GITHUB_REPO" ]; then
|
|
||||||
GITHUB_REPO="$(trim_repo "$GITHUB_REPO")"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
if command -v git >/dev/null 2>&1 && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
|
||||||
origin="$(git remote get-url origin 2>/dev/null)" || true
|
|
||||||
if [ -n "$origin" ]; then
|
|
||||||
GITHUB_REPO="$(echo "$origin" | sed -E 's|^https://github\.com/||; s|^git@github\.com:||; s|\.git$||; s|/$||')"
|
|
||||||
GITHUB_REPO="$(trim_repo "$GITHUB_REPO")"
|
|
||||||
if [ -n "$GITHUB_REPO" ]; then
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
if [ -n "$REPO_DEFAULT" ]; then
|
|
||||||
GITHUB_REPO="$(trim_repo "$REPO_DEFAULT")"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
echo "Error: GitHub repo not set. Use --repo owner/repo, set GITHUB_REPO, or run from a clone. For the one-liner, set REPO_DEFAULT in the script." >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
# Require jq for parsing GitHub API JSON.
|
# Require jq for parsing GitHub API JSON.
|
||||||
check_jq() {
|
check_jq() {
|
||||||
if command -v jq >/dev/null 2>&1; then
|
if command -v jq >/dev/null 2>&1; then
|
||||||
@@ -172,6 +143,14 @@ check_jq() {
|
|||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Safely run jq on release JSON (avoids echo mangling). $1 = JSON, $2+ = jq args.
|
||||||
|
jq_release() {
|
||||||
|
local json
|
||||||
|
json="$1"
|
||||||
|
shift
|
||||||
|
printf '%s' "$json" | jq -r "$@"
|
||||||
|
}
|
||||||
|
|
||||||
# Detect RID (same logic as publish-self-contained.sh).
|
# Detect RID (same logic as publish-self-contained.sh).
|
||||||
detect_arch() {
|
detect_arch() {
|
||||||
case "$(uname -m)" in
|
case "$(uname -m)" in
|
||||||
@@ -219,6 +198,7 @@ print_env_detection() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
# GET release (latest or by tag). Output raw JSON to stdout.
|
# GET release (latest or by tag). Output raw JSON to stdout.
|
||||||
|
# Use </dev/null so curl does not consume stdin (script when run via curl | sh).
|
||||||
fetch_release() {
|
fetch_release() {
|
||||||
local api_url
|
local api_url
|
||||||
if [ -z "$RELEASE_TAG" ] || [ "$RELEASE_TAG" = "latest" ]; then
|
if [ -z "$RELEASE_TAG" ] || [ "$RELEASE_TAG" = "latest" ]; then
|
||||||
@@ -226,41 +206,46 @@ fetch_release() {
|
|||||||
else
|
else
|
||||||
api_url="https://api.github.com/repos/$GITHUB_REPO/releases/tags/$RELEASE_TAG"
|
api_url="https://api.github.com/repos/$GITHUB_REPO/releases/tags/$RELEASE_TAG"
|
||||||
fi
|
fi
|
||||||
resp="$(curl -sSL -A "dnsmasq-webui-install/1.0" -w "\n%{http_code}" "$api_url")"
|
resp="$(curl -sSL -A "dnsmasq-webui-install/1.0" -w "\n%{http_code}" "$api_url" </dev/null)"
|
||||||
code="$(echo "$resp" | tail -n1)"
|
code="$(printf '%s' "$resp" | tail -n1)"
|
||||||
body="$(echo "$resp" | sed '$d')"
|
body="$(printf '%s' "$resp" | sed '$d')"
|
||||||
if [ "$code" != "200" ]; then
|
if [ "$code" != "200" ]; then
|
||||||
echo "Error: GitHub API returned $code for $api_url" >&2
|
echo "Error: GitHub API returned $code for $api_url" >&2
|
||||||
echo "$body" | jq -r '.message // .' 2>/dev/null || echo "$body" >&2
|
body="$(printf '%s' "$body" | tr -d '\000-\011\013\014\016-\037')"
|
||||||
|
printf '%s' "$body" | jq -r '.message // .' 2>/dev/null || printf '%s' "$body" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "$body"
|
# GitHub API can return release body with unescaped control chars; jq rejects them. Strip control chars (keep \n \r).
|
||||||
|
body="$(printf '%s' "$body" | tr -d '\000-\011\013\014\016-\037')"
|
||||||
|
printf '%s' "$body"
|
||||||
}
|
}
|
||||||
|
|
||||||
# List releases and exit.
|
# List releases and exit.
|
||||||
list_releases() {
|
list_releases() {
|
||||||
check_jq
|
check_jq
|
||||||
detect_repo
|
|
||||||
api_url="https://api.github.com/repos/$GITHUB_REPO/releases?per_page=20"
|
api_url="https://api.github.com/repos/$GITHUB_REPO/releases?per_page=20"
|
||||||
resp="$(curl -sSL -A "dnsmasq-webui-install/1.0" -w "\n%{http_code}" "$api_url")"
|
resp="$(curl -sSL -A "dnsmasq-webui-install/1.0" -w "\n%{http_code}" "$api_url" </dev/null)"
|
||||||
code="$(echo "$resp" | tail -n1)"
|
code="$(printf '%s' "$resp" | tail -n1)"
|
||||||
body="$(echo "$resp" | sed '$d')"
|
body="$(printf '%s' "$resp" | sed '$d')"
|
||||||
if [ "$code" != "200" ]; then
|
if [ "$code" != "200" ]; then
|
||||||
echo "Error: GitHub API returned $code" >&2
|
echo "Error: GitHub API returned $code" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "$body" | jq -r '.[] | "\(.tag_name) \(.name) \(.published_at // .created_at)"'
|
body="$(printf '%s' "$body" | tr -d '\000-\011\013\014\016-\037')"
|
||||||
|
printf '%s' "$body" | jq -r '.[] | "\(.tag_name) \(.name) \(.published_at // .created_at)"'
|
||||||
exit 0
|
exit 0
|
||||||
}
|
}
|
||||||
|
|
||||||
# Find asset download URL whose name contains the given RID.
|
# Find asset download URL whose name contains the given RID. Output trimmed single line or empty.
|
||||||
find_asset_url() {
|
find_asset_url() {
|
||||||
local release_json rid
|
local release_json rid raw
|
||||||
release_json="$1"
|
release_json="$1"
|
||||||
rid="$2"
|
rid="$2"
|
||||||
echo "$release_json" | jq -r --arg rid "$rid" '
|
raw="$(jq_release "$release_json" --arg rid "$rid" '
|
||||||
.assets[] | select(.name | test($rid)) | .browser_download_url
|
.assets[] | select(.name | test($rid)) | .browser_download_url
|
||||||
' | head -n1
|
' | head -n1)"
|
||||||
|
# Trim CR and leading/trailing whitespace (defensive for API quirks)
|
||||||
|
printf '%s' "$raw" | tr -d '\r' | sed 's/^[[:space:]]*//; s/[[:space:]]*$//'
|
||||||
}
|
}
|
||||||
|
|
||||||
# Remove user systemd unit (stop, disable, rm file). No root. Safe if not present.
|
# Remove user systemd unit (stop, disable, rm file). No root. Safe if not present.
|
||||||
@@ -361,7 +346,7 @@ do_install_from_source() {
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
if ! command -v dotnet >/dev/null 2>&1; then
|
if ! command -v dotnet >/dev/null 2>&1; then
|
||||||
echo "Error: --build-from-source requires the .NET SDK. Install from https://dotnet.microsoft.com/download or your distro (e.g. apt install dotnet-sdk-9.0)." >&2
|
echo "Error: --build-from-source requires the .NET SDK. Install from https://dotnet.microsoft.com/download or your distro (e.g. apt install dotnet-sdk-10.0)." >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -386,7 +371,7 @@ do_install_from_source() {
|
|||||||
echo "Error: Could not determine RID from build output." >&2
|
echo "Error: Could not determine RID from build output." >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
publish_dir="$repo_root/src/DnsmasqWebUI/bin/Release/net9.0/$rid/publish"
|
publish_dir="$repo_root/src/DnsmasqWebUI/bin/Release/net10.0/$rid/publish"
|
||||||
if [ ! -d "$publish_dir" ] || [ ! -f "$publish_dir/DnsmasqWebUI" ]; then
|
if [ ! -d "$publish_dir" ] || [ ! -f "$publish_dir/DnsmasqWebUI" ]; then
|
||||||
echo "Error: Build output not found at $publish_dir" >&2
|
echo "Error: Build output not found at $publish_dir" >&2
|
||||||
exit 1
|
exit 1
|
||||||
@@ -440,8 +425,8 @@ do_install() {
|
|||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
echo "Installing dnsmasq-webui..."
|
||||||
check_jq
|
check_jq
|
||||||
detect_repo
|
|
||||||
|
|
||||||
if [ "$SYSTEM_INSTALL" = true ]; then
|
if [ "$SYSTEM_INSTALL" = true ]; then
|
||||||
if [ "$(id -u)" -ne 0 ]; then
|
if [ "$(id -u)" -ne 0 ]; then
|
||||||
@@ -468,20 +453,20 @@ do_install() {
|
|||||||
print_env_detection "$rid"
|
print_env_detection "$rid"
|
||||||
echo "Fetching release..."
|
echo "Fetching release..."
|
||||||
release_json="$(fetch_release)"
|
release_json="$(fetch_release)"
|
||||||
tag="$(echo "$release_json" | jq -r '.tag_name')"
|
tag="$(jq_release "$release_json" '.tag_name')"
|
||||||
echo "Release: $tag"
|
echo "Release: $tag"
|
||||||
url="$(find_asset_url "$release_json" "$rid" | tr -d '\r' | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')"
|
url="$(find_asset_url "$release_json" "$rid")"
|
||||||
if [ -z "$url" ] || [ "$url" = "null" ]; then
|
if [ -z "$url" ] || [ "$url" = "null" ]; then
|
||||||
echo "Error: No asset found for RID $rid in release $tag." >&2
|
echo "Error: No asset found for RID $rid in release $tag." >&2
|
||||||
echo "Available assets:" >&2
|
echo "Available assets:" >&2
|
||||||
echo "$release_json" | jq -r '.assets[].name' | sed 's/^/ /' >&2
|
jq_release "$release_json" '.assets[].name' | sed 's/^/ /' >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
mkdir -p "$INSTALL_DIR"
|
mkdir -p "$INSTALL_DIR"
|
||||||
tmpzip="${TMPDIR:-/tmp}/dnsmasq-webui-$rid.zip"
|
tmpzip="$(mktemp)"
|
||||||
echo "Downloading $url ..."
|
echo "Downloading $url ..."
|
||||||
curl -sSL -A "dnsmasq-webui-install/1.0" -o "$tmpzip" "$url"
|
curl -sSL -A "dnsmasq-webui-install/1.0" -o "$tmpzip" "$url" </dev/null
|
||||||
echo "Extracting to $INSTALL_DIR ..."
|
echo "Extracting to $INSTALL_DIR ..."
|
||||||
unzip -o -q "$tmpzip" -d "$INSTALL_DIR"
|
unzip -o -q "$tmpzip" -d "$INSTALL_DIR"
|
||||||
rm -f "$tmpzip"
|
rm -f "$tmpzip"
|
||||||
@@ -619,12 +604,6 @@ while [ $# -gt 0 ]; do
|
|||||||
-h|-?|--help)
|
-h|-?|--help)
|
||||||
usage
|
usage
|
||||||
;;
|
;;
|
||||||
--repo)
|
|
||||||
shift
|
|
||||||
[ $# -gt 0 ] || { echo "Error: --repo requires OWNER/REPO" >&2; exit 1; }
|
|
||||||
GITHUB_REPO="$1"
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
--list)
|
--list)
|
||||||
LIST=true
|
LIST=true
|
||||||
shift
|
shift
|
||||||
@@ -689,26 +668,26 @@ if [ "$PURGE" = true ] && [ "$UNINSTALL" != true ]; then
|
|||||||
echo "Error: --purge must be used with --uninstall. E.g. $0 --uninstall --purge" >&2
|
echo "Error: --purge must be used with --uninstall. E.g. $0 --uninstall --purge" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
if [ "$UNINSTALL" = true ]; then
|
if [ "$UNINSTALL" = true ]; then
|
||||||
if [ "$UPDATE" = true ] || [ -n "$RELEASE_TAG" ] || [ "$SERVICE" = true ] || [ "$BUILD_FROM_SOURCE" = true ]; then
|
if [ "$UPDATE" = true ] || [ -n "$RELEASE_TAG" ] || [ "$SERVICE" = true ] || [ "$BUILD_FROM_SOURCE" = true ]; then
|
||||||
echo "Error: --uninstall cannot be combined with install/update options (--version, --update, --service, --build-from-source). Run uninstall alone, then install if needed." >&2
|
echo "Error: --uninstall cannot be combined with install/update options (--version, --update, --service, --build-from-source). Run uninstall alone, then install if needed." >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
|
||||||
if [ "$LIST" = true ]; then
|
|
||||||
echo "Error: --uninstall cannot be combined with --list." >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
fi
|
||||||
if [ "$BUILD_FROM_SOURCE" = true ]; then
|
if [ "$LIST" = true ]; then
|
||||||
if [ "$LIST" = true ]; then
|
echo "Error: --uninstall cannot be combined with --list." >&2
|
||||||
echo "Error: --build-from-source cannot be combined with --list." >&2
|
exit 1
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
if [ -n "$RELEASE_TAG" ] || [ "$UPDATE" = true ]; then
|
|
||||||
echo "Error: --build-from-source builds from current source; do not use --version or --update." >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
fi
|
||||||
|
fi
|
||||||
|
if [ "$BUILD_FROM_SOURCE" = true ]; then
|
||||||
|
if [ "$LIST" = true ]; then
|
||||||
|
echo "Error: --build-from-source cannot be combined with --list." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [ -n "$RELEASE_TAG" ] || [ "$UPDATE" = true ]; then
|
||||||
|
echo "Error: --build-from-source builds from current source; do not use --version or --update." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
if [ "$LIST" = true ]; then
|
if [ "$LIST" = true ]; then
|
||||||
if [ "$UNINSTALL" = true ] || [ "$UPDATE" = true ] || [ "$SERVICE" = true ] || [ -n "$RELEASE_TAG" ]; then
|
if [ "$UNINSTALL" = true ] || [ "$UPDATE" = true ] || [ "$SERVICE" = true ] || [ -n "$RELEASE_TAG" ]; then
|
||||||
echo "Error: --list lists releases and exits; do not combine with install/uninstall options." >&2
|
echo "Error: --list lists releases and exits; do not combine with install/uninstall options." >&2
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
# (app + dnsmasq + DHCP client). See testdata/README.md and docker-compose.test.yml.
|
# (app + dnsmasq + DHCP client). See testdata/README.md and docker-compose.test.yml.
|
||||||
#
|
#
|
||||||
# What this script does:
|
# What this script does:
|
||||||
# Start (default): clear mount (unless --no-clear), sync source -> mount, clean up previous test data,
|
# Start (default): sync source -> mount (preserving existing unless --clear), clean up previous test data,
|
||||||
# then docker compose up -d [--build] [--force-recreate].
|
# then docker compose up -d [--build] [--force-recreate].
|
||||||
# --stop: docker compose down (stop and remove containers/networks).
|
# --stop: docker compose down (stop and remove containers/networks).
|
||||||
# --tidy: docker compose down, then clear the mount directory for a clean next run.
|
# --tidy: docker compose down, then clear the mount directory for a clean next run.
|
||||||
@@ -18,18 +18,19 @@ MOUNT_DIR=""
|
|||||||
PREPARE_ONLY=false
|
PREPARE_ONLY=false
|
||||||
BUILD=false
|
BUILD=false
|
||||||
RECREATE=false
|
RECREATE=false
|
||||||
NO_CLEAR=false
|
CLEAR=false
|
||||||
STOP=false
|
STOP=false
|
||||||
TIDY=false
|
TIDY=false
|
||||||
|
MINIMAL_CONF=false
|
||||||
|
|
||||||
usage() {
|
usage() {
|
||||||
echo "Usage: $0 [OPTIONS] [--]"
|
echo "Usage: $0 [OPTIONS] [--]"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Prepare the testdata mount directory and optionally start or stop the Docker test harness"
|
echo "Prepare the testdata mount directory and optionally start or stop the Docker test harness"
|
||||||
echo "(app + dnsmasq + DHCP client). By default: clear mount, sync testdata -> mount, then up -d (no rebuild)."
|
echo "(app + dnsmasq + DHCP client). By default: sync testdata -> mount (preserving existing), then up -d (no rebuild)."
|
||||||
echo ""
|
echo ""
|
||||||
echo "Steps (when starting):"
|
echo "Steps (when starting):"
|
||||||
echo " 1. Clear mount dir (unless --no-clear), then sync source -> mount."
|
echo " 1. Optionally clear mount dir (only with --clear), then sync source -> mount."
|
||||||
echo " 2. Clean up previous test data (e.g. managed config) so the harness starts clean."
|
echo " 2. Clean up previous test data (e.g. managed config) so the harness starts clean."
|
||||||
echo " 3. If not --prepare-only: docker compose -f $COMPOSE_FILE up -d [options]."
|
echo " 3. If not --prepare-only: docker compose -f $COMPOSE_FILE up -d [options]."
|
||||||
echo ""
|
echo ""
|
||||||
@@ -39,11 +40,12 @@ usage() {
|
|||||||
echo " Compose uses TESTDATA_MOUNT; script exports it if you use --mount."
|
echo " Compose uses TESTDATA_MOUNT; script exports it if you use --mount."
|
||||||
echo ""
|
echo ""
|
||||||
echo "Mount behaviour:"
|
echo "Mount behaviour:"
|
||||||
echo " (default) Clear mount dir completely, then sync. Use for a clean run."
|
echo " (default) Preserve mount dir; sync source over existing contents."
|
||||||
echo " --no-clear Do not clear mount dir; only sync over existing contents."
|
echo " --clear Clear mount dir completely before sync. Use for a clean run."
|
||||||
echo " Use to preserve leases or debug files between runs."
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "Compose behaviour:"
|
echo "Compose behaviour:"
|
||||||
|
echo " --minimal-conf Use minimal dnsmasq config (dnsmasq-test-minimal.conf) so effective"
|
||||||
|
echo " config has few readonly options; good for testing reload/restart failure flows."
|
||||||
echo " --prepare-only Only prepare the mount; do not run docker compose."
|
echo " --prepare-only Only prepare the mount; do not run docker compose."
|
||||||
echo " Use to inspect or edit the mount before starting containers."
|
echo " Use to inspect or edit the mount before starting containers."
|
||||||
echo " --build Pass --build to docker compose (rebuild images before starting)."
|
echo " --build Pass --build to docker compose (rebuild images before starting)."
|
||||||
@@ -62,19 +64,19 @@ usage() {
|
|||||||
echo ""
|
echo ""
|
||||||
echo "Examples:"
|
echo "Examples:"
|
||||||
echo " $0"
|
echo " $0"
|
||||||
echo " Full run: clear mount, sync testdata, start containers (no rebuild)."
|
echo " Sync testdata to mount (preserving existing), start containers (no rebuild)."
|
||||||
echo ""
|
echo ""
|
||||||
echo " $0 --build"
|
echo " $0 --build"
|
||||||
echo " Clear and sync, then rebuild images and start containers."
|
echo " Sync, rebuild images, and start containers."
|
||||||
echo ""
|
echo ""
|
||||||
echo " $0 --recreate"
|
echo " $0 --recreate"
|
||||||
echo " Clear and sync, then up -d --force-recreate (fresh containers)."
|
echo " Sync, then up -d --force-recreate (fresh containers)."
|
||||||
echo ""
|
echo ""
|
||||||
echo " $0 --no-clear"
|
echo " $0 --clear"
|
||||||
echo " Preserve mount contents, sync over it, start (no rebuild)."
|
echo " Clear mount, sync testdata, start (clean run, no rebuild)."
|
||||||
echo ""
|
echo ""
|
||||||
echo " $0 --prepare-only"
|
echo " $0 --prepare-only"
|
||||||
echo " Only clear and sync testdata -> testdata-mount; no containers."
|
echo " Only sync testdata -> testdata-mount; no containers."
|
||||||
echo " Then run: docker compose -f $COMPOSE_FILE up -d [--build]"
|
echo " Then run: docker compose -f $COMPOSE_FILE up -d [--build]"
|
||||||
echo ""
|
echo ""
|
||||||
echo " $0 --source myfixtures --mount mymount --prepare-only"
|
echo " $0 --source myfixtures --mount mymount --prepare-only"
|
||||||
@@ -86,6 +88,9 @@ usage() {
|
|||||||
echo ""
|
echo ""
|
||||||
echo " $0 --tidy"
|
echo " $0 --tidy"
|
||||||
echo " Stop harness and clear testdata-mount for a clean next run."
|
echo " Stop harness and clear testdata-mount for a clean next run."
|
||||||
|
echo ""
|
||||||
|
echo " $0 --minimal-conf"
|
||||||
|
echo " Use dnsmasq-test-minimal.conf (single file, few options) and start."
|
||||||
}
|
}
|
||||||
|
|
||||||
while [ $# -gt 0 ]; do
|
while [ $# -gt 0 ]; do
|
||||||
@@ -106,8 +111,8 @@ while [ $# -gt 0 ]; do
|
|||||||
MOUNT_DIR="$1"
|
MOUNT_DIR="$1"
|
||||||
shift
|
shift
|
||||||
;;
|
;;
|
||||||
--no-clear)
|
--clear)
|
||||||
NO_CLEAR=true
|
CLEAR=true
|
||||||
shift
|
shift
|
||||||
;;
|
;;
|
||||||
--prepare-only)
|
--prepare-only)
|
||||||
@@ -126,6 +131,10 @@ while [ $# -gt 0 ]; do
|
|||||||
RECREATE=true
|
RECREATE=true
|
||||||
shift
|
shift
|
||||||
;;
|
;;
|
||||||
|
--minimal-conf)
|
||||||
|
MINIMAL_CONF=true
|
||||||
|
shift
|
||||||
|
;;
|
||||||
--stop)
|
--stop)
|
||||||
STOP=true
|
STOP=true
|
||||||
shift
|
shift
|
||||||
@@ -189,7 +198,7 @@ docker compose -f "$COMPOSE_FILE" down
|
|||||||
|
|
||||||
mkdir -p "$MOUNT_DIR"
|
mkdir -p "$MOUNT_DIR"
|
||||||
|
|
||||||
if [ "$NO_CLEAR" = false ]; then
|
if [ "$CLEAR" = true ]; then
|
||||||
echo "Clearing mount directory: $MOUNT_DIR"
|
echo "Clearing mount directory: $MOUNT_DIR"
|
||||||
find "$MOUNT_DIR" -mindepth 1 -delete 2>/dev/null || true
|
find "$MOUNT_DIR" -mindepth 1 -delete 2>/dev/null || true
|
||||||
fi
|
fi
|
||||||
@@ -211,7 +220,11 @@ if [ "$PREPARE_ONLY" = true ]; then
|
|||||||
/*) MOUNT_EXPORT="$MOUNT_DIR" ;;
|
/*) MOUNT_EXPORT="$MOUNT_DIR" ;;
|
||||||
*) MOUNT_EXPORT="./$MOUNT_DIR" ;;
|
*) MOUNT_EXPORT="./$MOUNT_DIR" ;;
|
||||||
esac
|
esac
|
||||||
echo "To start the harness: TESTDATA_MOUNT=$MOUNT_EXPORT docker compose -f $COMPOSE_FILE up -d [--build]"
|
START_CMD="TESTDATA_MOUNT=$MOUNT_EXPORT docker compose -f $COMPOSE_FILE up -d [--build]"
|
||||||
|
if [ "$MINIMAL_CONF" = true ]; then
|
||||||
|
START_CMD="TESTDATA_MOUNT=$MOUNT_EXPORT TEST_DNSMASQ_CONF=/data/dnsmasq-test-minimal.conf docker compose -f $COMPOSE_FILE up -d [--build]"
|
||||||
|
fi
|
||||||
|
echo "To start the harness: $START_CMD"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -221,6 +234,11 @@ case "$MOUNT_DIR" in
|
|||||||
*) export TESTDATA_MOUNT="./$MOUNT_DIR" ;;
|
*) export TESTDATA_MOUNT="./$MOUNT_DIR" ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
|
if [ "$MINIMAL_CONF" = true ]; then
|
||||||
|
export TEST_DNSMASQ_CONF="/data/dnsmasq-test-minimal.conf"
|
||||||
|
echo "Using minimal config: $TEST_DNSMASQ_CONF"
|
||||||
|
fi
|
||||||
|
|
||||||
COMPOSE_CMD="docker compose -f $COMPOSE_FILE up -d"
|
COMPOSE_CMD="docker compose -f $COMPOSE_FILE up -d"
|
||||||
if [ "$BUILD" = true ]; then
|
if [ "$BUILD" = true ]; then
|
||||||
COMPOSE_CMD="$COMPOSE_CMD --build"
|
COMPOSE_CMD="$COMPOSE_CMD --build"
|
||||||
|
|||||||
@@ -59,14 +59,17 @@ default_rid() {
|
|||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Optional version override (e.g. v0.0.4 from CI tag). When set, passed to dotnet publish for assembly metadata.
|
||||||
|
VERSION_OVERRIDE=""
|
||||||
|
|
||||||
while [ $# -gt 0 ]; do
|
while [ $# -gt 0 ]; do
|
||||||
case "$1" in
|
case "$1" in
|
||||||
-h|-?|--help)
|
-h|-?|--help)
|
||||||
echo "Usage: $0 [OPTIONS] [RID]"
|
echo "Usage: $0 [OPTIONS] [RID] [VERSION]"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Build a self-contained folder publish for Linux. If RID is omitted, the script"
|
echo "Build a self-contained folder publish for Linux. If RID is omitted, the script"
|
||||||
echo "auto-detects from the current OS and architecture (recommended on Ubuntu and Alpine)."
|
echo "auto-detects from the current OS and architecture (recommended on Ubuntu and Alpine)."
|
||||||
echo "Pass options first, then RID if desired (e.g. $0 --trim linux-x64)."
|
echo "Pass options first, then RID, then optional VERSION (e.g. v0.0.4 from a release tag)."
|
||||||
echo ""
|
echo ""
|
||||||
echo "Options:"
|
echo "Options:"
|
||||||
echo " --trim Enable trimming (smaller output; can cause 404/routing issues with Blazor)"
|
echo " --trim Enable trimming (smaller output; can cause 404/routing issues with Blazor)"
|
||||||
@@ -85,7 +88,7 @@ while [ $# -gt 0 ]; do
|
|||||||
echo " ubuntu.24.04-x64 ubuntu.24.04-arm64"
|
echo " ubuntu.24.04-x64 ubuntu.24.04-arm64"
|
||||||
echo " ubuntu.22.04-x64 ubuntu.22.04-arm64"
|
echo " ubuntu.22.04-x64 ubuntu.22.04-arm64"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Output: src/DnsmasqWebUI/bin/Release/net9.0/<RID>/publish/"
|
echo "Output: src/DnsmasqWebUI/bin/Release/net10.0/<RID>/publish/"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Examples:"
|
echo "Examples:"
|
||||||
echo " $0 # Publish for current machine (auto-detect RID)"
|
echo " $0 # Publish for current machine (auto-detect RID)"
|
||||||
@@ -112,6 +115,10 @@ while [ $# -gt 0 ]; do
|
|||||||
*)
|
*)
|
||||||
RID="$1"
|
RID="$1"
|
||||||
shift
|
shift
|
||||||
|
if [ $# -gt 0 ] && [ -n "$1" ] && [ "${1#-}" = "$1" ]; then
|
||||||
|
VERSION_OVERRIDE="$1"
|
||||||
|
shift
|
||||||
|
fi
|
||||||
break
|
break
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
@@ -148,22 +155,32 @@ if [ "$CLEAN" = true ]; then
|
|||||||
dotnet clean "$PROJECT" -c Release -nologo -v q
|
dotnet clean "$PROJECT" -c Release -nologo -v q
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
VERSION_ARGS=""
|
||||||
|
if [ -n "$VERSION_OVERRIDE" ]; then
|
||||||
|
# Strip leading 'v' (e.g. v0.0.4 -> 0.0.4) for assembly metadata
|
||||||
|
VER="${VERSION_OVERRIDE#v}"
|
||||||
|
VERSION_ARGS="-p:Version=$VER -p:InformationalVersion=$VER"
|
||||||
|
echo "Using version: $VER (from $VERSION_OVERRIDE)"
|
||||||
|
fi
|
||||||
|
|
||||||
if [ "$TRIM" = true ]; then
|
if [ "$TRIM" = true ]; then
|
||||||
echo "Publishing self-contained (trimmed, folder) for $RID..."
|
echo "Publishing self-contained (trimmed, folder) for $RID..."
|
||||||
dotnet publish "$PROJECT" \
|
dotnet publish "$PROJECT" \
|
||||||
-c Release \
|
-c Release \
|
||||||
-r "$RID" \
|
-r "$RID" \
|
||||||
--self-contained true \
|
--self-contained true \
|
||||||
-p:PublishTrimmed=true
|
-p:PublishTrimmed=true \
|
||||||
|
$VERSION_ARGS
|
||||||
else
|
else
|
||||||
echo "Publishing self-contained (no trim, folder) for $RID..."
|
echo "Publishing self-contained (no trim, folder) for $RID..."
|
||||||
dotnet publish "$PROJECT" \
|
dotnet publish "$PROJECT" \
|
||||||
-c Release \
|
-c Release \
|
||||||
-r "$RID" \
|
-r "$RID" \
|
||||||
--self-contained true
|
--self-contained true \
|
||||||
|
$VERSION_ARGS
|
||||||
fi
|
fi
|
||||||
|
|
||||||
OUT_DIR="$REPO_ROOT/src/DnsmasqWebUI/bin/Release/net9.0/$RID/publish"
|
OUT_DIR="$REPO_ROOT/src/DnsmasqWebUI/bin/Release/net10.0/$RID/publish"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Done. Output: $OUT_DIR"
|
echo "Done. Output: $OUT_DIR"
|
||||||
echo "Run on this host: $OUT_DIR/DnsmasqWebUI"
|
echo "Run on this host: $OUT_DIR/DnsmasqWebUI"
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
using DnsmasqWebUI.Models.EffectiveConfig;
|
using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig;
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Tests;
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
@@ -17,25 +17,30 @@ public class ConfigValueSourceTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void GetReadOnlyTooltip_WhenReadOnlyWithoutLineNumber_ReturnsFileNameOnly()
|
public void GetReadOnlyTooltip_WhenReadOnlyWithoutLineNumber_ReturnsFileNameOnly()
|
||||||
{
|
{
|
||||||
var source = new ConfigValueSource("/etc/dnsmasq.d/02.conf", "02.conf", IsManaged: false, LineNumber: null);
|
var fileName = "02.conf";
|
||||||
|
var fullPath = $"/etc/dnsmasq.d/{fileName}";
|
||||||
|
var source = new ConfigValueSource(fullPath, fileName, IsManaged: false, LineNumber: null);
|
||||||
var tooltip = source.GetReadOnlyTooltip();
|
var tooltip = source.GetReadOnlyTooltip();
|
||||||
Assert.NotNull(tooltip);
|
Assert.NotNull(tooltip);
|
||||||
Assert.Contains("02.conf", tooltip);
|
Assert.Contains(fileName, tooltip);
|
||||||
Assert.Contains("readonly", tooltip);
|
Assert.Contains("readonly", tooltip);
|
||||||
Assert.Contains("/etc/dnsmasq.d/02.conf", tooltip);
|
Assert.Contains(fullPath, tooltip);
|
||||||
Assert.DoesNotContain("line", tooltip);
|
Assert.DoesNotContain("line", tooltip);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void GetReadOnlyTooltip_WhenReadOnlyWithLineNumber_IncludesLineNumber()
|
public void GetReadOnlyTooltip_WhenReadOnlyWithLineNumber_IncludesLineNumber()
|
||||||
{
|
{
|
||||||
var source = new ConfigValueSource("/etc/dnsmasq.d/02.conf", "02.conf", IsManaged: false, LineNumber: 3);
|
var fileName = "02.conf";
|
||||||
|
var fullPath = $"/etc/dnsmasq.d/{fileName}";
|
||||||
|
int? lineNumber = 3;
|
||||||
|
var source = new ConfigValueSource(fullPath, fileName, IsManaged: false, LineNumber: lineNumber);
|
||||||
var tooltip = source.GetReadOnlyTooltip();
|
var tooltip = source.GetReadOnlyTooltip();
|
||||||
Assert.NotNull(tooltip);
|
Assert.NotNull(tooltip);
|
||||||
Assert.Contains("02.conf", tooltip);
|
Assert.Contains(fileName, tooltip);
|
||||||
Assert.Contains("line 3", tooltip);
|
Assert.Contains($"line {lineNumber}", tooltip);
|
||||||
Assert.Contains("readonly", tooltip);
|
Assert.Contains("readonly", tooltip);
|
||||||
Assert.Contains("/etc/dnsmasq.d/02.conf", tooltip);
|
Assert.Contains(fullPath, tooltip);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
using DnsmasqWebUI.Models.Dhcp;
|
using DnsmasqWebUI.Models.Dhcp;
|
||||||
using DnsmasqWebUI.Parsers;
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Tests;
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
@@ -20,136 +20,219 @@ public class DnsmasqConfDhcpHostLineParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_BasicMacIpNameLease_Parses()
|
public void ParseLine_BasicMacIpNameLease_Parses()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("dhcp-host=aa:bb:cc:dd:ee:ff,192.168.1.10,testpc,infinite", 1);
|
string mac = "aa:bb:cc:dd:ee:ff";
|
||||||
|
string address = "192.168.1.10";
|
||||||
|
string name = "testpc";
|
||||||
|
string lease = "infinite";
|
||||||
|
|
||||||
|
var line = $"dhcp-host={mac},{address},{name},{lease}";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.False(e!.IsComment);
|
Assert.False(e!.IsComment);
|
||||||
Assert.False(e.IsDeleted);
|
Assert.False(e.IsDeleted);
|
||||||
Assert.Single(e.MacAddresses);
|
Assert.Single(e.MacAddresses);
|
||||||
Assert.Equal("aa:bb:cc:dd:ee:ff", e.MacAddresses[0]);
|
Assert.Equal(mac, e.MacAddresses[0]);
|
||||||
Assert.Equal("192.168.1.10", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
Assert.Equal("testpc", e.Name);
|
Assert.Equal(name, e.Name);
|
||||||
Assert.Equal("infinite", e.Lease);
|
Assert.Equal(lease, e.Lease);
|
||||||
Assert.Empty(e.Extra);
|
Assert.Empty(e.Extra);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_CommentedLine_ParsesWithIsComment()
|
public void ParseLine_CommentedLine_ParsesWithIsComment()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("#dhcp-host=aa:bb:cc:dd:ee:ff,192.168.1.10,testpc,infinite", 1);
|
string mac = "aa:bb:cc:dd:ee:ff";
|
||||||
|
string address = "192.168.1.10";
|
||||||
|
string name = "testpc";
|
||||||
|
string lease = "infinite";
|
||||||
|
|
||||||
|
var line = $"#dhcp-host={mac},{address},{name},{lease}";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.True(e!.IsComment);
|
Assert.True(e!.IsComment);
|
||||||
Assert.False(e.IsDeleted);
|
Assert.False(e.IsDeleted);
|
||||||
Assert.Single(e.MacAddresses);
|
Assert.Single(e.MacAddresses);
|
||||||
Assert.Equal("192.168.1.10", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_DeletedLine_ParsesWithIsDeleted()
|
public void ParseLine_DeletedLine_ParsesWithIsDeleted()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("##dhcp-host=aa:bb:cc:dd:ee:ff,192.168.1.10,oldpc", 1);
|
string mac = "aa:bb:cc:dd:ee:ff";
|
||||||
|
string address = "192.168.1.10";
|
||||||
|
string name = "oldpc";
|
||||||
|
|
||||||
|
var line = $"##dhcp-host={mac},{address},{name}";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.True(e!.IsComment);
|
Assert.True(e!.IsComment);
|
||||||
Assert.True(e.IsDeleted);
|
Assert.True(e.IsDeleted);
|
||||||
Assert.Single(e.MacAddresses);
|
Assert.Single(e.MacAddresses);
|
||||||
Assert.Equal("192.168.1.10", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_TrailingComment_ParsesComment()
|
public void ParseLine_TrailingComment_ParsesComment()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("dhcp-host=11:22:33:44:55:66,192.168.1.11,laptop,infinite # main laptop", 1);
|
string mac = "11:22:33:44:55:66";
|
||||||
|
string address = "192.168.1.11";
|
||||||
|
string name = "laptop";
|
||||||
|
string lease = "infinite";
|
||||||
|
string comment = "main laptop";
|
||||||
|
|
||||||
|
var line = $"dhcp-host={mac},{address},{name},{lease} # {comment}";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("main laptop", e!.Comment);
|
Assert.Equal(comment, e!.Comment);
|
||||||
Assert.Single(e.MacAddresses);
|
Assert.Single(e.MacAddresses);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_MultipleMacs_SameIp_Parses()
|
public void ParseLine_MultipleMacs_SameIp_Parses()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("dhcp-host=11:22:33:44:55:66,12:34:56:78:90:12,192.168.0.2", 1);
|
string mac1 = "11:22:33:44:55:66";
|
||||||
|
string mac2 = "12:34:56:78:90:12";
|
||||||
|
string address = "192.168.0.2";
|
||||||
|
|
||||||
|
var line = $"dhcp-host={mac1},{mac2},{address}";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal(2, e!.MacAddresses.Count);
|
Assert.Equal(2, e!.MacAddresses.Count);
|
||||||
Assert.Equal("11:22:33:44:55:66", e.MacAddresses[0]);
|
Assert.Equal(mac1, e.MacAddresses[0]);
|
||||||
Assert.Equal("12:34:56:78:90:12", e.MacAddresses[1]);
|
Assert.Equal(mac2, e.MacAddresses[1]);
|
||||||
Assert.Equal("192.168.0.2", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_WithSetTag_PutsInExtra()
|
public void ParseLine_WithSetTag_PutsInExtra()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("dhcp-host=AA:BB:CC:DD:CC:BB,redhost1,192.168.1.41,infinite,set:red", 1);
|
string mac = "AA:BB:CC:DD:CC:BB";
|
||||||
|
string name = "redhost1";
|
||||||
|
string address = "192.168.1.41";
|
||||||
|
string lease = "infinite";
|
||||||
|
string extraTag = "set:red";
|
||||||
|
|
||||||
|
var line = $"dhcp-host={mac},{name},{address},{lease},{extraTag}";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("192.168.1.41", e!.Address);
|
Assert.Equal(address, e!.Address);
|
||||||
Assert.Equal("redhost1", e.Name);
|
Assert.Equal(name, e.Name);
|
||||||
Assert.Contains(e.Extra, x => x == "set:red");
|
Assert.Contains(e.Extra, x => x == extraTag);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_HostnameOnly_Parses()
|
public void ParseLine_HostnameOnly_Parses()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("dhcp-host=lap,192.168.0.199", 1);
|
string name = "lap";
|
||||||
|
string address = "192.168.0.199";
|
||||||
|
|
||||||
|
var line = $"dhcp-host={name},{address}";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("lap", e!.Name);
|
Assert.Equal(name, e!.Name);
|
||||||
Assert.Equal("192.168.0.199", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
Assert.Empty(e.MacAddresses);
|
Assert.Empty(e.MacAddresses);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_Ignore_Parses()
|
public void ParseLine_Ignore_Parses()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("dhcp-host=00:20:e0:3b:13:af,ignore", 1);
|
string mac = "00:20:e0:3b:13:af";
|
||||||
|
|
||||||
|
var line = $"dhcp-host={mac},ignore";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.True(e!.Ignore);
|
Assert.True(e!.Ignore);
|
||||||
Assert.Single(e.MacAddresses);
|
Assert.Single(e.MacAddresses);
|
||||||
Assert.Equal("00:20:e0:3b:13:af", e.MacAddresses[0]);
|
Assert.Equal(mac, e.MacAddresses[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_NumericLease_Parses()
|
public void ParseLine_NumericLease_Parses()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("dhcp-host=aa:bb:cc:dd:ee:ff,192.168.1.10,pc,3600", 1);
|
string mac = "aa:bb:cc:dd:ee:ff";
|
||||||
|
string address = "192.168.1.10";
|
||||||
|
string name = "pc";
|
||||||
|
string lease = "3600";
|
||||||
|
|
||||||
|
var line = $"dhcp-host={mac},{address},{name},{lease}";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("3600", e!.Lease);
|
Assert.Equal(lease, e!.Lease);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_WithIdClient_PutsInExtra()
|
public void ParseLine_WithIdClient_PutsInExtra()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("dhcp-host=id:01:02:03:04,192.168.1.50,myhost", 1);
|
string idPart = "id:01:02:03:04";
|
||||||
|
string address = "192.168.1.50";
|
||||||
|
string name = "myhost";
|
||||||
|
|
||||||
|
var line = $"dhcp-host={idPart},{address},{name}";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Contains(e!.Extra, x => x.StartsWith("id:", StringComparison.OrdinalIgnoreCase));
|
Assert.Contains(e!.Extra, x => x.StartsWith("id:", StringComparison.OrdinalIgnoreCase));
|
||||||
Assert.Equal("192.168.1.50", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_Roundtrip_Basic()
|
public void ToLine_Roundtrip_Basic()
|
||||||
{
|
{
|
||||||
var line = "dhcp-host=aa:bb:cc:dd:ee:ff,192.168.1.10,testpc,infinite";
|
string mac = "aa:bb:cc:dd:ee:ff";
|
||||||
|
string address = "192.168.1.10";
|
||||||
|
string name = "testpc";
|
||||||
|
string lease = "infinite";
|
||||||
|
|
||||||
|
var line = $"dhcp-host={mac},{address},{name},{lease}";
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
var back = DnsmasqConfDhcpHostLineParser.ToLine(e!);
|
var back = DnsmasqConfDhcpHostLineParser.ToLine(e!);
|
||||||
Assert.StartsWith("dhcp-host=", back);
|
Assert.StartsWith("dhcp-host=", back);
|
||||||
Assert.Contains("aa:bb:cc:dd:ee:ff", back);
|
Assert.Contains(mac, back);
|
||||||
Assert.Contains("192.168.1.10", back);
|
Assert.Contains(address, back);
|
||||||
Assert.Contains("testpc", back);
|
Assert.Contains(name, back);
|
||||||
Assert.Contains("infinite", back);
|
Assert.Contains(lease, back);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_Roundtrip_WithComment()
|
public void ToLine_Roundtrip_WithComment()
|
||||||
{
|
{
|
||||||
var line = "dhcp-host=11:22:33:44:55:66,192.168.1.11,laptop,infinite # main laptop";
|
string mac = "11:22:33:44:55:66";
|
||||||
|
string address = "192.168.1.11";
|
||||||
|
string name = "laptop";
|
||||||
|
string lease = "infinite";
|
||||||
|
string comment = "main laptop";
|
||||||
|
|
||||||
|
var line = $"dhcp-host={mac},{address},{name},{lease} # {comment}";
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
var back = DnsmasqConfDhcpHostLineParser.ToLine(e!);
|
var back = DnsmasqConfDhcpHostLineParser.ToLine(e!);
|
||||||
Assert.StartsWith("dhcp-host=", back);
|
Assert.StartsWith("dhcp-host=", back);
|
||||||
Assert.Contains("main laptop", back);
|
Assert.Contains(comment, back);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_CommentedEntry_Prefix()
|
public void ToLine_CommentedEntry_Prefix()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("#dhcp-host=aa:bb:cc:dd:ee:ff,192.168.1.10,testpc", 1);
|
string mac = "aa:bb:cc:dd:ee:ff";
|
||||||
|
string address = "192.168.1.10";
|
||||||
|
string name = "testpc";
|
||||||
|
|
||||||
|
var line = $"#dhcp-host={mac},{address},{name}";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
var back = DnsmasqConfDhcpHostLineParser.ToLine(e!);
|
var back = DnsmasqConfDhcpHostLineParser.ToLine(e!);
|
||||||
Assert.StartsWith("#dhcp-host=", back);
|
Assert.StartsWith("#dhcp-host=", back);
|
||||||
@@ -158,7 +241,13 @@ public class DnsmasqConfDhcpHostLineParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_DeletedEntry_DoubleHash()
|
public void ToLine_DeletedEntry_DoubleHash()
|
||||||
{
|
{
|
||||||
var e = DnsmasqConfDhcpHostLineParser.ParseLine("##dhcp-host=aa:bb:cc:dd:ee:ff,192.168.1.10,old", 1);
|
string mac = "aa:bb:cc:dd:ee:ff";
|
||||||
|
string address = "192.168.1.10";
|
||||||
|
string name = "old";
|
||||||
|
|
||||||
|
var line = $"##dhcp-host={mac},{address},{name}";
|
||||||
|
var e = DnsmasqConfDhcpHostLineParser.ParseLine(line, 1);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
var back = DnsmasqConfDhcpHostLineParser.ToLine(e!);
|
var back = DnsmasqConfDhcpHostLineParser.ToLine(e!);
|
||||||
Assert.StartsWith("##dhcp-host=", back);
|
Assert.StartsWith("##dhcp-host=", back);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
using DnsmasqWebUI.Models.Config;
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
using DnsmasqWebUI.Parsers;
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Tests;
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
@@ -26,10 +26,12 @@ public class DnsmasqConfDirectiveParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void TryParseKeyValue_KeyValue_ReturnsKeyAndValue()
|
public void TryParseKeyValue_KeyValue_ReturnsKeyAndValue()
|
||||||
{
|
{
|
||||||
var kv = DnsmasqConfDirectiveParser.TryParseKeyValue("port=53");
|
var value = "53";
|
||||||
|
var line = $"port={value}";
|
||||||
|
var kv = DnsmasqConfDirectiveParser.TryParseKeyValue(line);
|
||||||
Assert.NotNull(kv);
|
Assert.NotNull(kv);
|
||||||
Assert.Equal(DnsmasqConfKeys.Port, kv!.Value.key);
|
Assert.Equal(DnsmasqConfKeys.Port, kv!.Value.key);
|
||||||
Assert.Equal("53", kv.Value.value);
|
Assert.Equal(value, kv.Value.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -50,16 +52,42 @@ public class DnsmasqConfDirectiveParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void StripComment_CommentAfterSpace_StripsToEnd()
|
public void StripComment_CommentAfterSpace_StripsToEnd()
|
||||||
{
|
{
|
||||||
Assert.Equal("port=53", DnsmasqConfDirectiveParser.StripComment("port=53 # DNS port"));
|
var before = "port=53";
|
||||||
Assert.Equal("port=53", DnsmasqConfDirectiveParser.StripComment("port=53 # comment"));
|
var comment1 = " DNS port";
|
||||||
|
var comment2 = " comment";
|
||||||
|
Assert.Equal(before, DnsmasqConfDirectiveParser.StripComment(before + " #" + comment1));
|
||||||
|
Assert.Equal(before, DnsmasqConfDirectiveParser.StripComment(before + " #" + comment2));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void TryParseKeyValue_LineWithComment_ValueExcludesComment()
|
public void TryParseKeyValue_LineWithComment_ValueExcludesComment()
|
||||||
{
|
{
|
||||||
var kv = DnsmasqConfDirectiveParser.TryParseKeyValue("port=53 # DNS port");
|
var value = "53";
|
||||||
|
var comment = " DNS port";
|
||||||
|
var line = $"port={value} #{comment}";
|
||||||
|
var kv = DnsmasqConfDirectiveParser.TryParseKeyValue(line);
|
||||||
Assert.NotNull(kv);
|
Assert.NotNull(kv);
|
||||||
Assert.Equal(DnsmasqConfKeys.Port, kv!.Value.key);
|
Assert.Equal(DnsmasqConfKeys.Port, kv!.Value.key);
|
||||||
Assert.Equal("53", kv.Value.value);
|
Assert.Equal(value, kv.Value.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TryParseKeyValue_ValueContainsEquals_ParsesFirstEqualsAsKeyValueSeparator()
|
||||||
|
{
|
||||||
|
var line = "server=/local/1.2.3.4";
|
||||||
|
var kv = DnsmasqConfDirectiveParser.TryParseKeyValue(line);
|
||||||
|
Assert.NotNull(kv);
|
||||||
|
Assert.Equal("server", kv!.Value.key);
|
||||||
|
Assert.Equal("/local/1.2.3.4", kv.Value.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TryParseKeyValue_ErrorOverload_InvalidLine_ReturnsFalseAndSetsError()
|
||||||
|
{
|
||||||
|
// KeyValueLine requires at least one key character before '='; "=no-key" has no key and fails.
|
||||||
|
var ok = DnsmasqConfDirectiveParser.TryParseKeyValue("=no-key", out var kv, out var error, out var errorPosition);
|
||||||
|
Assert.False(ok);
|
||||||
|
Assert.NotNull(error);
|
||||||
|
Assert.True(errorPosition.Absolute >= 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using DnsmasqWebUI.Models.Config;
|
using DnsmasqWebUI.Models.Config;
|
||||||
using DnsmasqWebUI.Models.Dhcp;
|
using DnsmasqWebUI.Models.Dhcp;
|
||||||
using DnsmasqWebUI.Parsers;
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Tests;
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
@@ -19,73 +19,89 @@ public class DnsmasqConfFileLineParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ParseFile_BlankLine_BlankKind()
|
public void ParseFile_BlankLine_BlankKind()
|
||||||
{
|
{
|
||||||
var lines = DnsmasqConfFileLineParser.ParseFile([""]);
|
var raw = "";
|
||||||
|
var lines = DnsmasqConfFileLineParser.ParseFile([raw]);
|
||||||
Assert.Single(lines);
|
Assert.Single(lines);
|
||||||
var blank = Assert.IsType<BlankLine>(lines[0]);
|
var blank = Assert.IsType<BlankLine>(lines[0]);
|
||||||
Assert.Equal(1, blank.LineNumber);
|
Assert.Equal(1, blank.LineNumber);
|
||||||
Assert.Equal("", blank.RawLine);
|
Assert.Equal(raw, blank.RawLine);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseFile_BlankLineWithSpaces_BlankKind()
|
public void ParseFile_BlankLineWithSpaces_BlankKind()
|
||||||
{
|
{
|
||||||
var lines = DnsmasqConfFileLineParser.ParseFile([" \t "]);
|
var raw = " \t ";
|
||||||
|
var lines = DnsmasqConfFileLineParser.ParseFile([raw]);
|
||||||
Assert.Single(lines);
|
Assert.Single(lines);
|
||||||
var blank = Assert.IsType<BlankLine>(lines[0]);
|
var blank = Assert.IsType<BlankLine>(lines[0]);
|
||||||
Assert.Equal(" \t ", blank.RawLine);
|
Assert.Equal(raw, blank.RawLine);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseFile_CommentLine_CommentKind()
|
public void ParseFile_CommentLine_CommentKind()
|
||||||
{
|
{
|
||||||
var lines = DnsmasqConfFileLineParser.ParseFile(["# Not managed by this app."]);
|
var commentLine = "# Not managed by this app.";
|
||||||
|
var lines = DnsmasqConfFileLineParser.ParseFile([commentLine]);
|
||||||
Assert.Single(lines);
|
Assert.Single(lines);
|
||||||
var comment = Assert.IsType<CommentLine>(lines[0]);
|
var comment = Assert.IsType<CommentLine>(lines[0]);
|
||||||
Assert.Equal(1, comment.LineNumber);
|
Assert.Equal(1, comment.LineNumber);
|
||||||
Assert.Equal("# Not managed by this app.", comment.RawLine);
|
Assert.Equal(commentLine, comment.RawLine);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseFile_OtherDirective_OtherKind()
|
public void ParseFile_OtherDirective_OtherKind()
|
||||||
{
|
{
|
||||||
var lines = DnsmasqConfFileLineParser.ParseFile(["domain=local"]);
|
var raw = "domain=local";
|
||||||
|
var lines = DnsmasqConfFileLineParser.ParseFile([raw]);
|
||||||
Assert.Single(lines);
|
Assert.Single(lines);
|
||||||
var other = Assert.IsType<OtherLine>(lines[0]);
|
var other = Assert.IsType<OtherLine>(lines[0]);
|
||||||
Assert.Equal("domain=local", other.RawLine);
|
Assert.Equal(raw, other.RawLine);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseFile_AddnHostsLine_AddnHostsKind()
|
public void ParseFile_AddnHostsLine_AddnHostsKind()
|
||||||
{
|
{
|
||||||
var lines = DnsmasqConfFileLineParser.ParseFile(["addn-hosts=/var/lib/dnsmasq/hosts"]);
|
var path = "/var/lib/dnsmasq/hosts";
|
||||||
|
var line = $"addn-hosts={path}";
|
||||||
|
var lines = DnsmasqConfFileLineParser.ParseFile([line]);
|
||||||
Assert.Single(lines);
|
Assert.Single(lines);
|
||||||
var addn = Assert.IsType<AddnHostsLine>(lines[0]);
|
var addn = Assert.IsType<AddnHostsLine>(lines[0]);
|
||||||
Assert.Equal("/var/lib/dnsmasq/hosts", addn.AddnHostsPath);
|
Assert.Equal(path, addn.AddnHostsPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_AddnHosts_EmitsAddnHostsLine()
|
public void ToLine_AddnHosts_EmitsAddnHostsLine()
|
||||||
{
|
{
|
||||||
var line = new AddnHostsLine { LineNumber = 1, AddnHostsPath = "/etc/hosts" };
|
var path = "/etc/hosts";
|
||||||
Assert.Equal("addn-hosts=/etc/hosts", DnsmasqConfFileLineParser.ToLine(line));
|
var line = new AddnHostsLine { LineNumber = 1, AddnHostsPath = path };
|
||||||
|
Assert.Equal($"addn-hosts={path}", DnsmasqConfFileLineParser.ToLine(line));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseFile_DhcpHostLine_DhcpHostKind()
|
public void ParseFile_DhcpHostLine_DhcpHostKind()
|
||||||
{
|
{
|
||||||
var lines = DnsmasqConfFileLineParser.ParseFile(["dhcp-host=aa:bb:cc:dd:ee:ff,192.168.1.10,testpc,infinite"]);
|
string mac = "aa:bb:cc:dd:ee:ff";
|
||||||
|
string address = "192.168.1.10";
|
||||||
|
string name = "testpc";
|
||||||
|
string lease = "infinite";
|
||||||
|
var line = $"dhcp-host={mac},{address},{name},{lease}";
|
||||||
|
var lines = DnsmasqConfFileLineParser.ParseFile([line]);
|
||||||
Assert.Single(lines);
|
Assert.Single(lines);
|
||||||
var dhcpLine = Assert.IsType<DhcpHostLine>(lines[0]);
|
var dhcpLine = Assert.IsType<DhcpHostLine>(lines[0]);
|
||||||
Assert.Single(dhcpLine.DhcpHost.MacAddresses);
|
Assert.Single(dhcpLine.DhcpHost.MacAddresses);
|
||||||
Assert.Equal("aa:bb:cc:dd:ee:ff", dhcpLine.DhcpHost.MacAddresses[0]);
|
Assert.Equal(mac, dhcpLine.DhcpHost.MacAddresses[0]);
|
||||||
Assert.Equal("192.168.1.10", dhcpLine.DhcpHost.Address);
|
Assert.Equal(address, dhcpLine.DhcpHost.Address);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseFile_CommentedDhcpHost_TreatedAsComment()
|
public void ParseFile_CommentedDhcpHost_TreatedAsComment()
|
||||||
{
|
{
|
||||||
// Parser treats any line starting with # as Comment (does not parse dhcp-host content)
|
// Parser treats any line starting with # as Comment (does not parse dhcp-host content)
|
||||||
var lines = DnsmasqConfFileLineParser.ParseFile(["#dhcp-host=aa:bb:cc:dd:ee:ff,192.168.1.10,oldpc"]);
|
string mac = "aa:bb:cc:dd:ee:ff";
|
||||||
|
string address = "192.168.1.10";
|
||||||
|
string name = "oldpc";
|
||||||
|
var line = $"#dhcp-host={mac},{address},{name}";
|
||||||
|
var lines = DnsmasqConfFileLineParser.ParseFile([line]);
|
||||||
Assert.Single(lines);
|
Assert.Single(lines);
|
||||||
Assert.Equal(DnsmasqConfLineKind.Comment, lines[0].Kind);
|
Assert.Equal(DnsmasqConfLineKind.Comment, lines[0].Kind);
|
||||||
}
|
}
|
||||||
@@ -93,13 +109,21 @@ public class DnsmasqConfFileLineParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ParseFile_MixedFile_ParsesAll()
|
public void ParseFile_MixedFile_ParsesAll()
|
||||||
{
|
{
|
||||||
|
var domainLine = "domain=local";
|
||||||
|
string dhcpMac = "11:22:33:44:55:66";
|
||||||
|
string dhcpAddress = "192.168.1.11";
|
||||||
|
string dhcpName = "laptop";
|
||||||
|
string dhcpLease = "infinite";
|
||||||
|
var rangeLine = "dhcp-range=192.168.1.100,192.168.1.200";
|
||||||
|
var dhcpLine = $"dhcp-host={dhcpMac},{dhcpAddress},{dhcpName},{dhcpLease}";
|
||||||
|
|
||||||
var input = new[]
|
var input = new[]
|
||||||
{
|
{
|
||||||
"# Sample config",
|
"# Sample config",
|
||||||
"",
|
"",
|
||||||
"domain=local",
|
domainLine,
|
||||||
"dhcp-host=11:22:33:44:55:66,192.168.1.11,laptop,infinite",
|
dhcpLine,
|
||||||
"dhcp-range=192.168.1.100,192.168.1.200"
|
rangeLine
|
||||||
};
|
};
|
||||||
var lines = DnsmasqConfFileLineParser.ParseFile(input);
|
var lines = DnsmasqConfFileLineParser.ParseFile(input);
|
||||||
Assert.Equal(5, lines.Count);
|
Assert.Equal(5, lines.Count);
|
||||||
@@ -107,48 +131,55 @@ public class DnsmasqConfFileLineParserTests
|
|||||||
Assert.IsType<CommentLine>(lines[0]);
|
Assert.IsType<CommentLine>(lines[0]);
|
||||||
Assert.IsType<BlankLine>(lines[1]);
|
Assert.IsType<BlankLine>(lines[1]);
|
||||||
var other2 = Assert.IsType<OtherLine>(lines[2]);
|
var other2 = Assert.IsType<OtherLine>(lines[2]);
|
||||||
Assert.Equal("domain=local", other2.RawLine);
|
Assert.Equal(domainLine, other2.RawLine);
|
||||||
var dhcp3 = Assert.IsType<DhcpHostLine>(lines[3]);
|
var dhcp3 = Assert.IsType<DhcpHostLine>(lines[3]);
|
||||||
Assert.Equal("192.168.1.11", dhcp3.DhcpHost.Address);
|
Assert.Equal(dhcpAddress, dhcp3.DhcpHost.Address);
|
||||||
var other4 = Assert.IsType<OtherLine>(lines[4]);
|
var other4 = Assert.IsType<OtherLine>(lines[4]);
|
||||||
Assert.Equal("dhcp-range=192.168.1.100,192.168.1.200", other4.RawLine);
|
Assert.Equal(rangeLine, other4.RawLine);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_Blank_PreservesRawLine()
|
public void ToLine_Blank_PreservesRawLine()
|
||||||
{
|
{
|
||||||
var line = new BlankLine { LineNumber = 1, RawLine = " " };
|
var raw = " ";
|
||||||
Assert.Equal(" ", DnsmasqConfFileLineParser.ToLine(line));
|
var line = new BlankLine { LineNumber = 1, RawLine = raw };
|
||||||
|
Assert.Equal(raw, DnsmasqConfFileLineParser.ToLine(line));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_Comment_PreservesRawLine()
|
public void ToLine_Comment_PreservesRawLine()
|
||||||
{
|
{
|
||||||
var line = new CommentLine { LineNumber = 1, RawLine = "# comment" };
|
var raw = "# comment";
|
||||||
Assert.Equal("# comment", DnsmasqConfFileLineParser.ToLine(line));
|
var line = new CommentLine { LineNumber = 1, RawLine = raw };
|
||||||
|
Assert.Equal(raw, DnsmasqConfFileLineParser.ToLine(line));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_Other_PreservesRawLine()
|
public void ToLine_Other_PreservesRawLine()
|
||||||
{
|
{
|
||||||
var line = new OtherLine { LineNumber = 1, RawLine = "domain=local" };
|
var raw = "domain=local";
|
||||||
Assert.Equal("domain=local", DnsmasqConfFileLineParser.ToLine(line));
|
var line = new OtherLine { LineNumber = 1, RawLine = raw };
|
||||||
|
Assert.Equal(raw, DnsmasqConfFileLineParser.ToLine(line));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_DhcpHost_SerializesViaDhcpHostLineParser()
|
public void ToLine_DhcpHost_SerializesViaDhcpHostLineParser()
|
||||||
{
|
{
|
||||||
|
string mac = "aa:bb:cc:dd:ee:ff";
|
||||||
|
string address = "192.168.1.10";
|
||||||
|
string name = "testpc";
|
||||||
|
string lease = "infinite";
|
||||||
var dhcp = new DhcpHostEntry
|
var dhcp = new DhcpHostEntry
|
||||||
{
|
{
|
||||||
LineNumber = 1,
|
LineNumber = 1,
|
||||||
MacAddresses = ["aa:bb:cc:dd:ee:ff"],
|
MacAddresses = [mac],
|
||||||
Address = "192.168.1.10",
|
Address = address,
|
||||||
Name = "testpc",
|
Name = name,
|
||||||
Lease = "infinite"
|
Lease = lease
|
||||||
};
|
};
|
||||||
var line = new DhcpHostLine { LineNumber = 1, DhcpHost = dhcp };
|
var line = new DhcpHostLine { LineNumber = 1, DhcpHost = dhcp };
|
||||||
var back = DnsmasqConfFileLineParser.ToLine(line);
|
var back = DnsmasqConfFileLineParser.ToLine(line);
|
||||||
Assert.Equal("dhcp-host=aa:bb:cc:dd:ee:ff, testpc, 192.168.1.10, infinite", back);
|
Assert.Equal($"dhcp-host={mac}, {name}, {address}, {lease}", back);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -0,0 +1,329 @@
|
|||||||
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>Parser semantics: flags (option present/absent/with value), last-wins, case-sensitive, path order.</summary>
|
||||||
|
public class DnsmasqConfIncludeParserCoreBehaviourTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_OptionPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-flag-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(conf, "expand-hosts\nno-resolv\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.ExpandHosts);
|
||||||
|
Assert.True(result);
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NoResolv));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_OptionAbsent_ReturnsFalse()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-flag-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(conf, "port=53\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NoHosts);
|
||||||
|
Assert.False(result);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_LastWins()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-last-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var f1 = Path.Combine(dir, "01.conf");
|
||||||
|
var f2 = Path.Combine(dir, "02.conf");
|
||||||
|
var firstVal = "100";
|
||||||
|
var secondVal = "200";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(f1, $"cache-size={firstVal}\n");
|
||||||
|
File.WriteAllText(f2, $"cache-size={secondVal}\n");
|
||||||
|
var (value, configDir) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { f1, f2 }, DnsmasqConfKeys.CacheSize);
|
||||||
|
Assert.Equal(secondVal, value);
|
||||||
|
Assert.Equal(dir, configDir);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_LogFacility_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-logfac-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var logPath = "/data/dnsmasq.log";
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(conf, $"log-facility={logPath}\n");
|
||||||
|
var (value, configDir) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.LogFacility);
|
||||||
|
Assert.Equal(logPath, value);
|
||||||
|
Assert.Equal(dir, configDir);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_LogFacility_LastWins()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-logfac2-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var f1 = Path.Combine(dir, "01.conf");
|
||||||
|
var f2 = Path.Combine(dir, "02.conf");
|
||||||
|
var firstLogPath = "/var/log/dnsmasq.log";
|
||||||
|
var secondLogPath = "/data/dnsmasq.log";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(f1, $"log-facility={firstLogPath}\n");
|
||||||
|
File.WriteAllText(f2, $"log-facility={secondLogPath}\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { f1, f2 }, DnsmasqConfKeys.LogFacility);
|
||||||
|
Assert.Equal(secondLogPath, value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResolvePath_Relative_ResolvesAgainstDir()
|
||||||
|
{
|
||||||
|
var dir = Path.GetTempPath();
|
||||||
|
var subDirName = "sub";
|
||||||
|
var fileName = "pid.pid";
|
||||||
|
var relativePath = $"{subDirName}/{fileName}";
|
||||||
|
var result = DnsmasqConfIncludeParser.ResolvePath(relativePath, dir);
|
||||||
|
Assert.Equal(Path.GetFullPath(Path.Combine(dir, subDirName, fileName)), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResolvePath_Absolute_ReturnsAsIs()
|
||||||
|
{
|
||||||
|
var absPath = Path.Combine(Path.GetTempPath(), "absolute.pid");
|
||||||
|
var result = DnsmasqConfIncludeParser.ResolvePath(absPath, "/some/dir");
|
||||||
|
Assert.Equal(Path.GetFullPath(absPath), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Tests matching dnsmasq option.c semantics (ARG_ONE = last wins, flags = no value allowed) ---
|
||||||
|
|
||||||
|
/// <summary>dnsmasq option.c: opts[i].has_arg == 0 && arg -> "extraneous parameter"; flag with value is invalid, so we must not count it.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_FlagWithValue_ReturnsFalse()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-flag-val-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var invalidValue = "1";
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(conf, $"expand-hosts={invalidValue}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.ExpandHosts);
|
||||||
|
Assert.False(result);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>dnsmasq option.c: strcmp(opts[i].name, start) == 0 — option names are case-sensitive; "Port" is bad option.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_CaseSensitive_PortWithCapitalP_ReturnsNull()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-case-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var wrongKey = "Port";
|
||||||
|
var value = "53";
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(conf, $"{wrongKey}={value}\n");
|
||||||
|
var (parsedValue, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Port);
|
||||||
|
Assert.Null(parsedValue);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Path list is [main, conf-file...]. We read each file entirely in that order, so last port is last occurrence in that stream (main lines then extra). Main has port=53, port=5353; extra has port=54 → last is 54.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_TwoFiles_LastOccurrenceInPathOrderWins()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-two-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var main = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var extra = Path.Combine(dir, "extra.conf");
|
||||||
|
var port1 = "53";
|
||||||
|
var port2 = "5353";
|
||||||
|
var port3 = "54";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(main, $"port={port1}\nconf-file=extra.conf\nport={port2}\n");
|
||||||
|
File.WriteAllText(extra, $"port={port3}\n");
|
||||||
|
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(paths, DnsmasqConfKeys.Port);
|
||||||
|
Assert.Equal(port3, value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- pathToLines overloads: same result as file-based when content is pre-read ---
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_WithPathToLines_ReturnsSameResultAsFileBased()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-ptl-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var lines = new[] { "expand-hosts", "no-resolv" };
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, string.Join("\n", lines) + "\n");
|
||||||
|
var paths = new[] { conf };
|
||||||
|
var pathToLines = new Dictionary<string, string[]>(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
[Path.GetFullPath(conf)] = lines
|
||||||
|
};
|
||||||
|
var fromFile = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(paths, DnsmasqConfKeys.ExpandHosts);
|
||||||
|
var fromDict = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(paths, pathToLines, DnsmasqConfKeys.ExpandHosts);
|
||||||
|
Assert.Equal(fromFile, fromDict);
|
||||||
|
Assert.True(fromDict);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_WithPathToLines_ReturnsSameResultAsFileBased()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-ptl-last-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var value = "1000";
|
||||||
|
var lines = new[] { $"cache-size={value}" };
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, lines[0] + "\n");
|
||||||
|
var paths = new[] { conf };
|
||||||
|
var pathToLines = new Dictionary<string, string[]>(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
[Path.GetFullPath(conf)] = lines
|
||||||
|
};
|
||||||
|
var (fromFileVal, fromFileDir) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(paths, DnsmasqConfKeys.CacheSize);
|
||||||
|
var (fromDictVal, fromDictDir) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(paths, pathToLines, DnsmasqConfKeys.CacheSize);
|
||||||
|
Assert.Equal(fromFileVal, fromDictVal);
|
||||||
|
Assert.Equal(value, fromDictVal);
|
||||||
|
Assert.Equal(fromFileDir, fromDictDir);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_WithPathToLines_ReturnsSameResultAsFileBased()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-ptl-multi-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var lines = new[] { "server=1.1.1.1", "server=8.8.8.8" };
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, string.Join("\n", lines) + "\n");
|
||||||
|
var paths = new[] { conf };
|
||||||
|
var pathToLines = new Dictionary<string, string[]>(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
[Path.GetFullPath(conf)] = lines
|
||||||
|
};
|
||||||
|
var fromFile = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.Server);
|
||||||
|
var fromDict = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, pathToLines, DnsmasqConfKeys.Server);
|
||||||
|
Assert.Equal(fromFile, fromDict);
|
||||||
|
Assert.Equal(2, fromDict.Count);
|
||||||
|
Assert.Equal("1.1.1.1", fromDict[0]);
|
||||||
|
Assert.Equal("8.8.8.8", fromDict[1]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Empty path list ---
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_EmptyPathList_ReturnsNullAndNull()
|
||||||
|
{
|
||||||
|
var (value, configDir) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(Array.Empty<string>(), DnsmasqConfKeys.Port);
|
||||||
|
Assert.Null(value);
|
||||||
|
Assert.Null(configDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_EmptyPathList_ReturnsEmptyList()
|
||||||
|
{
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(Array.Empty<string>(), DnsmasqConfKeys.Server);
|
||||||
|
Assert.NotNull(result);
|
||||||
|
Assert.Empty(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Non-existent file in path list: skipped without throw, last-wins from existing ---
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_NonExistentFileInList_SkipsMissingFileLastWinsFromExisting()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-missing-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var existing = Path.Combine(dir, "existing.conf");
|
||||||
|
var missing = Path.Combine(dir, "missing.conf");
|
||||||
|
var other = Path.Combine(dir, "other.conf");
|
||||||
|
var valueInExisting = "100";
|
||||||
|
var valueInOther = "200";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(existing, $"port={valueInExisting}\n");
|
||||||
|
File.WriteAllText(other, $"port={valueInOther}\n");
|
||||||
|
Assert.False(File.Exists(missing));
|
||||||
|
var paths = new[] { existing, missing, other };
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(paths, DnsmasqConfKeys.Port);
|
||||||
|
Assert.Equal(valueInOther, value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,359 @@
|
|||||||
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>DHCP advanced, TFTP/PXE, DNSSEC, enable-dbus/ubus, fast-dns-retry.</summary>
|
||||||
|
public class DnsmasqConfIncludeParserDhcpTftpDnssecTests
|
||||||
|
{
|
||||||
|
// --- One test per option: key wired, when set returns value(s) ---
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpMatch_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dhcpmatch-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "set:bios,option:client-arch,0";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-match={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpMatch);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpBoot_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dhcpboot-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "tag:bios-x86,firmware/ipxe.pxe,192.168.1.1";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-boot={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpBoot);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpIgnore_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dhcpignore-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "tag:!known";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-ignore={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpIgnore);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpVendorclass_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dhcpvc-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "set:pxe,option:vendor-class-identifier,PXEClient";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-vendorclass={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpVendorclass);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpUserclass_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dhcpuc-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "set:ipxe,iPXE";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-userclass={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpUserclass);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_RaParam_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-raparam-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "eth0,high,0";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"ra-param={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.RaParam);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_Slaac_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-slaac-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "eth0,0";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"slaac={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Slaac);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_EnableTftp_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-tftp-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "enable-tftp\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.EnableTftp);
|
||||||
|
Assert.True(result);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_TftpRoot_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-tftproot-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var path = "/var/lib/tftpboot";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"tftp-root={path}\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.TftpRoot);
|
||||||
|
Assert.Equal(path, value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_TftpSecure_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-tftpsec-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "tftp-secure\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.TftpSecure);
|
||||||
|
Assert.True(result);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_PxeService_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-pxe-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "x86PC,pxelinux.0";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"pxe-service={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.PxeService);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_PxePrompt_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-pxeprompt-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "timeout,0";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"pxe-prompt={line}\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.PxePrompt);
|
||||||
|
Assert.Equal(line, value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_Dnssec_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dnssec-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "dnssec\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Dnssec);
|
||||||
|
Assert.True(result);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_TrustAnchor_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-trust-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = ". IN DS 19036 8 2 49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDE32F024E8FC5";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"trust-anchor={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.TrustAnchor);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_DnssecCheckUnsigned_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dnsseccu-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "dnssec-check-unsigned\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DnssecCheckUnsigned);
|
||||||
|
Assert.True(result);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_EnableDbus_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dbus-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var svc = "org.freedesktop.NetworkManager";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"enable-dbus={svc}\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.EnableDbus);
|
||||||
|
Assert.Equal(svc, value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_EnableUbus_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-ubus-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var svc = "com.example.dnsmasq";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"enable-ubus={svc}\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.EnableUbus);
|
||||||
|
Assert.Equal(svc, value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_FastDnsRetry_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-fastretry-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "500,5000";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"fast-dns-retry={line}\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.FastDnsRetry);
|
||||||
|
Assert.Equal(line, value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>Boolean flags: no-hosts, bogus-priv, strict-order, domain-needed, no-poll, bind-*, rebind-*, clear-on-reload, filter*, localise-queries, log-debug, dhcp-authoritative, leasefile-ro.</summary>
|
||||||
|
public class DnsmasqConfIncludeParserFlagsTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_BogusPriv_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-boguspriv-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "bogus-priv\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.BogusPriv));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_StrictOrder_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-strict-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "strict-order\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.StrictOrder));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_DomainNeeded_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-domainneed-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "domain-needed\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DomainNeeded));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_NoPoll_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-nopoll-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "no-poll\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NoPoll));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_BindInterfaces_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-bindif-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "bind-interfaces\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.BindInterfaces));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_BindDynamic_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-binddyn-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "bind-dynamic\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.BindDynamic));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_NoNegcache_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-noneg-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "no-negcache\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NoNegcache));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_DnsLoopDetect_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-loop-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "dns-loop-detect\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DnsLoopDetect));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_StopDnsRebind_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-rebind-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "stop-dns-rebind\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.StopDnsRebind));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_RebindLocalhostOk_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-rebindlo-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "rebind-localhost-ok\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.RebindLocalhostOk));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_ClearOnReload_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-clear-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "clear-on-reload\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.ClearOnReload));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_Filterwin2k_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-filtw2k-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "filterwin2k\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Filterwin2k));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_FilterA_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-filta-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "filter-A\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.FilterA));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_FilterAaaa_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-filtaaaa-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "filter-AAAA\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.FilterAaaa));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_LocaliseQueries_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-localise-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "localise-queries\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.LocaliseQueries));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_LogDebug_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-logdbg-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "log-debug\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.LogDebug));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_DhcpAuthoritative_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dhcpauth-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "dhcp-authoritative\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpAuthoritative));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>Hosts (addn-hosts, hostsdir) and DHCP lease file parsing.</summary>
|
||||||
|
public class DnsmasqConfIncludeParserHostsAndLeaseTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void GetDhcpLeaseFilePathFromConfigFiles_FromTestdata_ReturnsLeasesPath()
|
||||||
|
{
|
||||||
|
var mainPath = TestDataHelper.GetPath("dnsmasq-test.conf");
|
||||||
|
Assert.True(File.Exists(mainPath), "Testdata dnsmasq-test.conf required");
|
||||||
|
var paths = new[] { mainPath };
|
||||||
|
var result = DnsmasqConfIncludeParser.GetDhcpLeaseFilePathFromConfigFiles(paths);
|
||||||
|
Assert.NotNull(result);
|
||||||
|
Assert.Equal(Path.GetFullPath("/data/leases"), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Uses testdata/dnsmasq-test.conf (harness main) to assert multi-value options are collected from testdata.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_FromTestdata_ReturnsServerAndAddnHosts()
|
||||||
|
{
|
||||||
|
var mainPath = TestDataHelper.GetPath("dnsmasq-test.conf");
|
||||||
|
Assert.True(File.Exists(mainPath), "Testdata dnsmasq-test.conf required");
|
||||||
|
var paths = new[] { mainPath };
|
||||||
|
var servers = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.Server);
|
||||||
|
var addnHosts = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFiles(paths);
|
||||||
|
var addresses = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.Address);
|
||||||
|
var listenAddrs = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.ListenAddress);
|
||||||
|
Assert.True(servers.Count >= 2, "testdata dnsmasq-test.conf should have at least 2 server= lines");
|
||||||
|
Assert.Contains("1.1.1.1", servers);
|
||||||
|
Assert.Contains("8.8.8.8", servers);
|
||||||
|
Assert.True(addnHosts.Count >= 2, "testdata should have at least 2 addn-hosts paths");
|
||||||
|
Assert.True(addresses.Count >= 2, "testdata should have at least 2 address= lines");
|
||||||
|
Assert.Single(listenAddrs);
|
||||||
|
Assert.Equal("172.28.0.2", listenAddrs[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetDhcpLeaseFilePathFromConfigFiles_LastWins()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-lease-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var firstLeasePath = "/var/first.leases";
|
||||||
|
var secondLeasePath = "/var/second.leases";
|
||||||
|
var first = Path.Combine(dir, "first.conf");
|
||||||
|
File.WriteAllText(first, $"dhcp-leasefile={firstLeasePath}\n");
|
||||||
|
var second = Path.Combine(dir, "second.conf");
|
||||||
|
File.WriteAllText(second, $"dhcp-leasefile={secondLeasePath}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetDhcpLeaseFilePathFromConfigFiles(new[] { first, second });
|
||||||
|
Assert.Equal(Path.GetFullPath(secondLeasePath), result);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetDhcpLeaseFilePathFromConfigFiles_RelativePath_ResolvedAgainstConfigDir()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-lease-rel-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var subdir = "subdir";
|
||||||
|
var leasesFile = "leases";
|
||||||
|
var relativePath = $"{subdir}/{leasesFile}";
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(conf, $"dhcp-leasefile={relativePath}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetDhcpLeaseFilePathFromConfigFiles(new[] { conf });
|
||||||
|
Assert.Equal(Path.GetFullPath(Path.Combine(dir, subdir, leasesFile)), result);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetAddnHostsPathsFromConfigFiles_Empty_ReturnsEmpty()
|
||||||
|
{
|
||||||
|
var result = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFiles(Array.Empty<string>());
|
||||||
|
Assert.Empty(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetAddnHostsPathsFromConfigFiles_Cumulative_ReturnsAllInOrder()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-addn-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var path1 = "/etc/hosts.d/first";
|
||||||
|
var path2 = "/data/hosts";
|
||||||
|
var path3 = "/data/extra.hosts";
|
||||||
|
var first = Path.Combine(dir, "first.conf");
|
||||||
|
File.WriteAllText(first, $"addn-hosts={path1}\n");
|
||||||
|
var second = Path.Combine(dir, "second.conf");
|
||||||
|
File.WriteAllText(second, $"addn-hosts={path2}\naddn-hosts={path3}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFiles(new[] { first, second });
|
||||||
|
Assert.Equal(3, result.Count);
|
||||||
|
Assert.Equal(Path.GetFullPath(path1), result[0]);
|
||||||
|
Assert.Equal(Path.GetFullPath(path2), result[1]);
|
||||||
|
Assert.Equal(Path.GetFullPath(path3), result[2]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetAddnHostsPathsFromConfigFiles_RelativePath_ResolvedAgainstConfigDir()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-addn-rel-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var pathPart1 = "hosts.d";
|
||||||
|
var pathPart2 = "app.hosts";
|
||||||
|
var addnRelativePath = $"{pathPart1}/{pathPart2}";
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(conf, $"addn-hosts={addnRelativePath}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFiles(new[] { conf });
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(Path.GetFullPath(Path.Combine(dir, pathPart1, pathPart2)), result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetAddnHostsPathsFromConfigFilesWithSource_ReturnsSourcePerPath()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-addn-src-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var f1 = Path.Combine(dir, "01.conf");
|
||||||
|
var f2 = Path.Combine(dir, "02.conf");
|
||||||
|
var managedPath = Path.Combine(dir, "managed.conf");
|
||||||
|
var path1 = "/etc/hosts.a";
|
||||||
|
var path2 = "/etc/hosts.b";
|
||||||
|
var path3 = "/etc/hosts.c";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(f1, $"addn-hosts={path1}\n");
|
||||||
|
File.WriteAllText(f2, $"addn-hosts={path2}\naddn-hosts={path3}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFilesWithSource(new[] { f1, f2 }, managedPath);
|
||||||
|
Assert.Equal(3, result.Count);
|
||||||
|
Assert.Equal(Path.GetFullPath(path1), result[0].Path);
|
||||||
|
Assert.Equal(Path.GetFileName(f1), result[0].Source.FileName);
|
||||||
|
Assert.False(result[0].Source.IsManaged);
|
||||||
|
Assert.Equal(1, result[0].Source.LineNumber);
|
||||||
|
Assert.Equal(Path.GetFullPath(path2), result[1].Path);
|
||||||
|
Assert.Equal(Path.GetFileName(f2), result[1].Source.FileName);
|
||||||
|
Assert.Equal(1, result[1].Source.LineNumber);
|
||||||
|
Assert.Equal(Path.GetFullPath(path3), result[2].Path);
|
||||||
|
Assert.Equal(2, result[2].Source.LineNumber);
|
||||||
|
Assert.True(result[2].Source.IsReadOnly == !result[2].Source.IsManaged);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetAddnHostsPathsFromConfigFilesWithSource_WhenManagedFileInList_IsManagedTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-addn-mgd-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var mainPath = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var managedPath = Path.Combine(dir, "zz-managed.conf");
|
||||||
|
var readOnlyPath = "/other/hosts";
|
||||||
|
var managedAddnPath = "/managed/hosts";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(mainPath, $"addn-hosts={readOnlyPath}\n");
|
||||||
|
File.WriteAllText(managedPath, $"addn-hosts={managedAddnPath}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFilesWithSource(new[] { mainPath, managedPath }, managedPath);
|
||||||
|
Assert.Equal(2, result.Count);
|
||||||
|
Assert.False(result[0].Source.IsManaged);
|
||||||
|
Assert.Equal(1, result[0].Source.LineNumber);
|
||||||
|
Assert.True(result[1].Source.IsManaged);
|
||||||
|
Assert.Equal(1, result[1].Source.LineNumber);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>Config discovery: conf-file=, conf-dir=, GetIncludedPaths, GetFirstConfDir, GetIncludedPathsWithSource, conf-dir suffix.</summary>
|
||||||
|
public class DnsmasqConfIncludeParserIncludeTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void GetIncludedPaths_MainFileMissing_ReturnsOnlyMainPath()
|
||||||
|
{
|
||||||
|
var main = Path.Combine(Path.GetTempPath(), "nonexistent-dnsmasq-" + Guid.NewGuid().ToString("N") + ".conf");
|
||||||
|
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
||||||
|
Assert.Single(paths);
|
||||||
|
Assert.Equal(Path.GetFullPath(main), paths[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetIncludedPaths_MainOnly_ReturnsSinglePath()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-main-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var main = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(main, "domain=local\n");
|
||||||
|
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
||||||
|
Assert.Single(paths);
|
||||||
|
Assert.Equal(Path.GetFullPath(main), paths[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetIncludedPaths_OneConfFile_ReturnsMainThenConfFile()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-conffile-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var includeFileName = "extra.conf";
|
||||||
|
var includePath = Path.Combine(dir, includeFileName);
|
||||||
|
File.WriteAllText(includePath, "# extra\n");
|
||||||
|
var main = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(main, $"conf-file={includeFileName}\n");
|
||||||
|
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
||||||
|
Assert.Equal(2, paths.Count);
|
||||||
|
Assert.Equal(Path.GetFullPath(main), paths[0]);
|
||||||
|
Assert.Equal(Path.GetFullPath(includePath), paths[1]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetIncludedPaths_OneConfDir_ReturnsMainThenDirFilesSorted()
|
||||||
|
{
|
||||||
|
var baseDir = Path.Combine(Path.GetTempPath(), "dnsmasq-confdir-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(baseDir);
|
||||||
|
var confDirName = "d";
|
||||||
|
var subDir = Path.Combine(baseDir, confDirName);
|
||||||
|
Directory.CreateDirectory(subDir);
|
||||||
|
var file1 = "aa.conf";
|
||||||
|
var file2 = "zz.conf";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(Path.Combine(subDir, file2), "");
|
||||||
|
File.WriteAllText(Path.Combine(subDir, file1), "");
|
||||||
|
var main = Path.Combine(baseDir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(main, $"conf-dir={confDirName}\n");
|
||||||
|
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
||||||
|
Assert.Equal(3, paths.Count); // main + aa.conf + zz.conf (alphabetical)
|
||||||
|
Assert.Equal(Path.GetFullPath(main), paths[0]);
|
||||||
|
Assert.Equal(Path.GetFullPath(Path.Combine(subDir, file1)), paths[1]);
|
||||||
|
Assert.Equal(Path.GetFullPath(Path.Combine(subDir, file2)), paths[2]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(baseDir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFirstConfDir_NoConfDir_ReturnsNull()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-noconfdir-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var main = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(main, "domain=local\nconf-file=other.conf\n");
|
||||||
|
var first = DnsmasqConfIncludeParser.GetFirstConfDir(main);
|
||||||
|
Assert.Null(first);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFirstConfDir_HasConfDir_ReturnsResolvedPath()
|
||||||
|
{
|
||||||
|
var baseDir = Path.Combine(Path.GetTempPath(), "dnsmasq-firstdir-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(baseDir);
|
||||||
|
var confDirName = "dnsmasq.d";
|
||||||
|
var subDir = Path.Combine(baseDir, confDirName);
|
||||||
|
Directory.CreateDirectory(subDir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var main = Path.Combine(baseDir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(main, $"conf-dir={confDirName}\n");
|
||||||
|
var first = DnsmasqConfIncludeParser.GetFirstConfDir(main);
|
||||||
|
Assert.NotNull(first);
|
||||||
|
Assert.Equal(Path.GetFullPath(subDir), first);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(baseDir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetIncludedPaths_CommentsAndBlanks_Ignored()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-comments-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var main = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(main, "# comment\n\n \nconf-file=extra.conf\n");
|
||||||
|
var extra = Path.Combine(dir, "extra.conf");
|
||||||
|
File.WriteAllText(extra, "");
|
||||||
|
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
||||||
|
Assert.Equal(2, paths.Count);
|
||||||
|
Assert.Equal(Path.GetFullPath(extra), paths[1]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetIncludedPaths_ConfDirMissing_ReturnsMainOnly()
|
||||||
|
{
|
||||||
|
var baseDir = Path.Combine(Path.GetTempPath(), "dnsmasq-confdir-missing-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(baseDir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var main = Path.Combine(baseDir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(main, "conf-dir=nonexistent-subdir\n");
|
||||||
|
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
||||||
|
Assert.Single(paths);
|
||||||
|
Assert.Equal(Path.GetFullPath(main), paths[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(baseDir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Mirrors harness layout: main + conf-dir with multiple files (including lan-dns.conf) + conf-file. Asserts all appear in load order with correct sources.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void GetIncludedPathsWithSource_ConfDirAndConfFile_ReturnsAllFilesInLoadOrderWithSources()
|
||||||
|
{
|
||||||
|
var baseDir = Path.Combine(Path.GetTempPath(), "dnsmasq-harness-layout-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(baseDir);
|
||||||
|
var confDir = Path.Combine(baseDir, "dnsmasq.d");
|
||||||
|
Directory.CreateDirectory(confDir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(Path.Combine(confDir, "01-other.conf"), "# other\n");
|
||||||
|
File.WriteAllText(Path.Combine(confDir, "02-servers.conf"), "# servers\n");
|
||||||
|
File.WriteAllText(Path.Combine(confDir, "lan-dns.conf"), "# lan dns\n");
|
||||||
|
File.WriteAllText(Path.Combine(baseDir, "zz-dnsmasq-webui.conf"), "# managed\n");
|
||||||
|
var main = Path.Combine(baseDir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(main, "conf-dir=dnsmasq.d\nconf-file=zz-dnsmasq-webui.conf\n");
|
||||||
|
var withSource = DnsmasqConfIncludeParser.GetIncludedPathsWithSource(main);
|
||||||
|
Assert.Equal(5, withSource.Count);
|
||||||
|
Assert.Equal(Path.GetFullPath(main), withSource[0].Path);
|
||||||
|
Assert.Equal(DnsmasqConfFileSource.Main, withSource[0].Source);
|
||||||
|
Assert.Equal(Path.GetFullPath(Path.Combine(confDir, "01-other.conf")), withSource[1].Path);
|
||||||
|
Assert.Equal(DnsmasqConfFileSource.ConfDir, withSource[1].Source);
|
||||||
|
Assert.Equal(Path.GetFullPath(Path.Combine(confDir, "02-servers.conf")), withSource[2].Path);
|
||||||
|
Assert.Equal(DnsmasqConfFileSource.ConfDir, withSource[2].Source);
|
||||||
|
Assert.Equal(Path.GetFullPath(Path.Combine(confDir, "lan-dns.conf")), withSource[3].Path);
|
||||||
|
Assert.Equal(DnsmasqConfFileSource.ConfDir, withSource[3].Source);
|
||||||
|
Assert.Equal(Path.GetFullPath(Path.Combine(baseDir, "zz-dnsmasq-webui.conf")), withSource[4].Path);
|
||||||
|
Assert.Equal(DnsmasqConfFileSource.ConfFile, withSource[4].Source);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(baseDir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>dnsmasq conf-dir=dir,*.suffix only includes files ending with suffix (option.c match_suffix).</summary>
|
||||||
|
[Fact]
|
||||||
|
public void GetIncludedPaths_ConfDir_WithMatchSuffix_OnlyIncludesMatchingFiles()
|
||||||
|
{
|
||||||
|
var baseDir = Path.Combine(Path.GetTempPath(), "dnsmasq-match-" + Guid.NewGuid().ToString("N"));
|
||||||
|
var subDir = Path.Combine(baseDir, "d");
|
||||||
|
Directory.CreateDirectory(subDir);
|
||||||
|
var fileConf1 = "a.conf";
|
||||||
|
var fileTxt = "b.txt";
|
||||||
|
var fileConf2 = "c.conf";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(Path.Combine(subDir, fileConf1), "");
|
||||||
|
File.WriteAllText(Path.Combine(subDir, fileTxt), "");
|
||||||
|
File.WriteAllText(Path.Combine(subDir, fileConf2), "");
|
||||||
|
var main = Path.Combine(baseDir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(main, "conf-dir=d,*.conf\n");
|
||||||
|
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
||||||
|
Assert.Equal(3, paths.Count);
|
||||||
|
Assert.Contains(paths, p => p.EndsWith(fileConf1, StringComparison.Ordinal));
|
||||||
|
Assert.Contains(paths, p => p.EndsWith(fileConf2, StringComparison.Ordinal));
|
||||||
|
Assert.DoesNotContain(paths, p => p.EndsWith(fileTxt, StringComparison.Ordinal));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(baseDir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>dnsmasq conf-dir=dir,.suffix ignores files ending with suffix (option.c ignore_suffix).</summary>
|
||||||
|
[Fact]
|
||||||
|
public void GetIncludedPaths_ConfDir_WithIgnoreSuffix_ExcludesMatchingFiles()
|
||||||
|
{
|
||||||
|
var baseDir = Path.Combine(Path.GetTempPath(), "dnsmasq-ignore-" + Guid.NewGuid().ToString("N"));
|
||||||
|
var subDir = Path.Combine(baseDir, "d");
|
||||||
|
Directory.CreateDirectory(subDir);
|
||||||
|
var fileIncluded = "a.conf";
|
||||||
|
var fileExcluded = "b.conf.bak";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(Path.Combine(subDir, fileIncluded), "");
|
||||||
|
File.WriteAllText(Path.Combine(subDir, fileExcluded), "");
|
||||||
|
var main = Path.Combine(baseDir, "dnsmasq.conf");
|
||||||
|
File.WriteAllText(main, "conf-dir=d,.bak\n");
|
||||||
|
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
||||||
|
Assert.Equal(2, paths.Count);
|
||||||
|
Assert.Contains(paths, p => p.EndsWith(fileIncluded, StringComparison.Ordinal));
|
||||||
|
Assert.DoesNotContain(paths, p => p.EndsWith(fileExcluded, StringComparison.Ordinal));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(baseDir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Direct test for EnumerateConfigLinesInDnsmasqOrder: main has line1, conf-file=extra, line2; extra has extra1. Asserts interleaving order.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void EnumerateConfigLinesInDnsmasqOrder_ConfFileInMiddle_InterleavesMainThenIncludedThenMain()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-enum-order-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var main = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var extra = Path.Combine(dir, "extra.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(main, "line1\nconf-file=extra.conf\nline2\n");
|
||||||
|
File.WriteAllText(extra, "extra1\n");
|
||||||
|
var mainFull = Path.GetFullPath(main);
|
||||||
|
var extraFull = Path.GetFullPath(extra);
|
||||||
|
var mainDir = Path.GetDirectoryName(mainFull) ?? "";
|
||||||
|
var seq = DnsmasqConfIncludeParser.EnumerateConfigLinesInDnsmasqOrder(mainFull, mainDir, DnsmasqConfFileSource.Main, null).ToList();
|
||||||
|
Assert.Equal(5, seq.Count);
|
||||||
|
Assert.Equal((mainFull, 0, "", DnsmasqConfFileSource.Main), seq[0]);
|
||||||
|
Assert.Equal((mainFull, 1, "line1", DnsmasqConfFileSource.Main), seq[1]);
|
||||||
|
Assert.Equal((extraFull, 0, "", DnsmasqConfFileSource.ConfFile), seq[2]);
|
||||||
|
Assert.Equal((extraFull, 1, "extra1", DnsmasqConfFileSource.ConfFile), seq[3]);
|
||||||
|
Assert.Equal((mainFull, 3, "line2", DnsmasqConfFileSource.Main), seq[4]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>Interfaces, auth-server, DHCP/option/resolv multi-value, rebind/bogus/ignore/alias, filter-rr, cache-rr.</summary>
|
||||||
|
public class DnsmasqConfIncludeParserInterfacesAndFilteringTests
|
||||||
|
{
|
||||||
|
// --- Additional tests: one per conf field so every option has a documented example test ---
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_Interface_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-if-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "interface=eth0\ninterface=wlan0\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Interface);
|
||||||
|
Assert.Equal(2, result.Count);
|
||||||
|
Assert.Equal("eth0", result[0]);
|
||||||
|
Assert.Equal("wlan0", result[1]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_ExceptInterface_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-except-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "except-interface=eth1\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.ExceptInterface);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal("eth1", result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_NoDhcpInterface_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-nodhcpi-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "no-dhcp-interface=eth2\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NoDhcpInterface);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal("eth2", result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_NoDhcpv4Interface_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-nodhcp4-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "no-dhcpv4-interface=eth0\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NoDhcpv4Interface);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal("eth0", result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_NoDhcpv6Interface_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-nodhcp6-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "no-dhcpv6-interface=eth0\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NoDhcpv6Interface);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal("eth0", result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_AuthServer_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-auth-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "lan,eth0";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"auth-server={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.AuthServer);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpHost_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dhcphost-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "00:11:22:33:44:55,192.168.1.100,router,12h";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-host={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpHost);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpOption_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dhcpopt-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "option:router,192.168.1.1";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-option={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpOption);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_ResolvFile_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-resolv-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var path = "/etc/resolv.dnsmasq";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"resolv-file={path}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.ResolvFile);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(path, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_RebindDomainOk_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-rebind-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "/local.lan/";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"rebind-domain-ok={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.RebindDomainOk);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_BogusNxdomain_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-bogusnx-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "64.94.110.11";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"bogus-nxdomain={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.BogusNxdomain);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_IgnoreAddress_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-ignoreaddr-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "192.168.1.0/24";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"ignore-address={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.IgnoreAddress);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_Alias_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-alias-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "1.2.3.0,6.7.8.0,255.255.255.0";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"alias={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Alias);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_FilterRr_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-filterrr-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "TXT,MX";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"filter-rr={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.FilterRr);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_CacheRr_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-cacherr-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "TXT";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"cache-rr={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.CacheRr);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_NoHosts_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-nohosts-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "no-hosts\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NoHosts);
|
||||||
|
Assert.True(result);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Positive parser tests for added options: key wired and "option present" behaviour.
|
||||||
|
/// Ensures key names in DnsmasqConfKeys match what the parser expects (complement to OfficialExampleTests which assert "all commented → false/empty").
|
||||||
|
/// Covers process flags (keep-in-foreground, no-daemon), DHCP include paths (dhcp-hostsfile, dhcp-optsfile, dhcp-hostsdir), proxy-dnssec, conntrack.
|
||||||
|
/// </summary>
|
||||||
|
public class DnsmasqConfIncludeParserNewOptionsTests
|
||||||
|
{
|
||||||
|
// --- Flags (8): key-only line → GetFlag returns true ---
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_ReadEthers_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
WriteFlagAndAssertTrue(DnsmasqConfKeys.ReadEthers);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_DhcpRapidCommit_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
WriteFlagAndAssertTrue(DnsmasqConfKeys.DhcpRapidCommit);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_TftpNoFail_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
WriteFlagAndAssertTrue(DnsmasqConfKeys.TftpNoFail);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_TftpNoBlocksize_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
WriteFlagAndAssertTrue(DnsmasqConfKeys.TftpNoBlocksize);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_Localmx_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
WriteFlagAndAssertTrue(DnsmasqConfKeys.Localmx);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_Selfmx_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
WriteFlagAndAssertTrue(DnsmasqConfKeys.Selfmx);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_EnableRa_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
WriteFlagAndAssertTrue(DnsmasqConfKeys.EnableRa);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_LogDhcp_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
WriteFlagAndAssertTrue(DnsmasqConfKeys.LogDhcp);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_KeepInForeground_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
WriteFlagAndAssertTrue(DnsmasqConfKeys.KeepInForeground);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_NoDaemon_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
WriteFlagAndAssertTrue(DnsmasqConfKeys.NoDaemon);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_ProxyDnssec_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
WriteFlagAndAssertTrue(DnsmasqConfKeys.ProxyDnssec);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Multi-value (6): key=value line(s) → GetMultiValue returns value(s) ---
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpOptionForce_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "208,f1:00:74:7e";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-option-force={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpOptionForce);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_Ipset_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "/example.com/vpn,search";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"ipset={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Ipset);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_Nftset_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "/example.com/ip#test#vpn";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"nftset={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Nftset);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpMac_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "set:red,00:60:8C:*:*:*";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-mac={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpMac);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpNameMatch_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "set:wpad-ignore,wpad";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-name-match={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpNameMatch);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpIgnoreNames_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "tag:wpad-ignore";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-ignore-names={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpIgnoreNames);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpHostsfile_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var path = "/etc/dnsmasq.d/hosts.d";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-hostsfile={path}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpHostsfile);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(path, result[0]);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpOptsfile_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var path = "/etc/dnsmasq.d/opts.conf";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-optsfile={path}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpOptsfile);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(path, result[0]);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpHostsdir_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var path = "/etc/dnsmasq.d/hosts.d";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-hostsdir={path}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpHostsdir);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(path, result[0]);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Single-value (2): key=value → GetLastValue returns value ---
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_MxTarget_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var value = "mail.example.com";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"mx-target={value}\n");
|
||||||
|
var (result, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.MxTarget);
|
||||||
|
Assert.Equal(value, result);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_DhcpScript_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var value = "/usr/bin/dnsmasq-script";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-script={value}\n");
|
||||||
|
var (result, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpScript);
|
||||||
|
Assert.Equal(value, result);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_Conntrack_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var value = "42";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"conntrack={value}\n");
|
||||||
|
var (result, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Conntrack);
|
||||||
|
Assert.Equal(value, result);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WriteFlagAndAssertTrue(string key)
|
||||||
|
{
|
||||||
|
var dir = CreateTempDir();
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, key + "\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, key));
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(dir, recursive: true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string CreateTempDir()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-newopts-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tests that the parser correctly handles the official dnsmasq example (testdata/dnsmasq.official.conf.example).
|
||||||
|
/// All options in that file are commented out, so parsing it should yield no active values (single path, empty/false/null).
|
||||||
|
/// </summary>
|
||||||
|
public class DnsmasqConfIncludeParserOfficialExampleTests
|
||||||
|
{
|
||||||
|
private static string GetOfficialExamplePath()
|
||||||
|
{
|
||||||
|
var path = TestDataHelper.GetPath("dnsmasq.official.conf.example");
|
||||||
|
Assert.True(File.Exists(path), "Testdata dnsmasq.official.conf.example required (download from https://github.com/imp/dnsmasq)");
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetIncludedPaths_OfficialExample_ReturnsSinglePath()
|
||||||
|
{
|
||||||
|
var mainPath = GetOfficialExamplePath();
|
||||||
|
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(mainPath);
|
||||||
|
Assert.Single(paths);
|
||||||
|
Assert.Equal(Path.GetFullPath(mainPath), paths[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_OfficialExample_AllCommented_ReturnsNull()
|
||||||
|
{
|
||||||
|
var mainPath = GetOfficialExamplePath();
|
||||||
|
var paths = new[] { mainPath };
|
||||||
|
var (portVal, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(paths, DnsmasqConfKeys.Port);
|
||||||
|
var (cacheVal, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(paths, DnsmasqConfKeys.CacheSize);
|
||||||
|
var (mxTargetVal, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(paths, DnsmasqConfKeys.MxTarget);
|
||||||
|
var (dhcpScriptVal, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(paths, DnsmasqConfKeys.DhcpScript);
|
||||||
|
Assert.Null(portVal);
|
||||||
|
Assert.Null(cacheVal);
|
||||||
|
Assert.Null(mxTargetVal);
|
||||||
|
Assert.Null(dhcpScriptVal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_OfficialExample_AllCommented_ReturnsEmpty()
|
||||||
|
{
|
||||||
|
var mainPath = GetOfficialExamplePath();
|
||||||
|
var paths = new[] { mainPath };
|
||||||
|
var servers = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.Server);
|
||||||
|
var locals = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.Local);
|
||||||
|
var dhcpOptionForce = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.DhcpOptionForce);
|
||||||
|
var ipset = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.Ipset);
|
||||||
|
var nftset = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.Nftset);
|
||||||
|
var dhcpMac = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.DhcpMac);
|
||||||
|
var dhcpNameMatch = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.DhcpNameMatch);
|
||||||
|
var dhcpIgnoreNames = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.DhcpIgnoreNames);
|
||||||
|
Assert.Empty(servers);
|
||||||
|
Assert.Empty(locals);
|
||||||
|
Assert.Empty(dhcpOptionForce);
|
||||||
|
Assert.Empty(ipset);
|
||||||
|
Assert.Empty(nftset);
|
||||||
|
Assert.Empty(dhcpMac);
|
||||||
|
Assert.Empty(dhcpNameMatch);
|
||||||
|
Assert.Empty(dhcpIgnoreNames);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_OfficialExample_AllCommented_ReturnsFalse()
|
||||||
|
{
|
||||||
|
var mainPath = GetOfficialExamplePath();
|
||||||
|
var paths = new[] { mainPath };
|
||||||
|
Assert.False(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(paths, DnsmasqConfKeys.ExpandHosts));
|
||||||
|
Assert.False(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(paths, DnsmasqConfKeys.ReadEthers));
|
||||||
|
Assert.False(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(paths, DnsmasqConfKeys.DhcpRapidCommit));
|
||||||
|
Assert.False(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(paths, DnsmasqConfKeys.TftpNoFail));
|
||||||
|
Assert.False(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(paths, DnsmasqConfKeys.TftpNoBlocksize));
|
||||||
|
Assert.False(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(paths, DnsmasqConfKeys.Localmx));
|
||||||
|
Assert.False(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(paths, DnsmasqConfKeys.Selfmx));
|
||||||
|
Assert.False(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(paths, DnsmasqConfKeys.EnableRa));
|
||||||
|
Assert.False(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(paths, DnsmasqConfKeys.LogDhcp));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void OfficialExample_FileContainsExpectedOptionNames()
|
||||||
|
{
|
||||||
|
var path = GetOfficialExamplePath();
|
||||||
|
var content = File.ReadAllText(path);
|
||||||
|
// Sanity: official example documents the options we support (as commented lines).
|
||||||
|
Assert.Contains("read-ethers", content);
|
||||||
|
Assert.Contains("dhcp-option-force", content);
|
||||||
|
Assert.Contains("dhcp-rapid-commit", content);
|
||||||
|
Assert.Contains("dhcp-script", content);
|
||||||
|
Assert.Contains("tftp-no-fail", content);
|
||||||
|
Assert.Contains("tftp-no-blocksize", content);
|
||||||
|
Assert.Contains("mx-target", content);
|
||||||
|
Assert.Contains("localmx", content);
|
||||||
|
Assert.Contains("selfmx", content);
|
||||||
|
Assert.Contains("enable-ra", content);
|
||||||
|
Assert.Contains("log-dhcp", content);
|
||||||
|
Assert.Contains("ipset=", content);
|
||||||
|
Assert.Contains("nftset=", content);
|
||||||
|
Assert.Contains("dhcp-mac", content);
|
||||||
|
Assert.Contains("dhcp-name-match", content);
|
||||||
|
Assert.Contains("dhcp-ignore-names", content);
|
||||||
|
// SRV records use option name srv-host (not "srv")
|
||||||
|
Assert.Contains("srv-host", content);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetAddnHostsPathsFromConfigFiles_OfficialExample_AllCommented_ReturnsEmpty()
|
||||||
|
{
|
||||||
|
var mainPath = GetOfficialExamplePath();
|
||||||
|
var paths = new[] { mainPath };
|
||||||
|
var addnHosts = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFiles(paths);
|
||||||
|
Assert.NotNull(addnHosts);
|
||||||
|
Assert.Empty(addnHosts);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetNoHostsFromConfigFiles_OfficialExample_AllCommented_ReturnsFalse()
|
||||||
|
{
|
||||||
|
var mainPath = GetOfficialExamplePath();
|
||||||
|
var paths = new[] { mainPath };
|
||||||
|
var noHosts = DnsmasqConfIncludeParser.GetNoHostsFromConfigFiles(paths);
|
||||||
|
Assert.False(noHosts);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>DNS records and local names: hostsdir, domain, cname, mx-host, srv, ptr/txt/naptr/host-record, dynamic-host, interface-name.</summary>
|
||||||
|
public class DnsmasqConfIncludeParserRecordsTests
|
||||||
|
{
|
||||||
|
// --- One test per option: key wired, when set returns value(s) ---
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_Hostsdir_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-hostsdir-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var path = "/etc/dnsmasq.d/hosts";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"hostsdir={path}\n");
|
||||||
|
var (value, configDir) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Hostsdir);
|
||||||
|
Assert.Equal(path, value);
|
||||||
|
Assert.Equal(dir, configDir);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_Domain_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-domain-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "home,192.168.1.1";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"domain={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Domain);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_Cname_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-cname-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "mail.example.com,real.example.com";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"cname={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Cname);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_MxHost_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-mx-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "example.com,mail.example.com,50";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"mx-host={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.MxHost);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_Srv_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-srv-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "_http._tcp.example.com,server.example.com,80";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"srv-host={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Srv);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_PtrRecord_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-ptr-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "1.168.192.in-addr.arpa,host.example.com";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"ptr-record={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.PtrRecord);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_TxtRecord_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-txt-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "example.com,v=spf1 include:_spf.example.com";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"txt-record={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.TxtRecord);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_NaptrRecord_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-naptr-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "example.com,100,10,u,sip+E2U,sips:.*@example.com,.";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"naptr-record={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NaptrRecord);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_HostRecord_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-hostrecord-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "router.example.com,192.168.1.1";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"host-record={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.HostRecord);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DynamicHost_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dynamichost-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "hostname,example.com,192.168.1.50";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dynamic-host={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DynamicHost);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_InterfaceName_WhenSet_ReturnsValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-ifname-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var line = "eth0,router.local";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"interface-name={line}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.InterfaceName);
|
||||||
|
Assert.Single(result);
|
||||||
|
Assert.Equal(line, result[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>Server/local, rev-server, dhcp-range, all-servers, log-queries.</summary>
|
||||||
|
public class DnsmasqConfIncludeParserServerAndResolvTests
|
||||||
|
{
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_ServerAndLocal_CollectsBothInOrder()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-multi-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var f1 = Path.Combine(dir, "01.conf");
|
||||||
|
var f2 = Path.Combine(dir, "02.conf");
|
||||||
|
var v1 = "1.1.1.1";
|
||||||
|
var v2 = "/local/";
|
||||||
|
var v3 = "/example.com/192.168.1.1";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(f1, $"server={v1}\nlocal={v2}\n");
|
||||||
|
File.WriteAllText(f2, $"server={v3}\n");
|
||||||
|
var resultServer = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { f1, f2 }, DnsmasqConfKeys.Server);
|
||||||
|
var resultLocal = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { f1, f2 }, DnsmasqConfKeys.Local);
|
||||||
|
Assert.Equal(2, resultServer.Count);
|
||||||
|
Assert.Equal(v1, resultServer[0]);
|
||||||
|
Assert.Equal(v3, resultServer[1]);
|
||||||
|
Assert.Single(resultLocal);
|
||||||
|
Assert.Equal(v2, resultLocal[0]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_DhcpRange_CollectsAllInOrder()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dhcp-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var range1 = "172.28.0.10,172.28.0.50,12h";
|
||||||
|
var range2 = "192.168.1.10,192.168.1.100,255.255.255.0,24h";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"dhcp-range={range1}\ndhcp-range={range2}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpRange);
|
||||||
|
Assert.Equal(2, result.Count);
|
||||||
|
Assert.Equal(range1, result[0]);
|
||||||
|
Assert.Equal(range2, result[1]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_AllServers_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-allsrv-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "all-servers\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.AllServers);
|
||||||
|
Assert.True(result);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_LogQueries_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-logq-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "log-queries=extra\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.LogQueries);
|
||||||
|
Assert.Equal("extra", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetMultiValueFromConfigFiles_RevServer_ReturnsAllValues()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-rev-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var v1 = "1.2.3.0/24,192.168.0.1";
|
||||||
|
var v2 = "10.0.0.0/8,10.0.0.1";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"rev-server={v1}\nrev-server={v2}\n");
|
||||||
|
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.RevServer);
|
||||||
|
Assert.Equal(2, result.Count);
|
||||||
|
Assert.Equal(v1, result[0]);
|
||||||
|
Assert.Equal(v2, result[1]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
using DnsmasqWebUI.Infrastructure.Helpers.Config;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>Single-value options (last wins): local-ttl, pid-file, user, group, auth-ttl, edns-packet-max, query-port, port-limit, min/max-port, log-async, local-service, dhcp-lease-max, neg/max/min-cache-ttl, dhcp-ttl.</summary>
|
||||||
|
public class DnsmasqConfIncludeParserSingleValueTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void GetFlagFromConfigFiles_LeasefileRo_WhenPresent_ReturnsTrue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-leasero-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "leasefile-ro\n");
|
||||||
|
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.LeasefileRo));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_LocalTtl_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-localttl-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "local-ttl=300\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.LocalTtl);
|
||||||
|
Assert.Equal("300", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_PidFile_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-pid-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
var path = "/var/run/dnsmasq.pid";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, $"pid-file={path}\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.PidFile);
|
||||||
|
Assert.Equal(path, value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_User_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-user-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "user=nobody\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.User);
|
||||||
|
Assert.Equal("nobody", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_Group_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-group-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "group=dip\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Group);
|
||||||
|
Assert.Equal("dip", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_AuthTtl_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-authttl-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "auth-ttl=60\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.AuthTtl);
|
||||||
|
Assert.Equal("60", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_EdnsPacketMax_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-edns-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "edns-packet-max=1232\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.EdnsPacketMax);
|
||||||
|
Assert.Equal("1232", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_QueryPort_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-qport-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "query-port=0\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.QueryPort);
|
||||||
|
Assert.Equal("0", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_PortLimit_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-portlimit-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "port-limit=3\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.PortLimit);
|
||||||
|
Assert.Equal("3", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_MinPort_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-minport-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "min-port=1024\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.MinPort);
|
||||||
|
Assert.Equal("1024", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_MaxPort_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-maxport-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "max-port=65535\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.MaxPort);
|
||||||
|
Assert.Equal("65535", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_LogAsync_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-logasync-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "log-async=25\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.LogAsync);
|
||||||
|
Assert.Equal("25", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_LocalService_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-localsvc-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "local-service=host\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.LocalService);
|
||||||
|
Assert.Equal("host", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_DhcpLeaseMax_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-leasemax-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "dhcp-lease-max=150\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpLeaseMax);
|
||||||
|
Assert.Equal("150", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_NegTtl_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-negttl-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "neg-ttl=60\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NegTtl);
|
||||||
|
Assert.Equal("60", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_MaxTtl_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-maxttl-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "max-ttl=3600\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.MaxTtl);
|
||||||
|
Assert.Equal("3600", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_MaxCacheTtl_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-maxcttl-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "max-cache-ttl=86400\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.MaxCacheTtl);
|
||||||
|
Assert.Equal("86400", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_MinCacheTtl_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-mincttl-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "min-cache-ttl=60\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.MinCacheTtl);
|
||||||
|
Assert.Equal("60", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetLastValueFromConfigFiles_DhcpTtl_WhenSet_ReturnsValue()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dhcpttl-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
var conf = Path.Combine(dir, "dnsmasq.conf");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(conf, "dhcp-ttl=0\n");
|
||||||
|
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpTtl);
|
||||||
|
Assert.Equal("0", value);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(dir, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,600 +0,0 @@
|
|||||||
using DnsmasqWebUI.Models.Config;
|
|
||||||
using DnsmasqWebUI.Parsers;
|
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Tests;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Tests for DnsmasqConfIncludeParser. Discovers conf-file= and conf-dir= from main dnsmasq config
|
|
||||||
/// to build ordered list of included file paths and first conf-dir for managed file.
|
|
||||||
/// </summary>
|
|
||||||
public class DnsmasqConfIncludeParserTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public void GetIncludedPaths_MainFileMissing_ReturnsOnlyMainPath()
|
|
||||||
{
|
|
||||||
var main = Path.Combine(Path.GetTempPath(), "nonexistent-dnsmasq-" + Guid.NewGuid().ToString("N") + ".conf");
|
|
||||||
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
|
||||||
Assert.Single(paths);
|
|
||||||
Assert.Equal(Path.GetFullPath(main), paths[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetIncludedPaths_MainOnly_ReturnsSinglePath()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-main-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var main = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(main, "domain=local\n");
|
|
||||||
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
|
||||||
Assert.Single(paths);
|
|
||||||
Assert.Equal(Path.GetFullPath(main), paths[0]);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetIncludedPaths_OneConfFile_ReturnsMainThenConfFile()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-conffile-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var includePath = Path.Combine(dir, "extra.conf");
|
|
||||||
File.WriteAllText(includePath, "# extra\n");
|
|
||||||
var main = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(main, "conf-file=extra.conf\n");
|
|
||||||
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
|
||||||
Assert.Equal(2, paths.Count);
|
|
||||||
Assert.Equal(Path.GetFullPath(main), paths[0]);
|
|
||||||
Assert.Equal(Path.GetFullPath(includePath), paths[1]);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetIncludedPaths_OneConfDir_ReturnsMainThenDirFilesSorted()
|
|
||||||
{
|
|
||||||
var baseDir = Path.Combine(Path.GetTempPath(), "dnsmasq-confdir-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(baseDir);
|
|
||||||
var subDir = Path.Combine(baseDir, "d");
|
|
||||||
Directory.CreateDirectory(subDir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.WriteAllText(Path.Combine(subDir, "zz.conf"), "");
|
|
||||||
File.WriteAllText(Path.Combine(subDir, "aa.conf"), "");
|
|
||||||
var main = Path.Combine(baseDir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(main, "conf-dir=d\n");
|
|
||||||
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
|
||||||
Assert.Equal(3, paths.Count); // main + aa.conf + zz.conf (alphabetical)
|
|
||||||
Assert.Equal(Path.GetFullPath(main), paths[0]);
|
|
||||||
Assert.Equal(Path.GetFullPath(Path.Combine(subDir, "aa.conf")), paths[1]);
|
|
||||||
Assert.Equal(Path.GetFullPath(Path.Combine(subDir, "zz.conf")), paths[2]);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(baseDir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetFirstConfDir_NoConfDir_ReturnsNull()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-noconfdir-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var main = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(main, "domain=local\nconf-file=other.conf\n");
|
|
||||||
var first = DnsmasqConfIncludeParser.GetFirstConfDir(main);
|
|
||||||
Assert.Null(first);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetFirstConfDir_HasConfDir_ReturnsResolvedPath()
|
|
||||||
{
|
|
||||||
var baseDir = Path.Combine(Path.GetTempPath(), "dnsmasq-firstdir-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(baseDir);
|
|
||||||
var subDir = Path.Combine(baseDir, "dnsmasq.d");
|
|
||||||
Directory.CreateDirectory(subDir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var main = Path.Combine(baseDir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(main, "conf-dir=dnsmasq.d\n");
|
|
||||||
var first = DnsmasqConfIncludeParser.GetFirstConfDir(main);
|
|
||||||
Assert.NotNull(first);
|
|
||||||
Assert.Equal(Path.GetFullPath(subDir), first);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(baseDir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetIncludedPaths_CommentsAndBlanks_Ignored()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-comments-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var main = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(main, "# comment\n\n \nconf-file=extra.conf\n");
|
|
||||||
var extra = Path.Combine(dir, "extra.conf");
|
|
||||||
File.WriteAllText(extra, "");
|
|
||||||
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
|
||||||
Assert.Equal(2, paths.Count);
|
|
||||||
Assert.Equal(Path.GetFullPath(extra), paths[1]);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetIncludedPaths_testdata_dnsmasq_conf_ReturnsMainOnlyWhenConfDirMissing()
|
|
||||||
{
|
|
||||||
var mainPath = TestDataHelper.GetPath("dnsmasq.conf");
|
|
||||||
if (!File.Exists(mainPath))
|
|
||||||
return; // testdata not copied
|
|
||||||
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(mainPath);
|
|
||||||
Assert.Single(paths);
|
|
||||||
Assert.Equal(Path.GetFullPath(mainPath), paths[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetDhcpLeaseFilePathFromConfigFiles_FromTestdata_ReturnsLeasesPath()
|
|
||||||
{
|
|
||||||
var mainPath = TestDataHelper.GetPath("dnsmasq-test.conf");
|
|
||||||
if (!File.Exists(mainPath))
|
|
||||||
return;
|
|
||||||
var paths = new[] { mainPath };
|
|
||||||
var result = DnsmasqConfIncludeParser.GetDhcpLeaseFilePathFromConfigFiles(paths);
|
|
||||||
Assert.NotNull(result);
|
|
||||||
Assert.Equal(Path.GetFullPath("/data/leases"), result);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Uses testdata/dnsmasq-test.conf (harness main) to assert multi-value options are collected from testdata.</summary>
|
|
||||||
[Fact]
|
|
||||||
public void GetMultiValueFromConfigFiles_FromTestdata_ReturnsServerAndAddnHosts()
|
|
||||||
{
|
|
||||||
var mainPath = TestDataHelper.GetPath("dnsmasq-test.conf");
|
|
||||||
if (!File.Exists(mainPath))
|
|
||||||
return;
|
|
||||||
var paths = new[] { mainPath };
|
|
||||||
var servers = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.ServerLocalKeys);
|
|
||||||
var addnHosts = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFiles(paths);
|
|
||||||
var addresses = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.Address);
|
|
||||||
var listenAddrs = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(paths, DnsmasqConfKeys.ListenAddress);
|
|
||||||
Assert.True(servers.Count >= 2, "testdata dnsmasq-test.conf should have at least 2 server= lines");
|
|
||||||
Assert.Contains("1.1.1.1", servers);
|
|
||||||
Assert.Contains("8.8.8.8", servers);
|
|
||||||
Assert.True(addnHosts.Count >= 2, "testdata should have at least 2 addn-hosts paths");
|
|
||||||
Assert.True(addresses.Count >= 2, "testdata should have at least 2 address= lines");
|
|
||||||
Assert.Single(listenAddrs);
|
|
||||||
Assert.Equal("172.28.0.2", listenAddrs[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetDhcpLeaseFilePathFromConfigFiles_LastWins()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-lease-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var first = Path.Combine(dir, "first.conf");
|
|
||||||
File.WriteAllText(first, "dhcp-leasefile=/var/first.leases\n");
|
|
||||||
var second = Path.Combine(dir, "second.conf");
|
|
||||||
File.WriteAllText(second, "dhcp-leasefile=/var/second.leases\n");
|
|
||||||
var result = DnsmasqConfIncludeParser.GetDhcpLeaseFilePathFromConfigFiles(new[] { first, second });
|
|
||||||
Assert.Equal(Path.GetFullPath("/var/second.leases"), result);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetDhcpLeaseFilePathFromConfigFiles_RelativePath_ResolvedAgainstConfigDir()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-lease-rel-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var conf = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(conf, "dhcp-leasefile=subdir/leases\n");
|
|
||||||
var result = DnsmasqConfIncludeParser.GetDhcpLeaseFilePathFromConfigFiles(new[] { conf });
|
|
||||||
Assert.Equal(Path.GetFullPath(Path.Combine(dir, "subdir", "leases")), result);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetAddnHostsPathsFromConfigFiles_Empty_ReturnsEmpty()
|
|
||||||
{
|
|
||||||
var result = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFiles(Array.Empty<string>());
|
|
||||||
Assert.Empty(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetAddnHostsPathsFromConfigFiles_Cumulative_ReturnsAllInOrder()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-addn-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var first = Path.Combine(dir, "first.conf");
|
|
||||||
File.WriteAllText(first, "addn-hosts=/etc/hosts.d/first\n");
|
|
||||||
var second = Path.Combine(dir, "second.conf");
|
|
||||||
File.WriteAllText(second, "addn-hosts=/data/hosts\naddn-hosts=/data/extra.hosts\n");
|
|
||||||
var result = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFiles(new[] { first, second });
|
|
||||||
Assert.Equal(3, result.Count);
|
|
||||||
Assert.Equal(Path.GetFullPath("/etc/hosts.d/first"), result[0]);
|
|
||||||
Assert.Equal(Path.GetFullPath("/data/hosts"), result[1]);
|
|
||||||
Assert.Equal(Path.GetFullPath("/data/extra.hosts"), result[2]);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetAddnHostsPathsFromConfigFiles_RelativePath_ResolvedAgainstConfigDir()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-addn-rel-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var conf = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(conf, "addn-hosts=hosts.d/app.hosts\n");
|
|
||||||
var result = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFiles(new[] { conf });
|
|
||||||
Assert.Single(result);
|
|
||||||
Assert.Equal(Path.GetFullPath(Path.Combine(dir, "hosts.d", "app.hosts")), result[0]);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetFlagFromConfigFiles_OptionPresent_ReturnsTrue()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-flag-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var conf = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(conf, "expand-hosts\nno-resolv\n");
|
|
||||||
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.ExpandHosts);
|
|
||||||
Assert.True(result);
|
|
||||||
Assert.True(DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NoResolv));
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetFlagFromConfigFiles_OptionAbsent_ReturnsFalse()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-flag-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var conf = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(conf, "port=53\n");
|
|
||||||
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.NoHosts);
|
|
||||||
Assert.False(result);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetLastValueFromConfigFiles_LastWins()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-last-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
var f1 = Path.Combine(dir, "01.conf");
|
|
||||||
var f2 = Path.Combine(dir, "02.conf");
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.WriteAllText(f1, "cache-size=100\n");
|
|
||||||
File.WriteAllText(f2, "cache-size=200\n");
|
|
||||||
var (value, configDir) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { f1, f2 }, DnsmasqConfKeys.CacheSize);
|
|
||||||
Assert.Equal("200", value);
|
|
||||||
Assert.Equal(dir, configDir);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetLastValueFromConfigFiles_LogFacility_ReturnsValue()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-logfac-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var conf = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(conf, "log-facility=/data/dnsmasq.log\n");
|
|
||||||
var (value, configDir) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.LogFacility);
|
|
||||||
Assert.Equal("/data/dnsmasq.log", value);
|
|
||||||
Assert.Equal(dir, configDir);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetLastValueFromConfigFiles_LogFacility_LastWins()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-logfac2-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
var f1 = Path.Combine(dir, "01.conf");
|
|
||||||
var f2 = Path.Combine(dir, "02.conf");
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.WriteAllText(f1, "log-facility=/var/log/dnsmasq.log\n");
|
|
||||||
File.WriteAllText(f2, "log-facility=/data/dnsmasq.log\n");
|
|
||||||
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { f1, f2 }, DnsmasqConfKeys.LogFacility);
|
|
||||||
Assert.Equal("/data/dnsmasq.log", value);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ResolvePath_Relative_ResolvesAgainstDir()
|
|
||||||
{
|
|
||||||
var dir = Path.GetTempPath();
|
|
||||||
var result = DnsmasqConfIncludeParser.ResolvePath("sub/pid.pid", dir);
|
|
||||||
Assert.Equal(Path.GetFullPath(Path.Combine(dir, "sub", "pid.pid")), result);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ResolvePath_Absolute_ReturnsAsIs()
|
|
||||||
{
|
|
||||||
var abs = Path.Combine(Path.GetTempPath(), "absolute.pid");
|
|
||||||
var result = DnsmasqConfIncludeParser.ResolvePath(abs, "/some/dir");
|
|
||||||
Assert.Equal(Path.GetFullPath(abs), result);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Tests matching dnsmasq option.c semantics (ARG_ONE = last wins, flags = no value allowed) ---
|
|
||||||
|
|
||||||
/// <summary>dnsmasq option.c: opts[i].has_arg == 0 && arg -> "extraneous parameter"; flag with value is invalid, so we must not count it.</summary>
|
|
||||||
[Fact]
|
|
||||||
public void GetFlagFromConfigFiles_FlagWithValue_ReturnsFalse()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-flag-val-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var conf = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(conf, "expand-hosts=1\n");
|
|
||||||
var result = DnsmasqConfIncludeParser.GetFlagFromConfigFiles(new[] { conf }, DnsmasqConfKeys.ExpandHosts);
|
|
||||||
Assert.False(result);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>dnsmasq option.c: strcmp(opts[i].name, start) == 0 — option names are case-sensitive; "Port" is bad option.</summary>
|
|
||||||
[Fact]
|
|
||||||
public void GetLastValueFromConfigFiles_CaseSensitive_PortWithCapitalP_ReturnsNull()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-case-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var conf = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(conf, "Port=53\n");
|
|
||||||
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.Port);
|
|
||||||
Assert.Null(value);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Path list is [main, conf-file...]. We read each file entirely in that order, so last port is last occurrence in that stream (main lines then extra). Main has port=53, port=5353; extra has port=54 → last is 54.</summary>
|
|
||||||
[Fact]
|
|
||||||
public void GetLastValueFromConfigFiles_TwoFiles_LastOccurrenceInPathOrderWins()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-two-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
var main = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
var extra = Path.Combine(dir, "extra.conf");
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.WriteAllText(main, "port=53\nconf-file=extra.conf\nport=5353\n");
|
|
||||||
File.WriteAllText(extra, "port=54\n");
|
|
||||||
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
|
||||||
var (value, _) = DnsmasqConfIncludeParser.GetLastValueFromConfigFiles(paths, DnsmasqConfKeys.Port);
|
|
||||||
Assert.Equal("54", value);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>dnsmasq conf-dir=dir,*.suffix only includes files ending with suffix (option.c match_suffix).</summary>
|
|
||||||
[Fact]
|
|
||||||
public void GetIncludedPaths_ConfDir_WithMatchSuffix_OnlyIncludesMatchingFiles()
|
|
||||||
{
|
|
||||||
var baseDir = Path.Combine(Path.GetTempPath(), "dnsmasq-match-" + Guid.NewGuid().ToString("N"));
|
|
||||||
var subDir = Path.Combine(baseDir, "d");
|
|
||||||
Directory.CreateDirectory(subDir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.WriteAllText(Path.Combine(subDir, "a.conf"), "");
|
|
||||||
File.WriteAllText(Path.Combine(subDir, "b.txt"), "");
|
|
||||||
File.WriteAllText(Path.Combine(subDir, "c.conf"), "");
|
|
||||||
var main = Path.Combine(baseDir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(main, "conf-dir=d,*.conf\n");
|
|
||||||
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
|
||||||
Assert.Equal(3, paths.Count);
|
|
||||||
Assert.Contains(paths, p => p.EndsWith("a.conf", StringComparison.Ordinal));
|
|
||||||
Assert.Contains(paths, p => p.EndsWith("c.conf", StringComparison.Ordinal));
|
|
||||||
Assert.DoesNotContain(paths, p => p.EndsWith("b.txt", StringComparison.Ordinal));
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(baseDir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>dnsmasq conf-dir=dir,.suffix ignores files ending with suffix (option.c ignore_suffix).</summary>
|
|
||||||
[Fact]
|
|
||||||
public void GetIncludedPaths_ConfDir_WithIgnoreSuffix_ExcludesMatchingFiles()
|
|
||||||
{
|
|
||||||
var baseDir = Path.Combine(Path.GetTempPath(), "dnsmasq-ignore-" + Guid.NewGuid().ToString("N"));
|
|
||||||
var subDir = Path.Combine(baseDir, "d");
|
|
||||||
Directory.CreateDirectory(subDir);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.WriteAllText(Path.Combine(subDir, "a.conf"), "");
|
|
||||||
File.WriteAllText(Path.Combine(subDir, "b.conf.bak"), "");
|
|
||||||
var main = Path.Combine(baseDir, "dnsmasq.conf");
|
|
||||||
File.WriteAllText(main, "conf-dir=d,.bak\n");
|
|
||||||
var paths = DnsmasqConfIncludeParser.GetIncludedPaths(main);
|
|
||||||
Assert.Equal(2, paths.Count);
|
|
||||||
Assert.Contains(paths, p => p.EndsWith("a.conf", StringComparison.Ordinal));
|
|
||||||
Assert.DoesNotContain(paths, p => p.EndsWith("b.conf.bak", StringComparison.Ordinal));
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(baseDir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetAddnHostsPathsFromConfigFilesWithSource_ReturnsSourcePerPath()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-addn-src-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
var f1 = Path.Combine(dir, "01.conf");
|
|
||||||
var f2 = Path.Combine(dir, "02.conf");
|
|
||||||
var managedPath = Path.Combine(dir, "managed.conf");
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.WriteAllText(f1, "addn-hosts=/etc/hosts.a\n");
|
|
||||||
File.WriteAllText(f2, "addn-hosts=/etc/hosts.b\naddn-hosts=/etc/hosts.c\n");
|
|
||||||
var result = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFilesWithSource(new[] { f1, f2 }, managedPath);
|
|
||||||
Assert.Equal(3, result.Count);
|
|
||||||
Assert.Equal(Path.GetFullPath("/etc/hosts.a"), result[0].Path);
|
|
||||||
Assert.Equal(Path.GetFileName(f1), result[0].Source.FileName);
|
|
||||||
Assert.False(result[0].Source.IsManaged);
|
|
||||||
Assert.Equal(1, result[0].Source.LineNumber);
|
|
||||||
Assert.Equal(Path.GetFullPath("/etc/hosts.b"), result[1].Path);
|
|
||||||
Assert.Equal(Path.GetFileName(f2), result[1].Source.FileName);
|
|
||||||
Assert.Equal(1, result[1].Source.LineNumber);
|
|
||||||
Assert.Equal(Path.GetFullPath("/etc/hosts.c"), result[2].Path);
|
|
||||||
Assert.Equal(2, result[2].Source.LineNumber);
|
|
||||||
Assert.True(result[2].Source.IsReadOnly == !result[2].Source.IsManaged);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetAddnHostsPathsFromConfigFilesWithSource_WhenManagedFileInList_IsManagedTrue()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-addn-mgd-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
var mainPath = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
var managedPath = Path.Combine(dir, "zz-managed.conf");
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.WriteAllText(mainPath, "addn-hosts=/other/hosts\n");
|
|
||||||
File.WriteAllText(managedPath, "addn-hosts=/managed/hosts\n");
|
|
||||||
var result = DnsmasqConfIncludeParser.GetAddnHostsPathsFromConfigFilesWithSource(new[] { mainPath, managedPath }, managedPath);
|
|
||||||
Assert.Equal(2, result.Count);
|
|
||||||
Assert.False(result[0].Source.IsManaged);
|
|
||||||
Assert.Equal(1, result[0].Source.LineNumber);
|
|
||||||
Assert.True(result[1].Source.IsManaged);
|
|
||||||
Assert.Equal(1, result[1].Source.LineNumber);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetMultiValueFromConfigFiles_ServerAndLocal_CollectsBothInOrder()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-multi-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
var f1 = Path.Combine(dir, "01.conf");
|
|
||||||
var f2 = Path.Combine(dir, "02.conf");
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.WriteAllText(f1, "server=1.1.1.1\nlocal=/local/\n");
|
|
||||||
File.WriteAllText(f2, "server=/example.com/192.168.1.1\n");
|
|
||||||
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { f1, f2 }, DnsmasqConfKeys.ServerLocalKeys);
|
|
||||||
Assert.Equal(3, result.Count);
|
|
||||||
Assert.Equal("1.1.1.1", result[0]);
|
|
||||||
Assert.Equal("/local/", result[1]);
|
|
||||||
Assert.Equal("/example.com/192.168.1.1", result[2]);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetMultiValueFromConfigFiles_DhcpRange_CollectsAllInOrder()
|
|
||||||
{
|
|
||||||
var dir = Path.Combine(Path.GetTempPath(), "dnsmasq-dhcp-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(dir);
|
|
||||||
var conf = Path.Combine(dir, "dnsmasq.conf");
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.WriteAllText(conf, "dhcp-range=172.28.0.10,172.28.0.50,12h\ndhcp-range=192.168.1.10,192.168.1.100,255.255.255.0,24h\n");
|
|
||||||
var result = DnsmasqConfIncludeParser.GetMultiValueFromConfigFiles(new[] { conf }, DnsmasqConfKeys.DhcpRange);
|
|
||||||
Assert.Equal(2, result.Count);
|
|
||||||
Assert.Equal("172.28.0.10,172.28.0.50,12h", result[0]);
|
|
||||||
Assert.Equal("192.168.1.10,192.168.1.100,255.255.255.0,24h", result[1]);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Directory.Delete(dir, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using DnsmasqWebUI.Configuration;
|
using DnsmasqWebUI.Models.Config;
|
||||||
using DnsmasqWebUI.Models.EffectiveConfig;
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
using DnsmasqWebUI.Services;
|
using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Services.Dnsmasq.Config;
|
||||||
using Microsoft.Extensions.Logging.Abstractions;
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
@@ -24,7 +25,8 @@ public class DnsmasqConfigSetServiceTests
|
|||||||
Assert.Empty(config.AddnHostsPaths);
|
Assert.Empty(config.AddnHostsPaths);
|
||||||
Assert.NotNull(sources);
|
Assert.NotNull(sources);
|
||||||
Assert.Empty(sources.AddnHostsPaths);
|
Assert.Empty(sources.AddnHostsPaths);
|
||||||
Assert.Empty(sources.ServerLocalValues);
|
Assert.Empty(sources.ServerValues);
|
||||||
|
Assert.Empty(sources.LocalValues);
|
||||||
Assert.Empty(sources.DhcpRanges);
|
Assert.Empty(sources.DhcpRanges);
|
||||||
Assert.Null(sources.NoHosts);
|
Assert.Null(sources.NoHosts);
|
||||||
Assert.Null(sources.Port);
|
Assert.Null(sources.Port);
|
||||||
@@ -40,7 +42,10 @@ public class DnsmasqConfigSetServiceTests
|
|||||||
ConfigSetCache? cache = null;
|
ConfigSetCache? cache = null;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
File.WriteAllText(mainPath, "port=53\ncache-size=500\naddn-hosts=/etc/hosts.extra\n");
|
int port = 53;
|
||||||
|
int cacheSize = 500;
|
||||||
|
var addnHostsPath = "/etc/hosts.extra";
|
||||||
|
File.WriteAllText(mainPath, $"port={port}\ncache-size={cacheSize}\naddn-hosts={addnHostsPath}\n");
|
||||||
var options = Options.Create(new DnsmasqOptions
|
var options = Options.Create(new DnsmasqOptions
|
||||||
{
|
{
|
||||||
MainConfigPath = mainPath,
|
MainConfigPath = mainPath,
|
||||||
@@ -51,11 +56,12 @@ public class DnsmasqConfigSetServiceTests
|
|||||||
var (config, sources) = service.GetEffectiveConfigWithSources();
|
var (config, sources) = service.GetEffectiveConfigWithSources();
|
||||||
|
|
||||||
Assert.NotNull(config);
|
Assert.NotNull(config);
|
||||||
Assert.Equal(53, config.Port);
|
Assert.Equal(port, config.Port);
|
||||||
Assert.Equal(500, config.CacheSize);
|
Assert.Equal(cacheSize, config.CacheSize);
|
||||||
Assert.Single(config.AddnHostsPaths);
|
Assert.Single(config.AddnHostsPaths);
|
||||||
Assert.Equal(Path.GetFullPath("/etc/hosts.extra"), config.AddnHostsPaths[0]);
|
Assert.Equal(Path.GetFullPath(addnHostsPath), config.AddnHostsPaths[0]);
|
||||||
Assert.Empty(config.ServerLocalValues);
|
Assert.Empty(config.ServerValues);
|
||||||
|
Assert.Empty(config.LocalValues);
|
||||||
Assert.Empty(config.DhcpRanges);
|
Assert.Empty(config.DhcpRanges);
|
||||||
|
|
||||||
Assert.NotNull(sources);
|
Assert.NotNull(sources);
|
||||||
@@ -63,7 +69,7 @@ public class DnsmasqConfigSetServiceTests
|
|||||||
Assert.Equal(Path.GetFileName(mainPath), sources.Port!.FileName);
|
Assert.Equal(Path.GetFileName(mainPath), sources.Port!.FileName);
|
||||||
Assert.NotNull(sources.CacheSize);
|
Assert.NotNull(sources.CacheSize);
|
||||||
Assert.Single(sources.AddnHostsPaths);
|
Assert.Single(sources.AddnHostsPaths);
|
||||||
Assert.Equal(Path.GetFullPath("/etc/hosts.extra"), sources.AddnHostsPaths[0].Path);
|
Assert.Equal(Path.GetFullPath(addnHostsPath), sources.AddnHostsPaths[0].Path);
|
||||||
Assert.NotNull(sources.AddnHostsPaths[0].Source);
|
Assert.NotNull(sources.AddnHostsPaths[0].Source);
|
||||||
Assert.Equal(Path.GetFileName(mainPath), sources.AddnHostsPaths[0].Source!.FileName);
|
Assert.Equal(Path.GetFileName(mainPath), sources.AddnHostsPaths[0].Source!.FileName);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
using DnsmasqWebUI.Models.Dhcp;
|
using DnsmasqWebUI.Models.Dhcp;
|
||||||
using DnsmasqWebUI.Parsers;
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Tests;
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
@@ -19,63 +19,113 @@ public class DnsmasqLeasesFileLineParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_ValidFiveFields_Parses()
|
public void ParseLine_ValidFiveFields_Parses()
|
||||||
{
|
{
|
||||||
var e = DnsmasqLeasesFileLineParser.ParseLine("946689575 00:00:00:00:00:05 192.168.1.155 wdt 01:00:00:00:00:00:05");
|
long epoch = 946689575;
|
||||||
|
string mac = "00:00:00:00:00:05";
|
||||||
|
string address = "192.168.1.155";
|
||||||
|
string name = "wdt";
|
||||||
|
string clientId = "01:00:00:00:00:00:05";
|
||||||
|
|
||||||
|
var line = $"{epoch} {mac} {address} {name} {clientId}";
|
||||||
|
var e = DnsmasqLeasesFileLineParser.ParseLine(line);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal(946689575, e!.Epoch);
|
Assert.Equal(epoch, e!.Epoch);
|
||||||
Assert.Equal("00:00:00:00:00:05", e.Mac);
|
Assert.Equal(mac, e.Mac);
|
||||||
Assert.Equal("192.168.1.155", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
Assert.Equal("wdt", e.Name);
|
Assert.Equal(name, e.Name);
|
||||||
Assert.Equal("01:00:00:00:00:00:05", e.ClientId);
|
Assert.Equal(clientId, e.ClientId);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_UnknownHostname_Asterisk()
|
public void ParseLine_UnknownHostname_Asterisk()
|
||||||
{
|
{
|
||||||
var e = DnsmasqLeasesFileLineParser.ParseLine("946689522 00:00:00:00:00:04 192.168.1.237 * 01:00:00:00:00:00:04");
|
long epoch = 946689522;
|
||||||
|
string mac = "00:00:00:00:00:04";
|
||||||
|
string address = "192.168.1.237";
|
||||||
|
string name = "*";
|
||||||
|
string clientId = "01:00:00:00:00:00:04";
|
||||||
|
|
||||||
|
var line = $"{epoch} {mac} {address} {name} {clientId}";
|
||||||
|
var e = DnsmasqLeasesFileLineParser.ParseLine(line);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("*", e!.Name);
|
Assert.Equal(name, e!.Name);
|
||||||
Assert.Equal("192.168.1.237", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_UnknownClientId_Asterisk()
|
public void ParseLine_UnknownClientId_Asterisk()
|
||||||
{
|
{
|
||||||
var e = DnsmasqLeasesFileLineParser.ParseLine("946689351 00:0f:b0:3a:b5:0b 192.168.1.208 colinux *");
|
long epoch = 946689351;
|
||||||
|
string mac = "00:0f:b0:3a:b5:0b";
|
||||||
|
string address = "192.168.1.208";
|
||||||
|
string name = "colinux";
|
||||||
|
string clientId = "*";
|
||||||
|
|
||||||
|
var line = $"{epoch} {mac} {address} {name} {clientId}";
|
||||||
|
var e = DnsmasqLeasesFileLineParser.ParseLine(line);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("colinux", e!.Name);
|
Assert.Equal(name, e!.Name);
|
||||||
Assert.Equal("*", e.ClientId);
|
Assert.Equal(clientId, e.ClientId);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_MultipleSpacesBetweenFields_Parses()
|
public void ParseLine_MultipleSpacesBetweenFields_Parses()
|
||||||
{
|
{
|
||||||
var e = DnsmasqLeasesFileLineParser.ParseLine(" 946689575 00:00:00:00:00:05 192.168.1.155 wdt 01:00:00:00:00:00:05 ");
|
long epoch = 946689575;
|
||||||
|
string mac = "00:00:00:00:00:05";
|
||||||
|
string address = "192.168.1.155";
|
||||||
|
string name = "wdt";
|
||||||
|
string clientId = "01:00:00:00:00:00:05";
|
||||||
|
|
||||||
|
var line = $" {epoch} {mac} {address} {name} {clientId} ";
|
||||||
|
var e = DnsmasqLeasesFileLineParser.ParseLine(line);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal(946689575, e!.Epoch);
|
Assert.Equal(epoch, e!.Epoch);
|
||||||
Assert.Equal("00:00:00:00:00:05", e.Mac);
|
Assert.Equal(mac, e.Mac);
|
||||||
Assert.Equal("192.168.1.155", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
Assert.Equal("wdt", e.Name);
|
Assert.Equal(name, e.Name);
|
||||||
Assert.Equal("01:00:00:00:00:00:05", e.ClientId);
|
Assert.Equal(clientId, e.ClientId);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_TooFewFields_ReturnsNull()
|
public void ParseLine_TooFewFields_ReturnsNull()
|
||||||
{
|
{
|
||||||
Assert.Null(DnsmasqLeasesFileLineParser.ParseLine("946689575 00:00:00:00:00:05 192.168.1.155"));
|
long epoch = 946689575;
|
||||||
Assert.Null(DnsmasqLeasesFileLineParser.ParseLine("946689575 00:00:00:00:00:05"));
|
string mac = "00:00:00:00:00:05";
|
||||||
|
string address = "192.168.1.155";
|
||||||
|
|
||||||
|
Assert.Null(DnsmasqLeasesFileLineParser.ParseLine($"{epoch} {mac} {address}"));
|
||||||
|
Assert.Null(DnsmasqLeasesFileLineParser.ParseLine($"{epoch} {mac}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_TrailingJunk_ReturnsNull()
|
public void ParseLine_TrailingJunk_ReturnsNull()
|
||||||
{
|
{
|
||||||
// Parser uses .End() so extra text after fifth field fails
|
// Parser uses .End() so extra text after fifth field fails
|
||||||
Assert.Null(DnsmasqLeasesFileLineParser.ParseLine("946689575 00:00:00:00:00:05 192.168.1.155 wdt 01:00:00:00:00:00:05 extra"));
|
long epoch = 946689575;
|
||||||
|
string mac = "00:00:00:00:00:05";
|
||||||
|
string address = "192.168.1.155";
|
||||||
|
string name = "wdt";
|
||||||
|
string clientId = "01:00:00:00:00:00:05";
|
||||||
|
|
||||||
|
var line = $"{epoch} {mac} {address} {name} {clientId} extra";
|
||||||
|
Assert.Null(DnsmasqLeasesFileLineParser.ParseLine(line));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_InvalidEpoch_ReturnsNull()
|
public void ParseLine_InvalidEpoch_ReturnsNull()
|
||||||
{
|
{
|
||||||
Assert.Null(DnsmasqLeasesFileLineParser.ParseLine("notanum 00:00:00:00:00:05 192.168.1.155 wdt 01:00:00:00:00:00:05"));
|
string invalidEpoch = "notanum";
|
||||||
|
string mac = "00:00:00:00:00:05";
|
||||||
|
string address = "192.168.1.155";
|
||||||
|
string name = "wdt";
|
||||||
|
string clientId = "01:00:00:00:00:00:05";
|
||||||
|
|
||||||
|
var line = $"{invalidEpoch} {mac} {address} {name} {clientId}";
|
||||||
|
Assert.Null(DnsmasqLeasesFileLineParser.ParseLine(line));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -90,9 +140,18 @@ public class DnsmasqLeasesFileLineParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void Timestamp_ConvertsEpochToDateTime()
|
public void Timestamp_ConvertsEpochToDateTime()
|
||||||
{
|
{
|
||||||
var e = DnsmasqLeasesFileLineParser.ParseLine("946689575 00:00:00:00:00:05 192.168.1.155 wdt 01:00:00:00:00:00:05");
|
long epoch = 946689575;
|
||||||
|
string mac = "00:00:00:00:00:05";
|
||||||
|
string address = "192.168.1.155";
|
||||||
|
string name = "wdt";
|
||||||
|
string clientId = "01:00:00:00:00:00:05";
|
||||||
|
|
||||||
|
var line = $"{epoch} {mac} {address} {name} {clientId}";
|
||||||
|
var e = DnsmasqLeasesFileLineParser.ParseLine(line);
|
||||||
|
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
var dt = e!.Timestamp;
|
Assert.Equal(epoch, e!.Epoch);
|
||||||
|
var dt = e.Timestamp;
|
||||||
Assert.True(dt.Year >= 1999 && dt.Year <= 2000); // epoch 946689575 is ~1999-12
|
Assert.True(dt.Year >= 1999 && dt.Year <= 2000); // epoch 946689575 is ~1999-12
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<IsPackable>false</IsPackable>
|
<IsPackable>false</IsPackable>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
using DnsmasqWebUI.Models.EffectiveConfig;
|
using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig;
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Tests;
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
@@ -11,7 +11,10 @@ public class EffectiveDnsmasqConfigTests
|
|||||||
new(
|
new(
|
||||||
NoHosts: false,
|
NoHosts: false,
|
||||||
AddnHostsPaths: Array.Empty<string>(),
|
AddnHostsPaths: Array.Empty<string>(),
|
||||||
ServerLocalValues: Array.Empty<string>(),
|
HostsdirPath: null,
|
||||||
|
ServerValues: Array.Empty<string>(),
|
||||||
|
LocalValues: Array.Empty<string>(),
|
||||||
|
RevServerValues: Array.Empty<string>(),
|
||||||
AddressValues: Array.Empty<string>(),
|
AddressValues: Array.Empty<string>(),
|
||||||
Interfaces: Array.Empty<string>(),
|
Interfaces: Array.Empty<string>(),
|
||||||
ListenAddresses: Array.Empty<string>(),
|
ListenAddresses: Array.Empty<string>(),
|
||||||
@@ -19,17 +22,74 @@ public class EffectiveDnsmasqConfigTests
|
|||||||
DhcpRanges: Array.Empty<string>(),
|
DhcpRanges: Array.Empty<string>(),
|
||||||
DhcpHostLines: Array.Empty<string>(),
|
DhcpHostLines: Array.Empty<string>(),
|
||||||
DhcpOptionLines: Array.Empty<string>(),
|
DhcpOptionLines: Array.Empty<string>(),
|
||||||
|
DhcpMatchValues: Array.Empty<string>(),
|
||||||
|
DhcpBootValues: Array.Empty<string>(),
|
||||||
|
DhcpIgnoreValues: Array.Empty<string>(),
|
||||||
|
DhcpVendorclassValues: Array.Empty<string>(),
|
||||||
|
DhcpUserclassValues: Array.Empty<string>(),
|
||||||
|
RaParamValues: Array.Empty<string>(),
|
||||||
|
SlaacValues: Array.Empty<string>(),
|
||||||
|
PxeServiceValues: Array.Empty<string>(),
|
||||||
|
TrustAnchorValues: Array.Empty<string>(),
|
||||||
ResolvFiles: Array.Empty<string>(),
|
ResolvFiles: Array.Empty<string>(),
|
||||||
|
RebindDomainOkValues: Array.Empty<string>(),
|
||||||
|
BogusNxdomainValues: Array.Empty<string>(),
|
||||||
|
IgnoreAddressValues: Array.Empty<string>(),
|
||||||
|
AliasValues: Array.Empty<string>(),
|
||||||
|
FilterRrValues: Array.Empty<string>(),
|
||||||
|
CacheRrValues: Array.Empty<string>(),
|
||||||
|
AuthServerValues: Array.Empty<string>(),
|
||||||
|
NoDhcpInterfaceValues: Array.Empty<string>(),
|
||||||
|
NoDhcpv4InterfaceValues: Array.Empty<string>(),
|
||||||
|
NoDhcpv6InterfaceValues: Array.Empty<string>(),
|
||||||
|
DomainValues: Array.Empty<string>(), CnameValues: Array.Empty<string>(), MxHostValues: Array.Empty<string>(), SrvValues: Array.Empty<string>(),
|
||||||
|
PtrRecordValues: Array.Empty<string>(), TxtRecordValues: Array.Empty<string>(), NaptrRecordValues: Array.Empty<string>(),
|
||||||
|
HostRecordValues: Array.Empty<string>(), DynamicHostValues: Array.Empty<string>(), InterfaceNameValues: Array.Empty<string>(),
|
||||||
|
DhcpOptionForceLines: Array.Empty<string>(),
|
||||||
|
IpsetValues: Array.Empty<string>(),
|
||||||
|
NftsetValues: Array.Empty<string>(),
|
||||||
|
DhcpMacValues: Array.Empty<string>(),
|
||||||
|
DhcpNameMatchValues: Array.Empty<string>(),
|
||||||
|
DhcpIgnoreNamesValues: Array.Empty<string>(),
|
||||||
|
DhcpHostsfilePaths: Array.Empty<string>(),
|
||||||
|
DhcpOptsfilePaths: Array.Empty<string>(),
|
||||||
|
DhcpHostsdirPaths: Array.Empty<string>(),
|
||||||
ExpandHosts: false,
|
ExpandHosts: false,
|
||||||
BogusPriv: false,
|
BogusPriv: false,
|
||||||
StrictOrder: false,
|
StrictOrder: false,
|
||||||
|
AllServers: false,
|
||||||
NoResolv: false,
|
NoResolv: false,
|
||||||
DomainNeeded: false,
|
DomainNeeded: false,
|
||||||
NoPoll: false,
|
NoPoll: false,
|
||||||
BindInterfaces: false,
|
BindInterfaces: false,
|
||||||
|
BindDynamic: false,
|
||||||
NoNegcache: false,
|
NoNegcache: false,
|
||||||
|
DnsLoopDetect: false,
|
||||||
|
StopDnsRebind: false,
|
||||||
|
RebindLocalhostOk: false,
|
||||||
|
ClearOnReload: false,
|
||||||
|
Filterwin2k: false,
|
||||||
|
FilterA: false,
|
||||||
|
FilterAaaa: false,
|
||||||
|
LocaliseQueries: false,
|
||||||
|
LogDebug: false,
|
||||||
DhcpAuthoritative: false,
|
DhcpAuthoritative: false,
|
||||||
LeasefileRo: false,
|
LeasefileRo: false,
|
||||||
|
EnableTftp: false,
|
||||||
|
TftpSecure: false,
|
||||||
|
TftpNoFail: false,
|
||||||
|
TftpNoBlocksize: false,
|
||||||
|
Dnssec: false,
|
||||||
|
DnssecCheckUnsigned: false,
|
||||||
|
ReadEthers: false,
|
||||||
|
DhcpRapidCommit: false,
|
||||||
|
Localmx: false,
|
||||||
|
Selfmx: false,
|
||||||
|
EnableRa: false,
|
||||||
|
LogDhcp: false,
|
||||||
|
KeepInForeground: false,
|
||||||
|
NoDaemon: false,
|
||||||
|
ProxyDnssec: false,
|
||||||
DhcpLeaseFilePath: null,
|
DhcpLeaseFilePath: null,
|
||||||
CacheSize: null,
|
CacheSize: null,
|
||||||
Port: null,
|
Port: null,
|
||||||
@@ -38,12 +98,29 @@ public class EffectiveDnsmasqConfigTests
|
|||||||
User: null,
|
User: null,
|
||||||
Group: null,
|
Group: null,
|
||||||
LogFacility: logFacility,
|
LogFacility: logFacility,
|
||||||
|
LogQueries: null,
|
||||||
|
AuthTtl: null,
|
||||||
|
EdnsPacketMax: null,
|
||||||
|
QueryPort: null,
|
||||||
|
PortLimit: null,
|
||||||
|
MinPort: null,
|
||||||
|
MaxPort: null,
|
||||||
|
LogAsync: null,
|
||||||
|
LocalService: null,
|
||||||
DhcpLeaseMax: null,
|
DhcpLeaseMax: null,
|
||||||
NegTtl: null,
|
NegTtl: null,
|
||||||
MaxTtl: null,
|
MaxTtl: null,
|
||||||
MaxCacheTtl: null,
|
MaxCacheTtl: null,
|
||||||
MinCacheTtl: null,
|
MinCacheTtl: null,
|
||||||
DhcpTtl: null
|
DhcpTtl: null,
|
||||||
|
TftpRootPath: null,
|
||||||
|
PxePrompt: null,
|
||||||
|
EnableDbus: null,
|
||||||
|
EnableUbus: null,
|
||||||
|
FastDnsRetry: null,
|
||||||
|
DhcpScriptPath: null,
|
||||||
|
MxTarget: null,
|
||||||
|
Conntrack: null
|
||||||
);
|
);
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -76,35 +153,41 @@ public class EffectiveDnsmasqConfigTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void GetLogsPath_AbsolutePath_ReturnsPath()
|
public void GetLogsPath_AbsolutePath_ReturnsPath()
|
||||||
{
|
{
|
||||||
var config = CreateConfig(logFacility: "/data/dnsmasq.log");
|
var path = "/data/dnsmasq.log";
|
||||||
Assert.Equal("/data/dnsmasq.log", EffectiveDnsmasqConfig.GetLogsPath(config));
|
var config = CreateConfig(logFacility: path);
|
||||||
|
Assert.Equal(path, EffectiveDnsmasqConfig.GetLogsPath(config));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void GetLogsPath_AbsolutePathWithTrim_ReturnsPath()
|
public void GetLogsPath_AbsolutePathWithTrim_ReturnsPath()
|
||||||
{
|
{
|
||||||
var config = CreateConfig(logFacility: " /var/log/dnsmasq.log ");
|
var path = "/var/log/dnsmasq.log";
|
||||||
Assert.Equal("/var/log/dnsmasq.log", EffectiveDnsmasqConfig.GetLogsPath(config));
|
var pathWithSpaces = $" {path} ";
|
||||||
|
var config = CreateConfig(logFacility: pathWithSpaces);
|
||||||
|
Assert.Equal(path, EffectiveDnsmasqConfig.GetLogsPath(config));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void GetLogsPath_RelativePathWithSlash_ReturnsPath()
|
public void GetLogsPath_RelativePathWithSlash_ReturnsPath()
|
||||||
{
|
{
|
||||||
var config = CreateConfig(logFacility: "logs/dnsmasq.log");
|
var path = "logs/dnsmasq.log";
|
||||||
Assert.Equal("logs/dnsmasq.log", EffectiveDnsmasqConfig.GetLogsPath(config));
|
var config = CreateConfig(logFacility: path);
|
||||||
|
Assert.Equal(path, EffectiveDnsmasqConfig.GetLogsPath(config));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void GetLogsPath_SyslogFacilityName_ReturnsNull()
|
public void GetLogsPath_SyslogFacilityName_ReturnsNull()
|
||||||
{
|
{
|
||||||
var config = CreateConfig(logFacility: "local0");
|
var facility = "local0";
|
||||||
|
var config = CreateConfig(logFacility: facility);
|
||||||
Assert.Null(EffectiveDnsmasqConfig.GetLogsPath(config));
|
Assert.Null(EffectiveDnsmasqConfig.GetLogsPath(config));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void GetLogsPath_Stderr_ReturnsNull()
|
public void GetLogsPath_Stderr_ReturnsNull()
|
||||||
{
|
{
|
||||||
var config = CreateConfig(logFacility: "-");
|
var facility = "-";
|
||||||
|
var config = CreateConfig(logFacility: facility);
|
||||||
Assert.Null(EffectiveDnsmasqConfig.GetLogsPath(config));
|
Assert.Null(EffectiveDnsmasqConfig.GetLogsPath(config));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
using DnsmasqWebUI.Models.Hosts;
|
using DnsmasqWebUI.Models.Hosts;
|
||||||
using DnsmasqWebUI.Parsers;
|
using DnsmasqWebUI.Infrastructure.Parsers;
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Tests;
|
namespace DnsmasqWebUI.Tests;
|
||||||
|
|
||||||
@@ -22,7 +22,8 @@ public class HostsFileLineParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_WhitespaceOnly_ReturnsPassthrough()
|
public void ParseLine_WhitespaceOnly_ReturnsPassthrough()
|
||||||
{
|
{
|
||||||
var e = HostsFileLineParser.ParseLine(" \t ", 2);
|
var raw = " \t ";
|
||||||
|
var e = HostsFileLineParser.ParseLine(raw, 2);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.True(e!.IsPassthrough);
|
Assert.True(e!.IsPassthrough);
|
||||||
}
|
}
|
||||||
@@ -30,7 +31,8 @@ public class HostsFileLineParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_CommentOnly_TreatsWholeLineAsComment()
|
public void ParseLine_CommentOnly_TreatsWholeLineAsComment()
|
||||||
{
|
{
|
||||||
var e = HostsFileLineParser.ParseLine("# This is a comment", 1);
|
var commentLine = "# This is a comment";
|
||||||
|
var e = HostsFileLineParser.ParseLine(commentLine, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.True(e!.IsComment);
|
Assert.True(e!.IsComment);
|
||||||
Assert.True(e.IsPassthrough);
|
Assert.True(e.IsPassthrough);
|
||||||
@@ -42,7 +44,10 @@ public class HostsFileLineParserTests
|
|||||||
public void ParseLine_CommentWithDataLikeContent_DoesNotParseAsAddress()
|
public void ParseLine_CommentWithDataLikeContent_DoesNotParseAsAddress()
|
||||||
{
|
{
|
||||||
// Per hosts(5): text from # to EOL is comment - so "# 127.0.0.1 localhost" is entirely comment
|
// Per hosts(5): text from # to EOL is comment - so "# 127.0.0.1 localhost" is entirely comment
|
||||||
var e = HostsFileLineParser.ParseLine("# 127.0.0.1 localhost", 1);
|
string address = "127.0.0.1";
|
||||||
|
string name = "localhost";
|
||||||
|
var line = $"# {address} {name}";
|
||||||
|
var e = HostsFileLineParser.ParseLine(line, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.True(e!.IsComment);
|
Assert.True(e!.IsComment);
|
||||||
Assert.Equal("", e.Address);
|
Assert.Equal("", e.Address);
|
||||||
@@ -52,75 +57,99 @@ public class HostsFileLineParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_IPv4Localhost_ParsesAddressAndName()
|
public void ParseLine_IPv4Localhost_ParsesAddressAndName()
|
||||||
{
|
{
|
||||||
var e = HostsFileLineParser.ParseLine("127.0.0.1 localhost", 1);
|
string address = "127.0.0.1";
|
||||||
|
string name = "localhost";
|
||||||
|
var line = $"{address} {name}";
|
||||||
|
var e = HostsFileLineParser.ParseLine(line, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.False(e!.IsPassthrough);
|
Assert.False(e!.IsPassthrough);
|
||||||
Assert.Equal("127.0.0.1", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
Assert.Single(e.Names);
|
Assert.Single(e.Names);
|
||||||
Assert.Equal("localhost", e.Names[0]);
|
Assert.Equal(name, e.Names[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_IPv4WithCanonicalAndAlias_ParsesAll()
|
public void ParseLine_IPv4WithCanonicalAndAlias_ParsesAll()
|
||||||
{
|
{
|
||||||
var e = HostsFileLineParser.ParseLine("127.0.1.1 thishost.example.org thishost", 1);
|
string address = "127.0.1.1";
|
||||||
|
string canonical = "thishost.example.org";
|
||||||
|
string alias = "thishost";
|
||||||
|
var line = $"{address} {canonical} {alias}";
|
||||||
|
var e = HostsFileLineParser.ParseLine(line, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("127.0.1.1", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
Assert.True(e.Names.Count >= 1);
|
Assert.True(e.Names.Count >= 1);
|
||||||
Assert.Equal("thishost.example.org", e.Names[0]);
|
Assert.Equal(canonical, e.Names[0]);
|
||||||
if (e.Names.Count >= 2)
|
if (e.Names.Count >= 2)
|
||||||
Assert.Equal("thishost", e.Names[1]);
|
Assert.Equal(alias, e.Names[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_IPv4WithMultipleSpaces_ParsesCorrectly()
|
public void ParseLine_IPv4WithMultipleSpaces_ParsesCorrectly()
|
||||||
{
|
{
|
||||||
var e = HostsFileLineParser.ParseLine("192.168.1.10 foo.example.org foo", 1);
|
string address = "192.168.1.10";
|
||||||
|
string name1 = "foo.example.org";
|
||||||
|
string name2 = "foo";
|
||||||
|
var line = $"{address} {name1} {name2}";
|
||||||
|
var e = HostsFileLineParser.ParseLine(line, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("192.168.1.10", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
Assert.True(e.Names.Count >= 1);
|
Assert.True(e.Names.Count >= 1);
|
||||||
Assert.Equal("foo.example.org", e.Names[0]);
|
Assert.Equal(name1, e.Names[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_IPv6_ParsesAddressAndNames()
|
public void ParseLine_IPv6_ParsesAddressAndNames()
|
||||||
{
|
{
|
||||||
var e = HostsFileLineParser.ParseLine("::1 localhost ip6-localhost ip6-loopback", 1);
|
string address = "::1";
|
||||||
|
string name1 = "localhost";
|
||||||
|
var line = $"{address} {name1} ip6-localhost ip6-loopback";
|
||||||
|
var e = HostsFileLineParser.ParseLine(line, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("::1", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
Assert.True(e.Names.Count >= 1);
|
Assert.True(e.Names.Count >= 1);
|
||||||
Assert.Equal("localhost", e.Names[0]);
|
Assert.Equal(name1, e.Names[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_IPv6Multicast_Parses()
|
public void ParseLine_IPv6Multicast_Parses()
|
||||||
{
|
{
|
||||||
var e = HostsFileLineParser.ParseLine("ff02::1 ip6-allnodes", 1);
|
string address = "ff02::1";
|
||||||
|
string name = "ip6-allnodes";
|
||||||
|
var line = $"{address} {name}";
|
||||||
|
var e = HostsFileLineParser.ParseLine(line, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("ff02::1", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
Assert.Single(e.Names);
|
Assert.Single(e.Names);
|
||||||
Assert.Equal("ip6-allnodes", e.Names[0]);
|
Assert.Equal(name, e.Names[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_InlineComment_StopsAtHash()
|
public void ParseLine_InlineComment_StopsAtHash()
|
||||||
{
|
{
|
||||||
// Token stops at #; only address and names before # are parsed
|
// Token stops at #; only address and names before # are parsed
|
||||||
var e = HostsFileLineParser.ParseLine("127.0.0.1 localhost # loopback", 1);
|
string address = "127.0.0.1";
|
||||||
|
string name = "localhost";
|
||||||
|
string comment = "loopback";
|
||||||
|
var line = $"{address} {name} # {comment}";
|
||||||
|
var e = HostsFileLineParser.ParseLine(line, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("127.0.0.1", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
Assert.Single(e.Names);
|
Assert.Single(e.Names);
|
||||||
Assert.Equal("localhost", e.Names[0]);
|
Assert.Equal(name, e.Names[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ParseLine_LeadingWhitespace_TrimmedAndParsed()
|
public void ParseLine_LeadingWhitespace_TrimmedAndParsed()
|
||||||
{
|
{
|
||||||
var e = HostsFileLineParser.ParseLine(" 192.168.1.13 bar", 1);
|
string address = "192.168.1.13";
|
||||||
|
string name = "bar";
|
||||||
|
var line = $" {address} {name}";
|
||||||
|
var e = HostsFileLineParser.ParseLine(line, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.Equal("192.168.1.13", e.Address);
|
Assert.Equal(address, e.Address);
|
||||||
Assert.Single(e.Names);
|
Assert.Single(e.Names);
|
||||||
Assert.Equal("bar", e.Names[0]);
|
Assert.Equal(name, e.Names[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -136,7 +165,8 @@ public class HostsFileLineParserTests
|
|||||||
public void ParseLine_OnlyAddressNoNames_FailsContent_Passthrough()
|
public void ParseLine_OnlyAddressNoNames_FailsContent_Passthrough()
|
||||||
{
|
{
|
||||||
// Content requires address + whitespace + at least one name
|
// Content requires address + whitespace + at least one name
|
||||||
var e = HostsFileLineParser.ParseLine("192.168.1.1", 1);
|
string address = "192.168.1.1";
|
||||||
|
var e = HostsFileLineParser.ParseLine(address, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
Assert.True(e!.IsPassthrough);
|
Assert.True(e!.IsPassthrough);
|
||||||
}
|
}
|
||||||
@@ -144,7 +174,9 @@ public class HostsFileLineParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_Entry_Roundtrips()
|
public void ToLine_Entry_Roundtrips()
|
||||||
{
|
{
|
||||||
var line = "127.0.0.1 localhost";
|
string address = "127.0.0.1";
|
||||||
|
string name = "localhost";
|
||||||
|
var line = $"{address} {name}";
|
||||||
var e = HostsFileLineParser.ParseLine(line, 1);
|
var e = HostsFileLineParser.ParseLine(line, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
var back = HostsFileLineParser.ToLine(e!);
|
var back = HostsFileLineParser.ToLine(e!);
|
||||||
@@ -154,19 +186,23 @@ public class HostsFileLineParserTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_CommentedEntry_PrefixPreserved()
|
public void ToLine_CommentedEntry_PrefixPreserved()
|
||||||
{
|
{
|
||||||
var e = HostsFileLineParser.ParseLine("# 127.0.0.1 localhost", 1);
|
string address = "127.0.0.1";
|
||||||
|
string name = "localhost";
|
||||||
|
var commentLine = $"# {address} {name}";
|
||||||
|
var e = HostsFileLineParser.ParseLine(commentLine, 1);
|
||||||
Assert.NotNull(e);
|
Assert.NotNull(e);
|
||||||
// When we parse "# ..." we get isComment=true, address="", names=[]. ToLine for passthrough returns RawLine.
|
// When we parse "# ..." we get isComment=true, address="", names=[]. ToLine for passthrough returns RawLine.
|
||||||
e = new HostEntry { LineNumber = 1, Address = "127.0.0.1", Names = ["localhost"], IsComment = true };
|
e = new HostEntry { LineNumber = 1, Address = address, Names = [name], IsComment = true };
|
||||||
var back = HostsFileLineParser.ToLine(e);
|
var back = HostsFileLineParser.ToLine(e);
|
||||||
Assert.Equal("# 127.0.0.1 localhost", back);
|
Assert.Equal(commentLine, back);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ToLine_Passthrough_ReturnsRawLine()
|
public void ToLine_Passthrough_ReturnsRawLine()
|
||||||
{
|
{
|
||||||
var e = new HostEntry { LineNumber = 1, RawLine = " \t ", IsPassthrough = true };
|
var raw = " \t ";
|
||||||
Assert.Equal(" \t ", HostsFileLineParser.ToLine(e));
|
var e = new HostEntry { LineNumber = 1, RawLine = raw, IsPassthrough = true };
|
||||||
|
Assert.Equal(raw, HostsFileLineParser.ToLine(e));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
using DnsmasqWebUI.Models.EffectiveConfig;
|
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Client.Http.Abstractions;
|
|
||||||
|
|
||||||
/// <summary>Typed client for GET api/config/set.</summary>
|
|
||||||
public interface IConfigSetClient
|
|
||||||
{
|
|
||||||
Task<DnsmasqConfigSet> GetConfigSetAsync(CancellationToken ct = default);
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
using DnsmasqWebUI.Models.Hosts;
|
|
||||||
using DnsmasqWebUI.Models.Status;
|
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Client.Http.Abstractions;
|
|
||||||
|
|
||||||
/// <summary>Typed client for GET/PUT api/hosts.</summary>
|
|
||||||
public interface IHostsClient
|
|
||||||
{
|
|
||||||
Task<IReadOnlyList<HostEntry>> GetHostsAsync(CancellationToken ct = default);
|
|
||||||
Task<IReadOnlyList<ReadOnlyHostsFile>> GetReadOnlyHostsAsync(CancellationToken ct = default);
|
|
||||||
Task<SaveWithReloadResult> SaveHostsAsync(IReadOnlyList<HostEntry> entries, CancellationToken ct = default);
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
using DnsmasqWebUI.Services.Abstractions;
|
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Client.Http.Abstractions;
|
|
||||||
|
|
||||||
/// <summary>Typed client for POST api/reload.</summary>
|
|
||||||
public interface IReloadClient
|
|
||||||
{
|
|
||||||
Task<ReloadResult> ReloadAsync(CancellationToken ct = default);
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
using DnsmasqWebUI.Models.Status;
|
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Client.Http.Abstractions;
|
|
||||||
|
|
||||||
/// <summary>Typed client for GET api/status.</summary>
|
|
||||||
public interface IStatusClient
|
|
||||||
{
|
|
||||||
Task<DnsmasqServiceStatus> GetStatusAsync(CancellationToken ct = default);
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
using System.Text.Json;
|
|
||||||
using DnsmasqWebUI.Client.Http.Abstractions;
|
|
||||||
using DnsmasqWebUI.Models.Status;
|
|
||||||
using System.Net.Http.Json;
|
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Client.Http;
|
|
||||||
|
|
||||||
public sealed class StatusClient : IStatusClient
|
|
||||||
{
|
|
||||||
private readonly HttpClient _http;
|
|
||||||
|
|
||||||
/// <summary>Matches API serialization (camelCase) so nested EffectiveConfigSources and tuple (value, source) deserialize correctly.</summary>
|
|
||||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
||||||
{
|
|
||||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
||||||
PropertyNameCaseInsensitive = true
|
|
||||||
};
|
|
||||||
|
|
||||||
public StatusClient(HttpClient http) => _http = http;
|
|
||||||
|
|
||||||
public async Task<DnsmasqServiceStatus> GetStatusAsync(CancellationToken ct = default) =>
|
|
||||||
await _http.GetFromJsonAsync<DnsmasqServiceStatus>("api/status", JsonOptions, ct)
|
|
||||||
?? throw new InvalidOperationException("Unexpected null from api/status.");
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
namespace DnsmasqWebUI.Client.Models;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Client-side preferences persisted in browser local storage.
|
|
||||||
/// </summary>
|
|
||||||
public class ClientSettings
|
|
||||||
{
|
|
||||||
/// <summary>Polling interval for the service status block (seconds).</summary>
|
|
||||||
public int ServiceStatusPollingIntervalSeconds { get; set; } = 15;
|
|
||||||
|
|
||||||
/// <summary>Polling interval for the recent logs block (seconds).</summary>
|
|
||||||
public int RecentLogsPollingIntervalSeconds { get; set; } = 5;
|
|
||||||
|
|
||||||
/// <summary>Polling interval for the DHCP leases list (seconds).</summary>
|
|
||||||
public int LeasesPollingIntervalSeconds { get; set; } = 5;
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
namespace DnsmasqWebUI.Client.Models;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Which subset of client settings to show in the settings modal.
|
|
||||||
/// </summary>
|
|
||||||
public enum SettingsModalContext
|
|
||||||
{
|
|
||||||
/// <summary>Show all settings with optional search.</summary>
|
|
||||||
All,
|
|
||||||
|
|
||||||
/// <summary>Show only service status polling interval.</summary>
|
|
||||||
ServicePolling,
|
|
||||||
|
|
||||||
/// <summary>Show only recent logs polling interval.</summary>
|
|
||||||
LogsPolling,
|
|
||||||
|
|
||||||
/// <summary>Show only DHCP leases refresh interval.</summary>
|
|
||||||
LeasesPolling
|
|
||||||
}
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
using System.Text.Json;
|
|
||||||
using DnsmasqWebUI.Client.Models;
|
|
||||||
using DnsmasqWebUI.Client.Services.Abstractions;
|
|
||||||
using Microsoft.JSInterop;
|
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Client.Services;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Loads and saves client-side settings to browser local storage via JS interop.
|
|
||||||
/// Scoped per Blazor circuit; disposes the JS module when the scope is disposed.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class ClientSettingsService : IClientSettingsService, IAsyncDisposable
|
|
||||||
{
|
|
||||||
private readonly IJSRuntime _jsRuntime;
|
|
||||||
private IJSObjectReference? _module;
|
|
||||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
||||||
{
|
|
||||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
||||||
PropertyNameCaseInsensitive = true,
|
|
||||||
WriteIndented = false
|
|
||||||
};
|
|
||||||
|
|
||||||
public ClientSettingsService(IJSRuntime jsRuntime) => _jsRuntime = jsRuntime;
|
|
||||||
|
|
||||||
private async Task<IJSObjectReference> GetModuleAsync()
|
|
||||||
{
|
|
||||||
if (_module != null) return _module;
|
|
||||||
_module = await _jsRuntime.InvokeAsync<IJSObjectReference>(
|
|
||||||
"import", "./js/client-settings-storage.js");
|
|
||||||
return _module;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc />
|
|
||||||
public async Task<ClientSettings> LoadSettingsAsync()
|
|
||||||
{
|
|
||||||
var module = await GetModuleAsync();
|
|
||||||
var json = await module.InvokeAsync<string?>("getItem");
|
|
||||||
if (string.IsNullOrWhiteSpace(json)) return new ClientSettings();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
return JsonSerializer.Deserialize<ClientSettings>(json, JsonOptions) ?? new ClientSettings();
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
return new ClientSettings();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc />
|
|
||||||
public async Task SaveSettingsAsync(ClientSettings settings)
|
|
||||||
{
|
|
||||||
var json = JsonSerializer.Serialize(settings, JsonOptions);
|
|
||||||
var module = await GetModuleAsync();
|
|
||||||
await module.InvokeVoidAsync("setItem", json);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Disposes the JS module reference. Called when the Blazor circuit scope is disposed.
|
|
||||||
/// </summary>
|
|
||||||
public async ValueTask DisposeAsync()
|
|
||||||
{
|
|
||||||
if (_module == null) return;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await _module.DisposeAsync();
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_module = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
@using System.Reflection
|
||||||
@inject IOptions<ApplicationOptions> AppOptions
|
@inject IOptions<ApplicationOptions> AppOptions
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
@@ -6,26 +7,29 @@
|
|||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<base href="/" />
|
<base href="/" />
|
||||||
<link rel="stylesheet" href="lib/bootstrap/dist/css/bootstrap.min.css" />
|
<link rel="stylesheet" href="lib/bootstrap/dist/css/bootstrap.min.css?v=@_cacheBust" />
|
||||||
<link rel="stylesheet" href="lib/bootstrap-icons/bootstrap-icons.min.css" />
|
<link rel="stylesheet" href="lib/bootstrap-icons/bootstrap-icons.min.css?v=@_cacheBust" />
|
||||||
<link rel="stylesheet" href="app.css" />
|
<link rel="stylesheet" href="app.css?v=@_cacheBust" />
|
||||||
<link rel="stylesheet" href="DnsmasqWebUI.styles.css" />
|
<link rel="stylesheet" href="DnsmasqWebUI.styles.css?v=@_cacheBust" />
|
||||||
<link rel="icon" type="image/png" sizes="16x16" href="favicon-16.png" />
|
<link rel="icon" type="image/png" sizes="16x16" href="favicon-16.png?v=@_cacheBust" />
|
||||||
<link rel="icon" type="image/png" sizes="32x32" href="favicon-32.png" />
|
<link rel="icon" type="image/png" sizes="32x32" href="favicon-32.png?v=@_cacheBust" />
|
||||||
<link rel="icon" type="image/png" sizes="48x48" href="favicon-48.png" />
|
<link rel="icon" type="image/png" sizes="48x48" href="favicon-48.png?v=@_cacheBust" />
|
||||||
<link rel="icon" type="image/png" sizes="192x192" href="favicon-192.png" />
|
<link rel="icon" type="image/png" sizes="192x192" href="favicon-192.png?v=@_cacheBust" />
|
||||||
<link rel="icon" type="image/png" sizes="512x512" href="favicon-512.png" />
|
<link rel="icon" type="image/png" sizes="512x512" href="favicon-512.png?v=@_cacheBust" />
|
||||||
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png" />
|
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png?v=@_cacheBust" />
|
||||||
<title>@_appTitle</title>
|
<title>@_appTitle</title>
|
||||||
<HeadOutlet />
|
<HeadOutlet />
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<Routes />
|
<Routes @rendermode="InteractiveServer" />
|
||||||
|
<script src="js/copy-to-clipboard.js"></script>
|
||||||
<script src="_framework/blazor.web.js"></script>
|
<script src="_framework/blazor.web.js"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
</html>
|
</html>
|
||||||
@code {
|
@code {
|
||||||
|
private static readonly string _cacheBust = typeof(App).Assembly
|
||||||
|
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0";
|
||||||
private string? _appTitle => AppOptions?.Value?.EffectiveTitle;
|
private string? _appTitle => AppOptions?.Value?.EffectiveTitle;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.Dnsmasq.AppLogs
|
||||||
|
@inject ILoggingClient LoggingClient
|
||||||
|
@inject IJSRuntime JSRuntime
|
||||||
|
@implements IAsyncDisposable
|
||||||
|
|
||||||
|
@if (IsVisible)
|
||||||
|
{
|
||||||
|
<dialog @ref="_dialogRef" class="settings-modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h5 class="modal-title">App logs filters</h5>
|
||||||
|
<button type="button" class="btn-close" @onclick="Close" aria-label="Close"></button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<p class="text-muted small mb-2">Logger categories matching these prefixes are excluded from the app logs display.</p>
|
||||||
|
<div class="input-group input-group-sm mb-2">
|
||||||
|
<input type="text" class="form-control" placeholder="e.g. Microsoft.AspNetCore."
|
||||||
|
@bind="_newPrefix" @bind:event="oninput" @onkeydown="OnNewPrefixKeydown" />
|
||||||
|
<button type="button" class="btn btn-outline-primary" @onclick="AddPrefix" disabled="@string.IsNullOrWhiteSpace(_newPrefix)"><i class="bi bi-plus me-1" aria-hidden="true"></i>Add</button>
|
||||||
|
</div>
|
||||||
|
<ul class="list-group list-group-flush" style="max-height: 12rem; overflow-y: auto;">
|
||||||
|
@foreach (var prefix in _prefixes)
|
||||||
|
{
|
||||||
|
<li class="list-group-item d-flex align-items-center justify-content-between py-1 px-2">
|
||||||
|
<code class="small text-break">@prefix</code>
|
||||||
|
<button type="button" class="btn btn-link btn-sm p-0 text-danger" aria-label="Remove" @onclick="() => RemovePrefix(prefix)">
|
||||||
|
<i class="bi bi-x-lg" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
@if (_prefixes.Count == 0)
|
||||||
|
{
|
||||||
|
<li class="list-group-item text-muted small py-2">No filters. All categories are shown.</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer d-flex justify-content-between align-items-center">
|
||||||
|
<button type="button" class="btn btn-secondary" @onclick="RestoreDefaults" disabled="@_saving"><i class="bi bi-arrow-counterclockwise me-1" aria-hidden="true"></i>Restore defaults</button>
|
||||||
|
<div>
|
||||||
|
<button type="button" class="btn btn-secondary" @onclick="Close"><i class="bi bi-x me-1" aria-hidden="true"></i>Cancel</button>
|
||||||
|
<button type="button" class="btn btn-primary" @onclick="Save" disabled="@_saving">@if (_saving) { <span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span> } else { <i class="bi bi-floppy-fill me-1" aria-hidden="true"></i> }@(_saving ? "Saving…" : "Save")</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</dialog>
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
using DnsmasqWebUI.Extensions.Interop;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Client.Abstractions;
|
||||||
|
using Microsoft.AspNetCore.Components;
|
||||||
|
using Microsoft.AspNetCore.Components.Web;
|
||||||
|
using Microsoft.JSInterop;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Components.Dnsmasq.AppLogs;
|
||||||
|
|
||||||
|
public partial class AppLogsFiltersModal : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private ElementReference _dialogRef;
|
||||||
|
private IJSObjectReference? _jsModule;
|
||||||
|
private DotNetObjectReference<AppLogsFiltersModal>? _dotNetRef;
|
||||||
|
private List<string> _prefixes = [];
|
||||||
|
private List<string> _originalPrefixes = [];
|
||||||
|
private string _newPrefix = string.Empty;
|
||||||
|
private bool _saving;
|
||||||
|
private bool _moduleLoaded;
|
||||||
|
private bool _dialogInitialized;
|
||||||
|
private bool _wasVisible;
|
||||||
|
private readonly CancellationTokenSource _cts = new();
|
||||||
|
|
||||||
|
[Parameter] public bool IsVisible { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public EventCallback OnClose { get; set; }
|
||||||
|
|
||||||
|
[JSInvokable]
|
||||||
|
public async Task OnDialogClosed(string returnValue)
|
||||||
|
{
|
||||||
|
await OnClose.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task OnParametersSetAsync()
|
||||||
|
{
|
||||||
|
var justOpened = IsVisible && !_wasVisible;
|
||||||
|
_wasVisible = IsVisible;
|
||||||
|
if (justOpened)
|
||||||
|
{
|
||||||
|
_dialogInitialized = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var filters = await LoggingClient.GetFiltersAsync(_cts.Token);
|
||||||
|
_prefixes = filters.ToList();
|
||||||
|
_originalPrefixes = filters.ToList();
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
catch { /* leave current */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||||
|
{
|
||||||
|
if (firstRender)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/dialog.js");
|
||||||
|
_dotNetRef = DotNetObjectReference.Create(this);
|
||||||
|
_moduleLoaded = true;
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException) { }
|
||||||
|
catch (JSDisconnectedException) { }
|
||||||
|
catch (JSException) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsVisible && _moduleLoaded && _jsModule != null)
|
||||||
|
{
|
||||||
|
if (!_dialogInitialized)
|
||||||
|
{
|
||||||
|
await _jsModule.InvokeVoidAsyncSafe("initDialog", _dialogRef, _dotNetRef);
|
||||||
|
_dialogInitialized = true;
|
||||||
|
}
|
||||||
|
await _jsModule.InvokeVoidAsyncSafe("showModal", _dialogRef);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Close()
|
||||||
|
{
|
||||||
|
if (_jsModule != null)
|
||||||
|
await _jsModule.InvokeVoidAsyncSafe("closeModal", _dialogRef);
|
||||||
|
await OnClose.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void AddPrefix()
|
||||||
|
{
|
||||||
|
var p = _newPrefix?.Trim();
|
||||||
|
if (string.IsNullOrEmpty(p) || _prefixes.Contains(p, StringComparer.Ordinal)) return;
|
||||||
|
_prefixes.Add(p);
|
||||||
|
_newPrefix = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RemovePrefix(string prefix)
|
||||||
|
{
|
||||||
|
_prefixes.Remove(prefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnNewPrefixKeydown(KeyboardEventArgs e)
|
||||||
|
{
|
||||||
|
if (e.Key == "Enter")
|
||||||
|
{
|
||||||
|
AddPrefix();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Save()
|
||||||
|
{
|
||||||
|
_saving = true;
|
||||||
|
StateHasChanged();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await LoggingClient.SetFiltersAsync(_prefixes, _cts.Token);
|
||||||
|
_originalPrefixes = [.. _prefixes];
|
||||||
|
await Close();
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
catch { /* leave modal open */ }
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_saving = false;
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RestoreDefaults()
|
||||||
|
{
|
||||||
|
_saving = true;
|
||||||
|
StateHasChanged();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var defaults = await LoggingClient.RestoreFilterDefaultsAsync(_cts.Token);
|
||||||
|
_prefixes = defaults.ToList();
|
||||||
|
_originalPrefixes = [.. _prefixes];
|
||||||
|
await Close();
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
catch { /* leave modal open */ }
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_saving = false;
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
_cts.Cancel();
|
||||||
|
_cts.Dispose();
|
||||||
|
_dotNetRef?.Dispose();
|
||||||
|
await _jsModule.DisposeAsyncSafe();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
/* App logs filters modal – scoped styles; root is the dialog */
|
||||||
|
.settings-modal-dialog {
|
||||||
|
border: none;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
padding: 0;
|
||||||
|
box-shadow: 0 0.5rem 2rem rgba(0, 0, 0, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-modal-dialog::backdrop {
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
max-width: 28rem;
|
||||||
|
margin: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-header {
|
||||||
|
padding: 1rem 1.25rem;
|
||||||
|
border-bottom: 1px solid rgba(0, 0, 0, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-title {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-body {
|
||||||
|
padding: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-footer {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: flex-end;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
padding: 1rem 1.25rem;
|
||||||
|
border-top: 1px solid rgba(0, 0, 0, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-footer .btn {
|
||||||
|
min-width: 4.5rem;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.Dnsmasq.AppLogs
|
||||||
|
@* App logs — live view via SignalR from ILogger *@
|
||||||
|
@using DnsmasqWebUI.Models.Logs
|
||||||
|
@using Microsoft.AspNetCore.SignalR.Client
|
||||||
|
@inject NavigationManager Navigation
|
||||||
|
@inject IJSRuntime JSRuntime
|
||||||
|
@inject ILogger<AppLogsSection> Logger
|
||||||
|
@implements IAsyncDisposable
|
||||||
|
|
||||||
|
<p class="mb-1 mt-3 d-flex align-items-center justify-content-between flex-wrap gap-1">
|
||||||
|
<span class="d-flex align-items-center gap-1 flex-wrap">
|
||||||
|
<strong>App logs</strong>
|
||||||
|
<span class="status-dot d-inline-block rounded-circle flex-shrink-0 bg-success @(_justUpdated ? "status-dot-updating" : null)" style="width: 0.5rem; height: 0.5rem;" title="@(_justUpdated ? "Updating…" : "Live")" aria-hidden="true"></span>
|
||||||
|
</span>
|
||||||
|
<span class="d-flex align-items-center gap-1 flex-wrap">
|
||||||
|
<select class="form-select form-select-sm" style="width: auto;" aria-label="Log level" @bind="_logLevel" @bind:after="OnLogLevelChanged" disabled="@_logLevelDisabled">
|
||||||
|
<option value="Trace">Trace</option>
|
||||||
|
<option value="Debug">Debug</option>
|
||||||
|
<option value="Information">Information</option>
|
||||||
|
<option value="Warning">Warning</option>
|
||||||
|
<option value="Error">Error</option>
|
||||||
|
<option value="Critical">Critical</option>
|
||||||
|
</select>
|
||||||
|
<button type="button" class="btn btn-link btn-sm p-0 text-body" aria-label="App logs category filters" @onclick="OpenFiltersModal" title="Configure category filters">
|
||||||
|
<i class="bi bi-funnel-fill bi-gear-sm" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-link btn-sm p-0 text-body" aria-label="App logs polling settings" @onclick="() => OnOpenSettings.InvokeAsync()" title="Configure app logs polling interval">
|
||||||
|
<i class="bi bi-gear-fill bi-gear-sm" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
<AppLogsFiltersModal IsVisible="_filtersModalVisible" OnClose="CloseFiltersModal" />
|
||||||
|
<LogsPreView Id="app-logs-pre" Placeholder="@_initialPlaceholder" Freeze="_logsContentReceived" />
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
using DnsmasqWebUI.Extensions.Interop;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Client.Abstractions;
|
||||||
|
using DnsmasqWebUI.Models.Logs;
|
||||||
|
using Microsoft.AspNetCore.Components;
|
||||||
|
using Microsoft.AspNetCore.SignalR.Client;
|
||||||
|
using Microsoft.JSInterop;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Components.Dnsmasq.AppLogs;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// App logs block: connects to LogsHub, receives AppLogsUpdate pushes, polls at interval as fallback.
|
||||||
|
/// Snapshot on connect; RequestAppLogsUpdate on poll. Log level is configurable at runtime (persisted to appsettings.Overrides.json).
|
||||||
|
/// </summary>
|
||||||
|
public partial class AppLogsSection : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private const string AppLogsPreId = "app-logs-pre";
|
||||||
|
|
||||||
|
[Inject] private ILoggingClient LoggingClient { get; set; } = null!;
|
||||||
|
|
||||||
|
private bool _justUpdated;
|
||||||
|
private bool _logsContentReceived;
|
||||||
|
private int _intervalSeconds;
|
||||||
|
private string _logLevel = "Information";
|
||||||
|
private bool _logLevelDisabled;
|
||||||
|
private bool _filtersModalVisible;
|
||||||
|
private HubConnection? _hubConnection;
|
||||||
|
private IJSObjectReference? _logsJs;
|
||||||
|
private Timer? _pollTimer;
|
||||||
|
private Timer? _justUpdatedResetTimer;
|
||||||
|
private readonly CancellationTokenSource _cts = new();
|
||||||
|
|
||||||
|
[Parameter] public int RefreshIntervalSeconds { get; set; } = 15;
|
||||||
|
|
||||||
|
[Parameter] public int LogsMaxLines { get; set; } = 500;
|
||||||
|
|
||||||
|
[Parameter] public bool LogsAutoScroll { get; set; } = true;
|
||||||
|
|
||||||
|
[Parameter] public EventCallback OnOpenSettings { get; set; }
|
||||||
|
|
||||||
|
private string _initialPlaceholder => _hubConnection?.State == HubConnectionState.Connected ? "Waiting for logs…" : "Connecting…";
|
||||||
|
|
||||||
|
private object LogsOptions => new { maxLines = LogsMaxLines, autoScroll = LogsAutoScroll };
|
||||||
|
|
||||||
|
protected override void OnParametersSet()
|
||||||
|
{
|
||||||
|
if (RefreshIntervalSeconds == _intervalSeconds) return;
|
||||||
|
_intervalSeconds = RefreshIntervalSeconds;
|
||||||
|
RestartPollTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||||
|
{
|
||||||
|
if (!firstRender) return;
|
||||||
|
_intervalSeconds = RefreshIntervalSeconds;
|
||||||
|
var hubUri = new Uri(new Uri(Navigation.BaseUri), "hubs/logs").ToString();
|
||||||
|
|
||||||
|
_hubConnection = new HubConnectionBuilder()
|
||||||
|
.WithUrl(hubUri)
|
||||||
|
.WithAutomaticReconnect()
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
_hubConnection.On<LogsUpdatePayload>("AppLogsUpdate", OnAppLogsUpdate);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logsJs = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/logs.js");
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex) { Logger.LogDebug(ex, "AppLogsSection: JS import skipped (prerender)"); return; }
|
||||||
|
catch (JSDisconnectedException ex) { Logger.LogDebug(ex, "AppLogsSection: JS import skipped (circuit disconnected)"); return; }
|
||||||
|
catch (JSException ex) { Logger.LogDebug(ex, "AppLogsSection: JS import failed"); return; }
|
||||||
|
|
||||||
|
await _hubConnection.StartAsync(_cts.Token);
|
||||||
|
RestartPollTimer();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logLevel = await LoggingClient.GetLevelAsync(_cts.Token);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
catch (Exception) { /* leave default */ }
|
||||||
|
|
||||||
|
// Request initial snapshot (replace)
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _hubConnection.InvokeAsync("RequestAppLogsSnapshot", _cts.Token);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
catch (Exception) { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OpenFiltersModal() => _filtersModalVisible = true;
|
||||||
|
private void CloseFiltersModal() => _filtersModalVisible = false;
|
||||||
|
|
||||||
|
private async Task OnLogLevelChanged()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(_logLevel)) return;
|
||||||
|
_logLevelDisabled = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var updated = await LoggingClient.SetLevelAsync(_logLevel, _cts.Token);
|
||||||
|
_logLevel = updated;
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
catch (Exception) { /* leave binding as-is */ }
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_logLevelDisabled = false;
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RestartPollTimer()
|
||||||
|
{
|
||||||
|
_pollTimer?.Dispose();
|
||||||
|
_pollTimer = new Timer(
|
||||||
|
_ => _ = InvokeAsync(PollTick),
|
||||||
|
null,
|
||||||
|
TimeSpan.FromSeconds(_intervalSeconds),
|
||||||
|
TimeSpan.FromSeconds(_intervalSeconds));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task PollTick()
|
||||||
|
{
|
||||||
|
if (_cts.Token.IsCancellationRequested || _hubConnection?.State != HubConnectionState.Connected)
|
||||||
|
return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _hubConnection.InvokeAsync("RequestAppLogsUpdate", _cts.Token);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
catch (Exception) { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
private async void OnAppLogsUpdate(LogsUpdatePayload payload)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await InvokeAsync(async () =>
|
||||||
|
{
|
||||||
|
if (_logsJs == null) return;
|
||||||
|
if (payload.Mode == "replace")
|
||||||
|
await _logsJs.InvokeVoidAsyncSafe("replaceLogs", AppLogsPreId, payload.Content, LogsOptions);
|
||||||
|
else
|
||||||
|
await _logsJs.InvokeVoidAsyncSafe("appendLogs", AppLogsPreId, payload.Content, LogsOptions);
|
||||||
|
_logsContentReceived = true;
|
||||||
|
SetJustUpdated();
|
||||||
|
StateHasChanged();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (ObjectDisposedException) { /* Component disposed; ignore */ }
|
||||||
|
catch (InvalidOperationException) { /* Circuit disconnected; ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetJustUpdated()
|
||||||
|
{
|
||||||
|
_justUpdated = true;
|
||||||
|
_justUpdatedResetTimer?.Dispose();
|
||||||
|
_justUpdatedResetTimer = new Timer(_ =>
|
||||||
|
{
|
||||||
|
_justUpdatedResetTimer?.Dispose();
|
||||||
|
_justUpdatedResetTimer = null;
|
||||||
|
_ = InvokeAsync(() =>
|
||||||
|
{
|
||||||
|
_justUpdated = false;
|
||||||
|
StateHasChanged();
|
||||||
|
});
|
||||||
|
}, null, TimeSpan.FromSeconds(2), Timeout.InfiniteTimeSpan);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
_pollTimer?.Dispose();
|
||||||
|
_justUpdatedResetTimer?.Dispose();
|
||||||
|
_cts.Cancel();
|
||||||
|
_cts.Dispose();
|
||||||
|
if (_hubConnection != null)
|
||||||
|
{
|
||||||
|
await _hubConnection.DisposeAsync();
|
||||||
|
_hubConnection = null;
|
||||||
|
}
|
||||||
|
await _logsJs.DisposeAsyncSafe();
|
||||||
|
_logsJs = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
/* Status dot pulse – shared with StatusSection, LogsSection */
|
||||||
|
@keyframes status-dot-pulse {
|
||||||
|
0%, 100% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
opacity: 0.35;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-dot.status-dot-updating {
|
||||||
|
animation: status-dot-pulse 0.7s ease-in-out infinite;
|
||||||
|
}
|
||||||
-24
@@ -1,24 +0,0 @@
|
|||||||
@namespace DnsmasqWebUI.Components.Dnsmasq.EffectiveConfig.CustomDisplays
|
|
||||||
@using DnsmasqWebUI.Models.EffectiveConfig
|
|
||||||
|
|
||||||
@* Reusable value-only display for boolean/flag options. Edit mode: checkbox (unless readonly); View: "Enabled" / "Disabled". *@
|
|
||||||
@if (DisplayMode == EffectiveConfigDisplayMode.Edit && Descriptor.GetSource()?.IsReadOnly != true)
|
|
||||||
{
|
|
||||||
var isSet = Descriptor.GetValue() is bool b && b;
|
|
||||||
<input type="checkbox" class="form-check-input" checked="@isSet" @onchange="OnCheckedChange" />
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
@(Descriptor.GetValue() is bool isSet && isSet ? "Enabled" : "Disabled")
|
|
||||||
}
|
|
||||||
|
|
||||||
@code {
|
|
||||||
[Parameter] public EffectiveConfigFieldDescriptor Descriptor { get; set; } = null!;
|
|
||||||
[CascadingParameter] public EffectiveConfigDisplayMode DisplayMode { get; set; } = EffectiveConfigDisplayMode.View;
|
|
||||||
[Parameter] public EventCallback<bool> CheckedChanged { get; set; }
|
|
||||||
|
|
||||||
private async Task OnCheckedChange(ChangeEventArgs e)
|
|
||||||
{
|
|
||||||
await CheckedChanged.InvokeAsync(e.Value is true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-27
@@ -1,27 +0,0 @@
|
|||||||
@namespace DnsmasqWebUI.Components.Dnsmasq.EffectiveConfig.CustomDisplays
|
|
||||||
@using DnsmasqWebUI.Models.EffectiveConfig
|
|
||||||
|
|
||||||
@* Value-only display for the port option. Edit mode: number input (unless readonly); View: text with "(default DNS port)". *@
|
|
||||||
@if (DisplayMode == EffectiveConfigDisplayMode.Edit && Descriptor.GetSource()?.IsReadOnly != true)
|
|
||||||
{
|
|
||||||
var port = Descriptor.GetValue() is int p ? p : 53;
|
|
||||||
<input type="number" class="form-control form-control-sm" style="max-width: 6rem;" min="1" max="65535" value="@port" @oninput="OnPortInput" />
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
@(Descriptor.GetValue() is int port ? $"{port} (default DNS port)" : "(not set)")
|
|
||||||
}
|
|
||||||
|
|
||||||
@code {
|
|
||||||
[Parameter] public EffectiveConfigFieldDescriptor Descriptor { get; set; } = null!;
|
|
||||||
[CascadingParameter] public EffectiveConfigDisplayMode DisplayMode { get; set; } = EffectiveConfigDisplayMode.View;
|
|
||||||
[Parameter] public EventCallback<int?> PortChanged { get; set; }
|
|
||||||
|
|
||||||
private async Task OnPortInput(ChangeEventArgs e)
|
|
||||||
{
|
|
||||||
if (int.TryParse(e.Value?.ToString(), out var port) && port >= 1 && port <= 65535)
|
|
||||||
await PortChanged.InvokeAsync(port);
|
|
||||||
else
|
|
||||||
await PortChanged.InvokeAsync(null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
@namespace DnsmasqWebUI.Components.Dnsmasq.EffectiveConfig
|
|
||||||
@using DnsmasqWebUI.Models.EffectiveConfig
|
|
||||||
@using DnsmasqWebUI.Models.Config
|
|
||||||
@using DnsmasqWebUI.Services.Abstractions
|
|
||||||
@inject IEffectiveConfigRenderFragmentRegistry RenderFragmentRegistry
|
|
||||||
|
|
||||||
@* Custom fragment renders only the value; we keep the row shell (label + value slot + badge) here for consistency. *@
|
|
||||||
@if (_customFragment is { } fragment)
|
|
||||||
{
|
|
||||||
var labelTooltip = DnsmasqOptionTooltips.Get(Descriptor.OptionName);
|
|
||||||
<li class="ec-field" title="@(Descriptor.GetSource()?.GetReadOnlyTooltip())">
|
|
||||||
<span class="ec-field-label" title="@(labelTooltip ?? Descriptor.GetSource()?.GetReadOnlyTooltip())"><strong>@Descriptor.OptionName:</strong></span>
|
|
||||||
<span class="ec-field-value">@fragment(Descriptor)</span>
|
|
||||||
@if (Descriptor.GetSource()?.IsReadOnly == true)
|
|
||||||
{
|
|
||||||
<span class="badge bg-secondary ms-1">readonly</span>
|
|
||||||
}
|
|
||||||
</li>
|
|
||||||
}
|
|
||||||
else if (Descriptor.IsMultiValue)
|
|
||||||
{
|
|
||||||
var items = Descriptor.GetItems();
|
|
||||||
<EffectiveConfigMultiValueRow Label="@Descriptor.OptionName" Items="@items" LabelTooltip="@_labelTooltip" />
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
var value = Descriptor.GetValue();
|
|
||||||
var displayValue = value == null ? "(not set)" : (value is IReadOnlyList<string> list ? (list.Count == 0 ? "(none)" : string.Join(", ", list)) : value.ToString());
|
|
||||||
<EffectiveConfigOptionItem Label="@Descriptor.OptionName" DisplayValue="@(displayValue ?? "(not set)")" Source="@Descriptor.GetSource()" LabelTooltip="@_labelTooltip" />
|
|
||||||
}
|
|
||||||
|
|
||||||
@code {
|
|
||||||
[Parameter] public EffectiveConfigFieldDescriptor Descriptor { get; set; } = null!;
|
|
||||||
[CascadingParameter] public EffectiveConfigDisplayMode DisplayMode { get; set; } = EffectiveConfigDisplayMode.View;
|
|
||||||
|
|
||||||
private RenderFragment<EffectiveConfigFieldDescriptor>? _customFragment;
|
|
||||||
private string? _labelTooltip;
|
|
||||||
|
|
||||||
protected override void OnParametersSet()
|
|
||||||
{
|
|
||||||
_customFragment = RenderFragmentRegistry.GetDisplayFragment(Descriptor.SectionId, Descriptor.OptionName);
|
|
||||||
_labelTooltip = DnsmasqOptionTooltips.Get(Descriptor.OptionName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-15
@@ -1,15 +0,0 @@
|
|||||||
@namespace DnsmasqWebUI.Components.Dnsmasq.EffectiveConfig
|
|
||||||
@using DnsmasqWebUI.Models.EffectiveConfig
|
|
||||||
|
|
||||||
<span class="ec-field-value-item" title="@(Source?.GetReadOnlyTooltip())">
|
|
||||||
@Value
|
|
||||||
@if (Source?.IsReadOnly == true)
|
|
||||||
{
|
|
||||||
<span class="badge bg-secondary ms-1">readonly</span>
|
|
||||||
}
|
|
||||||
</span>
|
|
||||||
|
|
||||||
@code {
|
|
||||||
[Parameter] public string Value { get; set; } = "";
|
|
||||||
[Parameter] public ConfigValueSource? Source { get; set; }
|
|
||||||
}
|
|
||||||
-56
@@ -1,56 +0,0 @@
|
|||||||
@namespace DnsmasqWebUI.Components.Dnsmasq.EffectiveConfig
|
|
||||||
@using DnsmasqWebUI.Models.EffectiveConfig
|
|
||||||
|
|
||||||
<li class="ec-field">
|
|
||||||
<span class="ec-field-label" title="@LabelTooltip"><strong>@Label:</strong></span>
|
|
||||||
@if (DisplayMode == EffectiveConfigDisplayMode.Edit)
|
|
||||||
{
|
|
||||||
<span class="ec-field-value ec-field-value-multi">
|
|
||||||
<textarea class="form-control form-control-sm" rows="@(Math.Max(2, (Items?.Count ?? 0) + 1))" @oninput="OnLinesInput" placeholder="One value per line">@_editLines</textarea>
|
|
||||||
</span>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<span class="ec-field-value ec-field-value-multi">
|
|
||||||
@if (Items?.Count > 0)
|
|
||||||
{
|
|
||||||
<ol class="ec-field-value-list">
|
|
||||||
@foreach (var item in Items!)
|
|
||||||
{
|
|
||||||
<li><EffectiveConfigMultiValueItem Value="@item.Value" Source="@item.Source" /></li>
|
|
||||||
}
|
|
||||||
</ol>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<span class="text-muted">(none)</span>
|
|
||||||
}
|
|
||||||
</span>
|
|
||||||
}
|
|
||||||
</li>
|
|
||||||
|
|
||||||
@code {
|
|
||||||
[Parameter] public string Label { get; set; } = "";
|
|
||||||
[Parameter] public IReadOnlyList<ValueWithSource>? Items { get; set; }
|
|
||||||
[Parameter] public EventCallback<IReadOnlyList<string>> ItemsChanged { get; set; }
|
|
||||||
[Parameter] public string? LabelTooltip { get; set; }
|
|
||||||
[CascadingParameter] public EffectiveConfigDisplayMode DisplayMode { get; set; } = EffectiveConfigDisplayMode.View;
|
|
||||||
|
|
||||||
private string _editLines = "";
|
|
||||||
|
|
||||||
protected override void OnParametersSet()
|
|
||||||
{
|
|
||||||
if (Items != null && Items.Count > 0)
|
|
||||||
_editLines = string.Join("\n", Items.Select(i => i.Value));
|
|
||||||
else
|
|
||||||
_editLines = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task OnLinesInput(ChangeEventArgs e)
|
|
||||||
{
|
|
||||||
var text = e.Value?.ToString() ?? "";
|
|
||||||
_editLines = text;
|
|
||||||
var lines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()).Where(l => l.Length > 0).ToList();
|
|
||||||
await ItemsChanged.InvokeAsync(lines);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
@namespace DnsmasqWebUI.Components.Dnsmasq.EffectiveConfig
|
|
||||||
@using DnsmasqWebUI.Models.EffectiveConfig
|
|
||||||
|
|
||||||
<li class="ec-field" title="@(Source?.GetReadOnlyTooltip())">
|
|
||||||
<span class="ec-field-label" title="@(LabelTooltip ?? Source?.GetReadOnlyTooltip())"><strong>@Label:</strong></span>
|
|
||||||
@if (DisplayMode == EffectiveConfigDisplayMode.Edit && Source?.IsReadOnly != true)
|
|
||||||
{
|
|
||||||
<span class="ec-field-value">
|
|
||||||
<input type="text" class="form-control form-control-sm" value="@DisplayValue" @oninput="OnValueInput" />
|
|
||||||
</span>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<span class="ec-field-value">@DisplayValue</span>
|
|
||||||
@if (Source?.IsReadOnly == true)
|
|
||||||
{
|
|
||||||
<span class="badge bg-secondary ms-1">readonly</span>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</li>
|
|
||||||
|
|
||||||
@code {
|
|
||||||
[Parameter] public string Label { get; set; } = "";
|
|
||||||
[Parameter] public string DisplayValue { get; set; } = "";
|
|
||||||
[Parameter] public ConfigValueSource? Source { get; set; }
|
|
||||||
/// <summary>Optional explainer shown on hover over the label (e.g. from DnsmasqOptionTooltips).</summary>
|
|
||||||
[Parameter] public string? LabelTooltip { get; set; }
|
|
||||||
/// <summary>When Edit and not readonly: raised when the user changes the value. Not yet wired to save.</summary>
|
|
||||||
[Parameter] public EventCallback<string> DisplayValueChanged { get; set; }
|
|
||||||
[CascadingParameter] public EffectiveConfigDisplayMode DisplayMode { get; set; } = EffectiveConfigDisplayMode.View;
|
|
||||||
|
|
||||||
private async Task OnValueInput(ChangeEventArgs e)
|
|
||||||
{
|
|
||||||
var value = e.Value?.ToString() ?? "";
|
|
||||||
await DisplayValueChanged.InvokeAsync(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
@namespace DnsmasqWebUI.Components.Dnsmasq.EffectiveConfig
|
|
||||||
@using DnsmasqWebUI.Models.Status
|
|
||||||
@using DnsmasqWebUI.Models.EffectiveConfig
|
|
||||||
|
|
||||||
@if (Status != null)
|
|
||||||
{
|
|
||||||
<div class="ec-sections small">
|
|
||||||
@{
|
|
||||||
var descriptors = EffectiveConfigFieldBuilder.BuildFieldDescriptors(Status);
|
|
||||||
var sections = new[]
|
|
||||||
{
|
|
||||||
(EffectiveConfigFieldBuilder.SectionHosts, "Hosts"),
|
|
||||||
(EffectiveConfigFieldBuilder.SectionResolver, "Resolver / DNS"),
|
|
||||||
(EffectiveConfigFieldBuilder.SectionDhcp, "DHCP"),
|
|
||||||
(EffectiveConfigFieldBuilder.SectionCache, "Cache"),
|
|
||||||
(EffectiveConfigFieldBuilder.SectionProcess, "Process & networking")
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@foreach (var (sectionId, title) in sections)
|
|
||||||
{
|
|
||||||
var sectionDescriptors = descriptors.Where(d => d.SectionId == sectionId).ToList();
|
|
||||||
if (sectionDescriptors.Count > 0)
|
|
||||||
{
|
|
||||||
<EffectiveConfigSectionPanel SectionId="@sectionId" Title="@title" Descriptors="@sectionDescriptors" IsOpen="@IsOpen(sectionId)" OnToggle="@OnSectionToggle" DisplayMode="@DisplayMode" />
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
@code {
|
|
||||||
[Parameter] public DnsmasqServiceStatus? Status { get; set; }
|
|
||||||
/// <summary>View = read-only; Edit = editable (future). Cascaded to field displays.</summary>
|
|
||||||
[Parameter] public EffectiveConfigDisplayMode DisplayMode { get; set; } = EffectiveConfigDisplayMode.View;
|
|
||||||
|
|
||||||
private HashSet<string> _openPanels = new();
|
|
||||||
|
|
||||||
private bool IsOpen(string id) => _openPanels.Contains(id);
|
|
||||||
|
|
||||||
private void OnSectionToggle(string id)
|
|
||||||
{
|
|
||||||
if (_openPanels.Contains(id))
|
|
||||||
_openPanels.Remove(id);
|
|
||||||
else
|
|
||||||
_openPanels.Add(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.Dnsmasq.Logs
|
||||||
|
@* Renders a pre element for logs. Once Freeze is true, stops re-rendering so Blazor does not overwrite JS-owned content. *@
|
||||||
|
<pre id="@Id" class="pre-block mb-0" style="max-height: 24rem;">@Placeholder</pre>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public string Id { get; set; } = "";
|
||||||
|
[Parameter] public string Placeholder { get; set; } = "Connecting…";
|
||||||
|
[Parameter] public bool Freeze { get; set; }
|
||||||
|
|
||||||
|
protected override bool ShouldRender() => !Freeze;
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.Dnsmasq.Logs
|
||||||
|
@* Recent logs — live view via SignalR from LogsCommand; client polls at interval, server pushes deltas *@
|
||||||
|
@using DnsmasqWebUI.Models.Logs
|
||||||
|
@using Microsoft.AspNetCore.SignalR.Client
|
||||||
|
@inject NavigationManager Navigation
|
||||||
|
@inject IJSRuntime JSRuntime
|
||||||
|
@inject ILogger<LogsSection> Logger
|
||||||
|
@implements IAsyncDisposable
|
||||||
|
|
||||||
|
@if (_status != null && (_status.LogsConfigured || _status.LogsPath != null))
|
||||||
|
{
|
||||||
|
<p class="mb-1 mt-3 d-flex align-items-center justify-content-between flex-wrap gap-1">
|
||||||
|
<span class="d-flex align-items-center gap-1">
|
||||||
|
<strong>Recent logs</strong>
|
||||||
|
<span class="status-dot d-inline-block rounded-circle flex-shrink-0 bg-success @(_justUpdated ? "status-dot-updating" : null)" style="width: 0.5rem; height: 0.5rem;" title="@(_justUpdated ? "Updating…" : "Live")" aria-hidden="true"></span>
|
||||||
|
</span>
|
||||||
|
<button type="button" class="btn btn-link btn-sm p-0 text-body" aria-label="Recent logs polling settings" @onclick="() => OnOpenSettings.InvokeAsync()" title="Configure recent logs polling interval">
|
||||||
|
<i class="bi bi-gear-fill bi-gear-sm" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
</p>
|
||||||
|
@if (_status.LogsConfigured)
|
||||||
|
{
|
||||||
|
<p class="text-muted small mb-1"><code>@_status.LogsCommand</code></p>
|
||||||
|
}
|
||||||
|
@if (_status.LogsConfigured)
|
||||||
|
{
|
||||||
|
<LogsPreView Id="dnsmasq-logs-pre" Placeholder="@_initialPlaceholder" Freeze="_logsContentReceived" />
|
||||||
|
}
|
||||||
|
<div class="mt-2 d-flex flex-wrap gap-2 align-items-center">
|
||||||
|
<button class="btn btn-primary btn-sm" @onclick="RequestRefreshAsync" disabled="@_refreshing"><i class="bi bi-arrow-repeat me-1" aria-hidden="true"></i>Refresh</button>
|
||||||
|
@if (_status.LogsPath != null)
|
||||||
|
{
|
||||||
|
<a href="api/status/logs/download" download="dnsmasq.log" class="btn btn-primary btn-sm"><i class="bi bi-download me-1" aria-hidden="true"></i>Download logs</a>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<button type="button" class="btn btn-primary btn-sm" disabled title="No log file path detected. Set log-facility=/path/to/file in your dnsmasq config to enable download."><i class="bi bi-download me-1" aria-hidden="true"></i>Download logs</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
using DnsmasqWebUI.Extensions.Interop;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
|
using DnsmasqWebUI.Models.Logs;
|
||||||
|
using Microsoft.AspNetCore.Components;
|
||||||
|
using Microsoft.AspNetCore.SignalR.Client;
|
||||||
|
using Microsoft.JSInterop;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Components.Dnsmasq.Logs;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Recent logs block: connects to LogsHub, polls at interval via RequestDnsmasqLogs,
|
||||||
|
/// receives DnsmasqLogsUpdate pushes, updates DOM via JS interop.
|
||||||
|
/// </summary>
|
||||||
|
public partial class LogsSection : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private const string LogsPreId = "dnsmasq-logs-pre";
|
||||||
|
|
||||||
|
private DnsmasqServiceStatus? _status;
|
||||||
|
private bool _refreshing;
|
||||||
|
private bool _justUpdated;
|
||||||
|
private bool _logsContentReceived;
|
||||||
|
private int _intervalSeconds;
|
||||||
|
private HubConnection? _hubConnection;
|
||||||
|
private IJSObjectReference? _logsJs;
|
||||||
|
private Timer? _pollTimer;
|
||||||
|
private Timer? _justUpdatedResetTimer;
|
||||||
|
private readonly CancellationTokenSource _cts = new();
|
||||||
|
|
||||||
|
[Parameter] public DnsmasqServiceStatus? Status { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public int RefreshIntervalSeconds { get; set; } = 15;
|
||||||
|
|
||||||
|
[Parameter] public int LogsMaxLines { get; set; } = 500;
|
||||||
|
|
||||||
|
[Parameter] public bool LogsAutoScroll { get; set; } = true;
|
||||||
|
|
||||||
|
[Parameter] public EventCallback OnOpenSettings { get; set; }
|
||||||
|
|
||||||
|
private object LogsOptions => new { maxLines = LogsMaxLines, autoScroll = LogsAutoScroll };
|
||||||
|
|
||||||
|
private string _initialPlaceholder => _hubConnection?.State == HubConnectionState.Connected ? "Waiting for logs…" : "Connecting…";
|
||||||
|
|
||||||
|
protected override void OnParametersSet()
|
||||||
|
{
|
||||||
|
_status = Status;
|
||||||
|
if (RefreshIntervalSeconds == _intervalSeconds) return;
|
||||||
|
_intervalSeconds = RefreshIntervalSeconds;
|
||||||
|
RestartPollTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||||
|
{
|
||||||
|
if (!firstRender) return;
|
||||||
|
_intervalSeconds = RefreshIntervalSeconds;
|
||||||
|
_status = Status;
|
||||||
|
|
||||||
|
var hubUri = new Uri(new Uri(Navigation.BaseUri), "hubs/logs").ToString();
|
||||||
|
|
||||||
|
_hubConnection = new HubConnectionBuilder()
|
||||||
|
.WithUrl(hubUri)
|
||||||
|
.WithAutomaticReconnect()
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
_hubConnection.On<LogsUpdatePayload>("DnsmasqLogsUpdate", OnDnsmasqLogsUpdate);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logsJs = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/logs.js");
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex) { Logger.LogDebug(ex, "LogsSection: JS import skipped (prerender)"); return; }
|
||||||
|
catch (JSDisconnectedException ex) { Logger.LogDebug(ex, "LogsSection: JS import skipped (circuit disconnected)"); return; }
|
||||||
|
catch (JSException ex) { Logger.LogDebug(ex, "LogsSection: JS import failed"); return; }
|
||||||
|
|
||||||
|
await _hubConnection.StartAsync(_cts.Token);
|
||||||
|
RestartPollTimer();
|
||||||
|
|
||||||
|
// Initial request
|
||||||
|
await RequestRefreshAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RestartPollTimer()
|
||||||
|
{
|
||||||
|
_pollTimer?.Dispose();
|
||||||
|
_pollTimer = new Timer(
|
||||||
|
_ => _ = InvokeAsync(PollTick),
|
||||||
|
null,
|
||||||
|
TimeSpan.FromSeconds(_intervalSeconds),
|
||||||
|
TimeSpan.FromSeconds(_intervalSeconds));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task PollTick()
|
||||||
|
{
|
||||||
|
if (_cts.Token.IsCancellationRequested || _hubConnection?.State != HubConnectionState.Connected)
|
||||||
|
return;
|
||||||
|
await RequestRefreshAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RequestRefreshAsync()
|
||||||
|
{
|
||||||
|
if (_hubConnection?.State != HubConnectionState.Connected)
|
||||||
|
return;
|
||||||
|
_refreshing = true;
|
||||||
|
StateHasChanged();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _hubConnection.InvokeAsync("RequestDnsmasqLogs", _cts.Token);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
// Don't overwrite on background refresh
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_refreshing = false;
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async void OnDnsmasqLogsUpdate(LogsUpdatePayload payload)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await InvokeAsync(async () =>
|
||||||
|
{
|
||||||
|
if (_logsJs == null) return;
|
||||||
|
if (payload.Mode == "replace")
|
||||||
|
await _logsJs.InvokeVoidAsyncSafe("replaceLogs", LogsPreId, payload.Content, LogsOptions);
|
||||||
|
else
|
||||||
|
await _logsJs.InvokeVoidAsyncSafe("appendLogs", LogsPreId, payload.Content, LogsOptions);
|
||||||
|
_logsContentReceived = true;
|
||||||
|
SetJustUpdated();
|
||||||
|
StateHasChanged();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (ObjectDisposedException) { /* Component disposed; ignore */ }
|
||||||
|
catch (InvalidOperationException) { /* Circuit disconnected; ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetJustUpdated()
|
||||||
|
{
|
||||||
|
_justUpdated = true;
|
||||||
|
_justUpdatedResetTimer?.Dispose();
|
||||||
|
_justUpdatedResetTimer = new Timer(_ =>
|
||||||
|
{
|
||||||
|
_justUpdatedResetTimer?.Dispose();
|
||||||
|
_justUpdatedResetTimer = null;
|
||||||
|
_ = InvokeAsync(() =>
|
||||||
|
{
|
||||||
|
_justUpdated = false;
|
||||||
|
StateHasChanged();
|
||||||
|
});
|
||||||
|
}, null, TimeSpan.FromSeconds(2), Timeout.InfiniteTimeSpan);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
_pollTimer?.Dispose();
|
||||||
|
_justUpdatedResetTimer?.Dispose();
|
||||||
|
_cts.Cancel();
|
||||||
|
_cts.Dispose();
|
||||||
|
if (_hubConnection != null)
|
||||||
|
{
|
||||||
|
await _hubConnection.DisposeAsync();
|
||||||
|
_hubConnection = null;
|
||||||
|
}
|
||||||
|
await _logsJs.DisposeAsyncSafe();
|
||||||
|
_logsJs = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
/* Status dot pulse – shared with StatusSection */
|
||||||
|
@keyframes status-dot-pulse {
|
||||||
|
0%, 100% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
opacity: 0.35;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-dot.status-dot-updating {
|
||||||
|
animation: status-dot-pulse 0.7s ease-in-out infinite;
|
||||||
|
}
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
@namespace DnsmasqWebUI.Components.Dnsmasq
|
|
||||||
@* Recent logs — live view from LogsCommand; only this component re-renders on its timer *@
|
|
||||||
@if (_status != null && (_status.LogsConfigured || _status.LogsPath != null))
|
|
||||||
{
|
|
||||||
<p class="mb-1 mt-3 d-flex align-items-center justify-content-between">
|
|
||||||
<strong>Recent logs</strong>
|
|
||||||
<button type="button" class="btn btn-link btn-sm p-0 text-body" aria-label="Recent logs polling settings" @onclick="() => OnOpenSettings.InvokeAsync()" title="Configure recent logs polling interval">
|
|
||||||
<i class="bi bi-gear-fill bi-gear-sm" aria-hidden="true"></i>
|
|
||||||
</button>
|
|
||||||
</p>
|
|
||||||
@if (_status.LogsConfigured)
|
|
||||||
{
|
|
||||||
<p class="text-muted small mb-1"><code>@_status.LogsCommand</code></p>
|
|
||||||
}
|
|
||||||
@if (_status.LogsConfigured)
|
|
||||||
{
|
|
||||||
@if (string.IsNullOrWhiteSpace(_status.LogsOutput))
|
|
||||||
{
|
|
||||||
<p class="text-muted small">No output.</p>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<pre class="pre-block mb-0" style="max-height: 24rem;">@_status.LogsOutput</pre>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
<div class="mt-2 d-flex flex-wrap gap-2 align-items-center">
|
|
||||||
<button class="btn btn-primary btn-sm" @onclick="RefreshAsync" disabled="@_refreshing">Refresh</button>
|
|
||||||
@if (_status.LogsPath != null)
|
|
||||||
{
|
|
||||||
<a href="api/status/logs/download" download="dnsmasq.log" class="btn btn-primary btn-sm">Download logs</a>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<button type="button" class="btn btn-primary btn-sm" disabled title="No log file path detected. Set log-facility=/path/to/file in your dnsmasq config to enable download.">Download logs</button>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
using DnsmasqWebUI.Client.Http.Abstractions;
|
|
||||||
using DnsmasqWebUI.Models.Status;
|
|
||||||
using Microsoft.AspNetCore.Components;
|
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Components.Dnsmasq;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Recent logs block: polls LogsCommand output at its own interval and re-renders only itself.
|
|
||||||
/// </summary>
|
|
||||||
public partial class LogsSection : IDisposable
|
|
||||||
{
|
|
||||||
private DnsmasqServiceStatus? _status;
|
|
||||||
private bool _refreshing;
|
|
||||||
private int _intervalSeconds;
|
|
||||||
private readonly CancellationTokenSource _cts = new();
|
|
||||||
private Timer? _timer;
|
|
||||||
|
|
||||||
[Parameter] public int RefreshIntervalSeconds { get; set; } = 15;
|
|
||||||
|
|
||||||
[Parameter] public EventCallback OnOpenSettings { get; set; }
|
|
||||||
|
|
||||||
[Inject] private IStatusClient StatusClient { get; set; } = null!;
|
|
||||||
|
|
||||||
protected override async Task OnInitializedAsync()
|
|
||||||
{
|
|
||||||
_intervalSeconds = Math.Clamp(RefreshIntervalSeconds, 5, 300);
|
|
||||||
await RefreshAsync();
|
|
||||||
_timer = new Timer(
|
|
||||||
_ => _ = InvokeAsync(OnRefreshTick),
|
|
||||||
null,
|
|
||||||
TimeSpan.FromSeconds(_intervalSeconds),
|
|
||||||
TimeSpan.FromSeconds(_intervalSeconds));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override void OnParametersSet()
|
|
||||||
{
|
|
||||||
var next = Math.Clamp(RefreshIntervalSeconds, 5, 300);
|
|
||||||
if (next == _intervalSeconds) return;
|
|
||||||
_intervalSeconds = next;
|
|
||||||
_timer?.Dispose();
|
|
||||||
_timer = new Timer(
|
|
||||||
_ => _ = InvokeAsync(OnRefreshTick),
|
|
||||||
null,
|
|
||||||
TimeSpan.FromSeconds(_intervalSeconds),
|
|
||||||
TimeSpan.FromSeconds(_intervalSeconds));
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task OnRefreshTick()
|
|
||||||
{
|
|
||||||
if (_cts.Token.IsCancellationRequested) return;
|
|
||||||
await RefreshAsync();
|
|
||||||
StateHasChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task RefreshAsync()
|
|
||||||
{
|
|
||||||
_refreshing = true;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var token = _cts.Token;
|
|
||||||
_status = await StatusClient.GetStatusAsync(token);
|
|
||||||
}
|
|
||||||
catch (OperationCanceledException) { }
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
// Don't overwrite on background refresh
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_refreshing = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
_timer?.Dispose();
|
|
||||||
_timer = null;
|
|
||||||
_cts.Cancel();
|
|
||||||
_cts.Dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+4
-3
@@ -1,4 +1,4 @@
|
|||||||
@namespace DnsmasqWebUI.Components.Dnsmasq
|
@namespace DnsmasqWebUI.Components.Dnsmasq.Status
|
||||||
@* Service status — output of StatusShowCommand; only this component re-renders on its timer *@
|
@* Service status — output of StatusShowCommand; only this component re-renders on its timer *@
|
||||||
@if (_status != null && _status.StatusShowConfigured)
|
@if (_status != null && _status.StatusShowConfigured)
|
||||||
{
|
{
|
||||||
@@ -7,8 +7,9 @@
|
|||||||
<strong>Service status</strong>
|
<strong>Service status</strong>
|
||||||
@{
|
@{
|
||||||
var isActive = _status.DnsmasqStatus == "active";
|
var isActive = _status.DnsmasqStatus == "active";
|
||||||
|
var isUpdating = _refreshing || IsReloading;
|
||||||
}
|
}
|
||||||
<span class="status-dot d-inline-block rounded-circle flex-shrink-0 @(isActive ? "bg-success" : "bg-danger")" style="width: 0.5rem; height: 0.5rem;" title="@(isActive ? "Running" : "Not running")" aria-hidden="true"></span>
|
<span class="status-dot d-inline-block rounded-circle flex-shrink-0 @(isActive ? "bg-success" : "bg-danger") @(isUpdating ? "status-dot-updating" : null)" style="width: 0.5rem; height: 0.5rem;" title="@(isUpdating ? "Updating…" : (isActive ? "Running" : "Not running"))" aria-hidden="true"></span>
|
||||||
</span>
|
</span>
|
||||||
<button type="button" class="btn btn-link btn-sm p-0 text-body" aria-label="Service status polling settings" @onclick="() => OnOpenSettings.InvokeAsync()" title="Configure service status polling interval">
|
<button type="button" class="btn btn-link btn-sm p-0 text-body" aria-label="Service status polling settings" @onclick="() => OnOpenSettings.InvokeAsync()" title="Configure service status polling interval">
|
||||||
<i class="bi bi-gear-fill bi-gear-sm" aria-hidden="true"></i>
|
<i class="bi bi-gear-fill bi-gear-sm" aria-hidden="true"></i>
|
||||||
@@ -24,6 +25,6 @@
|
|||||||
<pre class="pre-block mb-0" style="max-height: 22rem;">@_status.StatusShowOutput</pre>
|
<pre class="pre-block mb-0" style="max-height: 22rem;">@_status.StatusShowOutput</pre>
|
||||||
}
|
}
|
||||||
<div class="mt-2">
|
<div class="mt-2">
|
||||||
<button class="btn btn-primary btn-sm" @onclick="RefreshAsync" disabled="@_refreshing">Refresh</button>
|
<button class="btn btn-primary btn-sm" @onclick="RefreshAsync" disabled="@_refreshing"><i class="bi bi-arrow-repeat me-1" aria-hidden="true"></i>Refresh</button>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
+19
-7
@@ -1,8 +1,8 @@
|
|||||||
using DnsmasqWebUI.Client.Http.Abstractions;
|
using DnsmasqWebUI.Infrastructure.Client.Abstractions;
|
||||||
using DnsmasqWebUI.Models.Status;
|
using DnsmasqWebUI.Models.Dnsmasq;
|
||||||
using Microsoft.AspNetCore.Components;
|
using Microsoft.AspNetCore.Components;
|
||||||
|
|
||||||
namespace DnsmasqWebUI.Components.Dnsmasq;
|
namespace DnsmasqWebUI.Components.Dnsmasq.Status;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Service status block: polls StatusShowCommand output at its own interval and re-renders only itself.
|
/// Service status block: polls StatusShowCommand output at its own interval and re-renders only itself.
|
||||||
@@ -17,13 +17,15 @@ public partial class StatusSection : IDisposable
|
|||||||
|
|
||||||
[Parameter] public int RefreshIntervalSeconds { get; set; } = 15;
|
[Parameter] public int RefreshIntervalSeconds { get; set; } = 15;
|
||||||
|
|
||||||
|
[Parameter] public bool IsReloading { get; set; }
|
||||||
|
|
||||||
[Parameter] public EventCallback OnOpenSettings { get; set; }
|
[Parameter] public EventCallback OnOpenSettings { get; set; }
|
||||||
|
|
||||||
[Inject] private IStatusClient StatusClient { get; set; } = null!;
|
[Inject] private IStatusClient StatusClient { get; set; } = null!;
|
||||||
|
|
||||||
protected override async Task OnInitializedAsync()
|
protected override async Task OnInitializedAsync()
|
||||||
{
|
{
|
||||||
_intervalSeconds = Math.Clamp(RefreshIntervalSeconds, 5, 300);
|
_intervalSeconds = RefreshIntervalSeconds;
|
||||||
await RefreshAsync();
|
await RefreshAsync();
|
||||||
_timer = new Timer(
|
_timer = new Timer(
|
||||||
_ => _ = InvokeAsync(OnRefreshTick),
|
_ => _ = InvokeAsync(OnRefreshTick),
|
||||||
@@ -34,9 +36,8 @@ public partial class StatusSection : IDisposable
|
|||||||
|
|
||||||
protected override void OnParametersSet()
|
protected override void OnParametersSet()
|
||||||
{
|
{
|
||||||
var next = Math.Clamp(RefreshIntervalSeconds, 5, 300);
|
if (RefreshIntervalSeconds == _intervalSeconds) return;
|
||||||
if (next == _intervalSeconds) return;
|
_intervalSeconds = RefreshIntervalSeconds;
|
||||||
_intervalSeconds = next;
|
|
||||||
_timer?.Dispose();
|
_timer?.Dispose();
|
||||||
_timer = new Timer(
|
_timer = new Timer(
|
||||||
_ => _ = InvokeAsync(OnRefreshTick),
|
_ => _ = InvokeAsync(OnRefreshTick),
|
||||||
@@ -52,9 +53,13 @@ public partial class StatusSection : IDisposable
|
|||||||
StateHasChanged();
|
StateHasChanged();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static readonly TimeSpan MinUpdatingDuration = TimeSpan.FromSeconds(1);
|
||||||
|
|
||||||
private async Task RefreshAsync()
|
private async Task RefreshAsync()
|
||||||
{
|
{
|
||||||
|
var started = DateTime.UtcNow;
|
||||||
_refreshing = true;
|
_refreshing = true;
|
||||||
|
StateHasChanged();
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var token = _cts.Token;
|
var token = _cts.Token;
|
||||||
@@ -67,6 +72,13 @@ public partial class StatusSection : IDisposable
|
|||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
|
var elapsed = DateTime.UtcNow - started;
|
||||||
|
var remaining = MinUpdatingDuration - elapsed;
|
||||||
|
if (remaining > TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
try { await Task.Delay(remaining, _cts.Token).ConfigureAwait(false); }
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
}
|
||||||
_refreshing = false;
|
_refreshing = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
/* Status dot pulse when fetching/updating status */
|
||||||
|
@keyframes status-dot-pulse {
|
||||||
|
0%, 100% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
opacity: 0.35;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-dot.status-dot-updating {
|
||||||
|
animation: status-dot-pulse 0.7s ease-in-out infinite;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@inject IJSRuntime JSRuntime
|
||||||
|
|
||||||
|
<div class="d-flex align-items-center gap-1 @CssClass">
|
||||||
|
<code class="flex-grow-1 text-break @CodeCssClass">@Text</code>
|
||||||
|
<button type="button" class="btn btn-sm btn-outline-secondary py-0" @onclick="CopyAsync" title="@CopyTitle"><i class="bi bi-clipboard me-1" aria-hidden="true"></i>Copy</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public string Text { get; set; } = "";
|
||||||
|
[Parameter] public string? CssClass { get; set; }
|
||||||
|
[Parameter] public string? CodeCssClass { get; set; }
|
||||||
|
[Parameter] public string CopyTitle { get; set; } = "Copy";
|
||||||
|
|
||||||
|
private async Task CopyAsync()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(Text)) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await JSRuntime.InvokeVoidAsync("copyToClipboard", Text);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Clipboard not available or failed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using Microsoft.AspNetCore.Components;
|
||||||
|
using Microsoft.AspNetCore.Components.Web;
|
||||||
|
using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Services.EffectiveConfig.Abstractions;
|
||||||
|
|
||||||
|
namespace DnsmasqWebUI.Components.EffectiveConfig;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Base for effective-config custom value displays. Provides shared parameters,
|
||||||
|
/// <see cref="NotifyValueChanged"/>, and <see cref="GetEffectiveDisplayValue"/> so pending changes are shown before save.
|
||||||
|
/// </summary>
|
||||||
|
public abstract class EffectiveConfigValueDisplayBase : ComponentBase
|
||||||
|
{
|
||||||
|
[Parameter]
|
||||||
|
public EffectiveConfigFieldDescriptor Descriptor { get; set; } = null!;
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public bool IsActiveEditor { get; set; }
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public EventCallback<FocusEventArgs> OnCommitRequested { get; set; }
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public EventCallback<object?> ValueChanged { get; set; }
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public IEffectiveConfigEditSession? Session { get; set; }
|
||||||
|
|
||||||
|
protected Task NotifyValueChanged(object? value) => ValueChanged.InvokeAsync(value);
|
||||||
|
|
||||||
|
/// <summary>Returns the value to display: pending change NewValue if this field has one, else descriptor value (not yet written to disk).</summary>
|
||||||
|
protected object? GetEffectiveDisplayValue()
|
||||||
|
{
|
||||||
|
var pending = Session?.PendingChanges.FirstOrDefault(c =>
|
||||||
|
string.Equals(c.SectionId, Descriptor.SectionId, StringComparison.OrdinalIgnoreCase) &&
|
||||||
|
string.Equals(c.OptionName, Descriptor.OptionName, StringComparison.OrdinalIgnoreCase));
|
||||||
|
return pending != null ? pending.NewValue : Descriptor.GetValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Helpers.Config
|
||||||
|
@inject IEffectiveConfigRenderFragmentRegistry RenderFragmentRegistry
|
||||||
|
|
||||||
|
<div class="ec-sections small">
|
||||||
|
@{
|
||||||
|
var views = EffectiveConfigViews.GetViewsForContext(Context);
|
||||||
|
var descriptorsBySection = EffectiveConfigViews.GetDescriptorsBySection(Status, views, RenderFragmentRegistry);
|
||||||
|
var hasSearch = !string.IsNullOrWhiteSpace(SearchTerm);
|
||||||
|
var term = SearchTerm?.Trim() ?? "";
|
||||||
|
}
|
||||||
|
@foreach (var view in views)
|
||||||
|
{
|
||||||
|
if (!descriptorsBySection.TryGetValue(view.SectionId, out var contextDescriptors))
|
||||||
|
continue;
|
||||||
|
var sectionDescriptors = hasSearch
|
||||||
|
? contextDescriptors.Where(d => DescriptorMatchesSearch(d, term)).ToList()
|
||||||
|
: contextDescriptors.ToList();
|
||||||
|
if (sectionDescriptors.Count == 0)
|
||||||
|
continue;
|
||||||
|
var isOpen = hasSearch || IsSectionOpen(view.SectionId);
|
||||||
|
<EffectiveConfigSectionPanel SectionId="@view.SectionId" Title="@view.Title" Descriptors="@sectionDescriptors" IsOpen="@isOpen" OnToggle="@OnSectionToggle"
|
||||||
|
DisplayMode="@( IsEditMode ? EffectiveConfigDisplayMode.Edit : EffectiveConfigDisplayMode.View )"
|
||||||
|
IsEditMode="@IsEditMode" ActiveFieldKey="@ActiveFieldKey" />
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public DnsmasqServiceStatus? Status { get; set; }
|
||||||
|
[Parameter] public EffectiveConfigContext Context { get; set; } = EffectiveConfigContext.All;
|
||||||
|
[Parameter] public string SearchTerm { get; set; } = "";
|
||||||
|
[Parameter] public HashSet<string> OpenSectionIds { get; set; } = new();
|
||||||
|
[Parameter] public EventCallback<string> OnSectionToggle { get; set; }
|
||||||
|
[Parameter] public bool IsEditMode { get; set; }
|
||||||
|
[Parameter] public string? ActiveFieldKey { get; set; }
|
||||||
|
|
||||||
|
private bool IsSectionOpen(string id) => OpenSectionIds.Contains(id);
|
||||||
|
|
||||||
|
private static bool DescriptorMatchesSearch(EffectiveConfigFieldDescriptor d, string term)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(term)) return true;
|
||||||
|
var searchable = (d.OptionName + " " + (DnsmasqOptionTooltips.Get(d.OptionName) ?? "")).Trim();
|
||||||
|
return searchable.Contains(term, StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Helpers.Config
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Services.EffectiveConfig.Abstractions
|
||||||
|
@inject IEffectiveConfigEditSession Session
|
||||||
|
@inject IJSRuntime JSRuntime
|
||||||
|
|
||||||
|
@if (Status != null)
|
||||||
|
{
|
||||||
|
<div class="ec-container" @onclick="DeactivateActiveFieldIfClicked">
|
||||||
|
<OptionHelpController @ref="_optionHelpControllerRef" Visible="@_showOptionHelp" HelpKey="@_optionHelpKey" AnchorId="@_optionHelpAnchorId" Title="@_optionHelpTitle" OnCloseRequested="CloseOptionHelp" />
|
||||||
|
<ReadonlyPopoverController @ref="_readonlyPopoverControllerRef" Visible="@_showReadonlyPopover" AnchorId="@_readonlyPopoverAnchorId" Source="@_readonlyPopoverSource" OptionName="@(_readonlyPopoverOptionName ?? "")" Value="@_readonlyPopoverValue" ManagedFilePath="@(Status?.ManagedFilePath)" OnCloseRequested="CloseReadonlyPopover" />
|
||||||
|
@{
|
||||||
|
var _sectionViews = EffectiveConfigViews.GetViewsForContext(Context);
|
||||||
|
var _allSectionsExpanded = _sectionViews.Count > 0 && _sectionViews.All(v => _openPanels.Contains(v.SectionId));
|
||||||
|
}
|
||||||
|
<EffectiveConfigToolbar ShowSearchBox="@ShowSearchBox" SearchTerm="@_searchTerm" SearchTermChanged="@OnSearchTermChanged"
|
||||||
|
IsEditMode="@Session.IsEditMode" PendingChangesCount="@Session.PendingChanges.Count"
|
||||||
|
AllSectionsExpanded="@_allSectionsExpanded"
|
||||||
|
OnExpandAll="ExpandAll" OnCollapseAll="CollapseAll" OnEnterEditMode="EnterEditMode" OnExitEditModeWithConfirm="ExitEditModeWithConfirmAsync" OnOpenSaveModal="OpenSaveModal" />
|
||||||
|
<CascadingValue Value="@Session">
|
||||||
|
<CascadingValue Value="@_uiContext">
|
||||||
|
<EffectiveConfigPanels Status="@Status" Context="@Context" SearchTerm="@_searchTerm" OpenSectionIds="@_openPanels"
|
||||||
|
OnSectionToggle="OnSectionToggle" IsEditMode="@Session.IsEditMode" ActiveFieldKey="@Session.ActiveFieldKey" />
|
||||||
|
</CascadingValue>
|
||||||
|
</CascadingValue>
|
||||||
|
<EffectiveConfigSaveFlow ShowModal="@_showSaveModal" PendingChanges="@Session.PendingChanges" Status="@Status" Session="@Session"
|
||||||
|
OnClose="CloseSaveModal" OnSaveCompleted="OnSaveCompleted" OnCloseAndEndEdit="CloseSaveModalAndEndEdit" />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public DnsmasqServiceStatus? Status { get; set; }
|
||||||
|
[Parameter] public EffectiveConfigContext Context { get; set; } = EffectiveConfigContext.All;
|
||||||
|
[Parameter] public bool ShowSearchBox { get; set; } = true;
|
||||||
|
[Parameter] public EventCallback OnSaveCompleted { get; set; }
|
||||||
|
|
||||||
|
private string _searchTerm = "";
|
||||||
|
private HashSet<string> _openPanels = new();
|
||||||
|
private bool _showSaveModal;
|
||||||
|
|
||||||
|
private string? _optionHelpKey;
|
||||||
|
private string? _optionHelpAnchorId;
|
||||||
|
private string _optionHelpTitle = "Option help";
|
||||||
|
private bool _showOptionHelp;
|
||||||
|
private OptionHelpController? _optionHelpControllerRef;
|
||||||
|
|
||||||
|
private bool _showReadonlyPopover;
|
||||||
|
private ReadonlyPopoverController? _readonlyPopoverControllerRef;
|
||||||
|
private string? _readonlyPopoverAnchorId;
|
||||||
|
private ConfigValueSource? _readonlyPopoverSource;
|
||||||
|
private string? _readonlyPopoverOptionName;
|
||||||
|
private object? _readonlyPopoverValue;
|
||||||
|
|
||||||
|
private EffectiveConfigUiContext? _uiContext;
|
||||||
|
|
||||||
|
protected override void OnInitialized()
|
||||||
|
{
|
||||||
|
_uiContext = new EffectiveConfigUiContext
|
||||||
|
{
|
||||||
|
RequestOptionHelpAsync = HandleOptionHelpRequested,
|
||||||
|
RequestReadonlyPopoverAsync = HandleReadonlyBadgeClicked,
|
||||||
|
ScheduleReadonlyPopoverCloseAsync = () =>
|
||||||
|
{
|
||||||
|
_readonlyPopoverControllerRef?.ScheduleCloseFromBadgeLeave();
|
||||||
|
return Task.CompletedTask;
|
||||||
|
},
|
||||||
|
ActivateFieldAsync = fieldKey => { ActivateField(fieldKey); return Task.CompletedTask; },
|
||||||
|
DeactivateFieldAsync = () => { Session.DeactivateField(); return InvokeAsync(StateHasChanged); },
|
||||||
|
CommitFieldAsync = args => { HandleFieldEditCommitted(args); return Task.CompletedTask; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnSearchTermChanged(string value)
|
||||||
|
{
|
||||||
|
_searchTerm = value ?? "";
|
||||||
|
await InvokeAsync(StateHasChanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CloseOptionHelp()
|
||||||
|
{
|
||||||
|
_showOptionHelp = false;
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleOptionHelpRequested(ConfigOptionHelpRequestEventArgs args)
|
||||||
|
{
|
||||||
|
if (args.IsLabelMouseLeave)
|
||||||
|
{
|
||||||
|
if (args.AnchorId == _optionHelpAnchorId)
|
||||||
|
_optionHelpControllerRef?.ScheduleCloseFromLabelLeave();
|
||||||
|
await InvokeAsync(StateHasChanged);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_optionHelpControllerRef?.CancelCloseFromLabelEnter();
|
||||||
|
_optionHelpKey = args.HelpKey;
|
||||||
|
_optionHelpTitle = args.OptionLabel;
|
||||||
|
_optionHelpAnchorId = args.AnchorId;
|
||||||
|
_showOptionHelp = true;
|
||||||
|
await InvokeAsync(StateHasChanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CloseReadonlyPopover()
|
||||||
|
{
|
||||||
|
_showReadonlyPopover = false;
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleReadonlyBadgeClicked(ReadonlyBadgeClickedEventArgs args)
|
||||||
|
{
|
||||||
|
_readonlyPopoverControllerRef?.CancelCloseFromBadgeEnter();
|
||||||
|
_readonlyPopoverAnchorId = args.AnchorId;
|
||||||
|
_readonlyPopoverSource = args.Source;
|
||||||
|
_readonlyPopoverOptionName = args.OptionName;
|
||||||
|
_readonlyPopoverValue = args.Value;
|
||||||
|
_showReadonlyPopover = true;
|
||||||
|
await InvokeAsync(StateHasChanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnSectionToggle(string id)
|
||||||
|
{
|
||||||
|
if (_openPanels.Contains(id))
|
||||||
|
_openPanels.Remove(id);
|
||||||
|
else
|
||||||
|
_openPanels.Add(id);
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ExpandAll()
|
||||||
|
{
|
||||||
|
foreach (var view in EffectiveConfigViews.GetViewsForContext(Context))
|
||||||
|
_openPanels.Add(view.SectionId);
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CollapseAll()
|
||||||
|
{
|
||||||
|
_openPanels.Clear();
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnterEditMode()
|
||||||
|
{
|
||||||
|
Session.EnterEditMode();
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ExitEditModeWithConfirmAsync()
|
||||||
|
{
|
||||||
|
if (Session.PendingChanges.Count > 0)
|
||||||
|
{
|
||||||
|
var module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/dialog.js");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var confirmed = await module.InvokeAsync<bool>("confirmMessage", "Discard unsaved changes and exit edit mode?");
|
||||||
|
if (!confirmed) return;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await module.DisposeAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Session.ExitEditModeDiscard();
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DeactivateActiveFieldIfClicked()
|
||||||
|
{
|
||||||
|
if (Session.IsEditMode && Session.ActiveFieldKey != null)
|
||||||
|
{
|
||||||
|
Session.DeactivateField();
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ActivateField(string fieldKey)
|
||||||
|
{
|
||||||
|
Session.ActivateField(fieldKey);
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void HandleFieldEditCommitted(EffectiveConfigEditCommittedArgs args)
|
||||||
|
{
|
||||||
|
Session.TrackCommit(args);
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OpenSaveModal()
|
||||||
|
{
|
||||||
|
if (Session.PendingChanges.Count == 0) return;
|
||||||
|
_showSaveModal = true;
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CloseSaveModal()
|
||||||
|
{
|
||||||
|
_showSaveModal = false;
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CloseSaveModalAndEndEdit()
|
||||||
|
{
|
||||||
|
_showSaveModal = false;
|
||||||
|
Session.ExitEditModeDiscard();
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
+97
-7
@@ -1,9 +1,48 @@
|
|||||||
/* Effective config sections – mobile-first, touch-friendly.
|
/* Effective config sections – mobile-first, touch-friendly.
|
||||||
Use ::deep so styles apply to EffectiveConfigSectionPanel (child component) markup. */
|
Use ::deep so styles apply to EffectiveConfigSectionPanel (child component) markup. */
|
||||||
|
|
||||||
|
/* Wrapper: border and grouping around all sections. Margin-top separates from config files list above. */
|
||||||
|
.ec-container {
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
border: 1px solid var(--bs-border-color, #dee2e6);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
padding: 1rem;
|
||||||
|
background-color: var(--bs-secondary-bg, #f8f9fa);
|
||||||
|
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
||||||
|
min-width: 0;
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Toolbar: single row, search left and actions right. Use ::deep so styles apply to EffectiveConfigToolbar (child) markup. */
|
||||||
|
::deep .ec-toolbar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
::deep .ec-toolbar-search {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 24rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
::deep .ec-toolbar-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
.ec-sections {
|
.ec-sections {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 0;
|
gap: 0;
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
::deep .ec-section {
|
::deep .ec-section {
|
||||||
@@ -14,7 +53,7 @@
|
|||||||
border-bottom: none;
|
border-bottom: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Touch-friendly header: min 44px tap target (WCAG 2.5.5), breathing room from edges */
|
/* Section header: clear separation from background, touch-friendly (min 44px), distinct so search jumps are obvious */
|
||||||
::deep .ec-section-header {
|
::deep .ec-section-header {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -24,20 +63,22 @@
|
|||||||
padding: 0.625rem 1rem;
|
padding: 0.625rem 1rem;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
border: none;
|
border: none;
|
||||||
|
border-left: 3px solid var(--bs-border-color, #dee2e6);
|
||||||
border-radius: 0.25rem;
|
border-radius: 0.25rem;
|
||||||
background: transparent;
|
background-color: var(--bs-body-bg, #fff);
|
||||||
color: inherit;
|
color: inherit;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
font-size: inherit;
|
font-size: inherit;
|
||||||
line-height: 1.3;
|
line-height: 1.3;
|
||||||
-webkit-tap-highlight-color: transparent;
|
-webkit-tap-highlight-color: transparent;
|
||||||
transition: background-color 0.15s ease, color 0.15s ease;
|
transition: background-color 0.15s ease, color 0.15s ease, border-color 0.15s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
::deep .ec-section-header:hover {
|
::deep .ec-section-header:hover {
|
||||||
color: var(--bs-primary, #0d6efd);
|
color: var(--bs-primary, #0d6efd);
|
||||||
background-color: var(--bs-secondary-bg, rgba(0, 0, 0, 0.04));
|
background-color: var(--bs-secondary-bg, rgba(0, 0, 0, 0.04));
|
||||||
|
border-left-color: var(--bs-primary, #0d6efd);
|
||||||
}
|
}
|
||||||
|
|
||||||
::deep .ec-section-header:focus-visible {
|
::deep .ec-section-header:focus-visible {
|
||||||
@@ -45,15 +86,17 @@
|
|||||||
outline-offset: 2px;
|
outline-offset: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Open state: header reads as "active" and clearly separates from body */
|
/* Open state: header reads as "active", left border accent */
|
||||||
::deep .ec-section-open .ec-section-header {
|
::deep .ec-section-open .ec-section-header {
|
||||||
background-color: var(--bs-secondary-bg, rgba(0, 0, 0, 0.05));
|
background-color: var(--bs-body-bg, #fff);
|
||||||
color: var(--bs-emphasis-color, inherit);
|
color: var(--bs-emphasis-color, inherit);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
border-left-color: var(--bs-primary, #0d6efd);
|
||||||
|
box-shadow: 0 1px 0 var(--bs-border-color, #dee2e6);
|
||||||
}
|
}
|
||||||
|
|
||||||
::deep .ec-section-open .ec-section-header:hover {
|
::deep .ec-section-open .ec-section-header:hover {
|
||||||
background-color: var(--bs-tertiary-bg, rgba(0, 0, 0, 0.08));
|
background-color: var(--bs-secondary-bg, rgba(0, 0, 0, 0.04));
|
||||||
color: var(--bs-primary, #0d6efd);
|
color: var(--bs-primary, #0d6efd);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,6 +122,8 @@
|
|||||||
padding-left: 1rem;
|
padding-left: 1rem;
|
||||||
border-left: 2px solid var(--bs-border-color-translucent, rgba(0, 0, 0, 0.075));
|
border-left: 2px solid var(--bs-border-color-translucent, rgba(0, 0, 0, 0.075));
|
||||||
margin-left: 0;
|
margin-left: 0;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: visible;
|
||||||
overflow-wrap: break-word;
|
overflow-wrap: break-word;
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
}
|
}
|
||||||
@@ -112,28 +157,62 @@
|
|||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Clickable label: open full option help on click (hover tooltip unchanged) */
|
||||||
|
::deep .ec-field-label-help {
|
||||||
|
cursor: pointer;
|
||||||
|
text-decoration: underline;
|
||||||
|
text-decoration-style: dotted;
|
||||||
|
text-underline-offset: 2px;
|
||||||
|
}
|
||||||
|
::deep .ec-field-label-help:hover {
|
||||||
|
color: var(--bs-primary, #0d6efd);
|
||||||
|
}
|
||||||
|
|
||||||
::deep .ec-field-value {
|
::deep .ec-field-value {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
flex: 1 1 auto;
|
flex: 1 1 auto;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
overflow-wrap: break-word;
|
overflow-wrap: break-word;
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
|
gap: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Multi-value: full width below label, indented ordered list */
|
/* Edit wrapper (checkbox/input) shrinks to content so the editable badge stays on the same line */
|
||||||
|
::deep .ec-field-edit-wrapper {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Input/select in value area can shrink so the editable badge stays on the same line */
|
||||||
|
::deep .ec-field-value > .form-control,
|
||||||
|
::deep .ec-field-value > .form-select {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Multi-value: full width below label, indented ordered list. min-width: 0 so flex doesn't prevent wrapping. */
|
||||||
::deep .ec-field-value-multi {
|
::deep .ec-field-value-multi {
|
||||||
flex-basis: 100%;
|
flex-basis: 100%;
|
||||||
|
min-width: 0;
|
||||||
padding-left: 1.25rem;
|
padding-left: 1.25rem;
|
||||||
margin-top: 0.15rem;
|
margin-top: 0.15rem;
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
word-break: break-word;
|
||||||
}
|
}
|
||||||
|
|
||||||
::deep .ec-field-value-list {
|
::deep .ec-field-value-list {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding-left: 1.25rem;
|
padding-left: 1.25rem;
|
||||||
list-style-type: decimal;
|
list-style-type: decimal;
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
::deep .ec-field-value-list li {
|
::deep .ec-field-value-list li {
|
||||||
margin-bottom: 0.2rem;
|
margin-bottom: 0.2rem;
|
||||||
|
min-width: 0;
|
||||||
overflow-wrap: break-word;
|
overflow-wrap: break-word;
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
}
|
}
|
||||||
@@ -142,14 +221,25 @@
|
|||||||
margin-bottom: 0;
|
margin-bottom: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Long paths/URLs wrap; allow break anywhere so nothing is clipped */
|
||||||
::deep .ec-field-value-item {
|
::deep .ec-field-value-item {
|
||||||
display: inline;
|
display: inline;
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
word-break: break-word;
|
||||||
}
|
}
|
||||||
|
|
||||||
::deep .ec-field-value-sep {
|
::deep .ec-field-value-sep {
|
||||||
margin-right: 0.25rem;
|
margin-right: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* StatusBadge inside field rows: alignment; spacing comes from StatusBadge .status-badge-inline */
|
||||||
|
::deep .ec-field .status-badge,
|
||||||
|
::deep .ec-field-value-item .status-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 767.98px) {
|
@media (max-width: 767.98px) {
|
||||||
::deep .ec-section-header {
|
::deep .ec-section-header {
|
||||||
padding-left: 0.75rem;
|
padding-left: 0.75rem;
|
||||||
+9
-4
@@ -1,5 +1,6 @@
|
|||||||
@namespace DnsmasqWebUI.Components.Dnsmasq.EffectiveConfig
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
@using DnsmasqWebUI.Models.EffectiveConfig
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
|
||||||
<CascadingValue Value="DisplayMode">
|
<CascadingValue Value="DisplayMode">
|
||||||
<div class="ec-section @(IsOpen ? "ec-section-open" : "")">
|
<div class="ec-section @(IsOpen ? "ec-section-open" : "")">
|
||||||
@@ -12,7 +13,9 @@
|
|||||||
<ul class="list-unstyled mb-0">
|
<ul class="list-unstyled mb-0">
|
||||||
@foreach (var f in Descriptors)
|
@foreach (var f in Descriptors)
|
||||||
{
|
{
|
||||||
<EffectiveConfigFieldDisplay Descriptor="@f" />
|
var fieldKey = $"{SectionId}:{f.OptionName}";
|
||||||
|
<EffectiveConfigFieldDisplay Descriptor="@f" FieldKey="@fieldKey"
|
||||||
|
IsEditMode="@IsEditMode" IsActive="@(ActiveFieldKey == fieldKey)" />
|
||||||
}
|
}
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
@@ -26,8 +29,10 @@
|
|||||||
[Parameter] public IReadOnlyList<EffectiveConfigFieldDescriptor> Descriptors { get; set; } = null!;
|
[Parameter] public IReadOnlyList<EffectiveConfigFieldDescriptor> Descriptors { get; set; } = null!;
|
||||||
[Parameter] public bool IsOpen { get; set; }
|
[Parameter] public bool IsOpen { get; set; }
|
||||||
[Parameter] public EventCallback<string> OnToggle { get; set; }
|
[Parameter] public EventCallback<string> OnToggle { get; set; }
|
||||||
/// <summary>Cascaded from EffectiveConfigSection. View = read-only; Edit = editable (future).</summary>
|
/// <summary>Cascaded from EffectiveConfigSection. View = read-only; Edit = editable.</summary>
|
||||||
[Parameter] public EffectiveConfigDisplayMode DisplayMode { get; set; } = EffectiveConfigDisplayMode.View;
|
[Parameter] public EffectiveConfigDisplayMode DisplayMode { get; set; } = EffectiveConfigDisplayMode.View;
|
||||||
|
[Parameter] public bool IsEditMode { get; set; }
|
||||||
|
[Parameter] public string? ActiveFieldKey { get; set; }
|
||||||
|
|
||||||
private async Task ToggleSection() => await OnToggle.InvokeAsync(SectionId);
|
private async Task ToggleSection() => await OnToggle.InvokeAsync(SectionId);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
|
||||||
|
<div class="ec-toolbar @(IsEditMode ? "ec-edit-toolbar" : "")">
|
||||||
|
@if (ShowSearchBox)
|
||||||
|
{
|
||||||
|
<input type="search" id="ec-search-input" class="form-control form-control-sm ec-toolbar-search" placeholder="Search..." autocomplete="off"
|
||||||
|
value="@SearchTerm" @oninput="OnSearchInput" />
|
||||||
|
}
|
||||||
|
<div class="ec-toolbar-actions">
|
||||||
|
<button type="button" class="btn btn-sm btn-outline-secondary" @onclick="OnToggleExpandCollapse"
|
||||||
|
title="@(AllSectionsExpanded ? "Collapse all sections" : "Expand all sections")"
|
||||||
|
aria-label="@(AllSectionsExpanded ? "Collapse all sections" : "Expand all sections")">
|
||||||
|
<i class="bi @(AllSectionsExpanded ? "bi-arrows-collapse" : "bi-arrows-expand")" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
@if (IsEditMode)
|
||||||
|
{
|
||||||
|
<button type="button" class="btn btn-sm btn-primary" @onclick="OnOpenSaveModal" disabled="@(PendingChangesCount == 0)" title="Save changes to managed config" aria-label="Save">
|
||||||
|
<i class="bi bi-floppy-fill" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-sm btn-outline-secondary" @onclick="OnExitEditModeWithConfirm" title="Exit edit mode" aria-label="Exit edit mode">
|
||||||
|
<i class="bi bi-box-arrow-right" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
@if (PendingChangesCount > 0)
|
||||||
|
{
|
||||||
|
<span class="text-muted small">@PendingChangesCount change(s)</span>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<button type="button" class="btn btn-sm btn-outline-secondary" @onclick="OnEnterEditMode" title="Edit effective config" aria-label="Edit">
|
||||||
|
<i class="bi bi-pencil" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public bool ShowSearchBox { get; set; } = true;
|
||||||
|
[Parameter] public string SearchTerm { get; set; } = "";
|
||||||
|
[Parameter] public EventCallback<string> SearchTermChanged { get; set; }
|
||||||
|
[Parameter] public bool IsEditMode { get; set; }
|
||||||
|
[Parameter] public int PendingChangesCount { get; set; }
|
||||||
|
[Parameter] public bool AllSectionsExpanded { get; set; }
|
||||||
|
[Parameter] public EventCallback OnExpandAll { get; set; }
|
||||||
|
[Parameter] public EventCallback OnCollapseAll { get; set; }
|
||||||
|
|
||||||
|
private async Task OnToggleExpandCollapse()
|
||||||
|
{
|
||||||
|
if (AllSectionsExpanded)
|
||||||
|
await OnCollapseAll.InvokeAsync();
|
||||||
|
else
|
||||||
|
await OnExpandAll.InvokeAsync();
|
||||||
|
}
|
||||||
|
[Parameter] public EventCallback OnEnterEditMode { get; set; }
|
||||||
|
[Parameter] public EventCallback OnExitEditModeWithConfirm { get; set; }
|
||||||
|
[Parameter] public EventCallback OnOpenSaveModal { get; set; }
|
||||||
|
|
||||||
|
private async Task OnSearchInput(ChangeEventArgs e)
|
||||||
|
{
|
||||||
|
await SearchTermChanged.InvokeAsync(e.Value?.ToString() ?? "");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig.CustomDisplays
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@inherits EffectiveConfigValueDisplayBase
|
||||||
|
|
||||||
|
@* Reusable value-only display for boolean/flag options. When active editor: checkbox (unless readonly); View: "Enabled" / "Disabled". Pending value shown until save. *@
|
||||||
|
@if (IsActiveEditor && Descriptor.GetSource()?.IsReadOnly != true)
|
||||||
|
{
|
||||||
|
var isSet = GetEffectiveDisplayValue() is bool b && b;
|
||||||
|
<input type="checkbox" class="form-check-input" checked="@isSet" @onchange="OnCheckedChange" @onfocusout="OnCommitRequested" />
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
@(GetEffectiveDisplayValue() is bool isSet && isSet ? "Enabled" : "Disabled")
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private async Task OnCheckedChange(ChangeEventArgs e)
|
||||||
|
{
|
||||||
|
await NotifyValueChanged(e.Value is true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig.CustomDisplays
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@inherits EffectiveConfigValueDisplayBase
|
||||||
|
|
||||||
|
@* Value-only display for int? options. Pending value shown until save. *@
|
||||||
|
@if (IsActiveEditor && Descriptor.GetSource()?.IsReadOnly != true)
|
||||||
|
{
|
||||||
|
var current = GetEffectiveDisplayValue() is int i ? i : DefaultValue;
|
||||||
|
<input type="number" class="form-control form-control-sm" style="max-width: 8rem;"
|
||||||
|
min="@Min" max="@Max" value="@(current?.ToString() ?? "")" @oninput="OnInput" @onfocusout="OnCommitRequested" />
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var v = GetEffectiveDisplayValue() is int n ? n : (int?)null;
|
||||||
|
if (v is null)
|
||||||
|
{
|
||||||
|
@("(not set)")
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
@v
|
||||||
|
@if (!string.IsNullOrEmpty(ViewSuffix)) { <text> @ViewSuffix</text> }
|
||||||
|
@if (!string.IsNullOrEmpty(Unit)) { <text> @Unit</text> }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private EffectiveIntegerConfigFieldDescriptor? IntDescriptor => Descriptor as EffectiveIntegerConfigFieldDescriptor;
|
||||||
|
private string? ViewSuffix => IntDescriptor?.ViewSuffix;
|
||||||
|
private string? Unit => IntDescriptor?.Unit;
|
||||||
|
private int Min => IntDescriptor?.Min ?? 0;
|
||||||
|
private int Max => IntDescriptor?.Max ?? int.MaxValue;
|
||||||
|
private int? DefaultValue => IntDescriptor?.DefaultValue;
|
||||||
|
|
||||||
|
private async Task OnInput(ChangeEventArgs e)
|
||||||
|
{
|
||||||
|
int? value = null;
|
||||||
|
if (int.TryParse(e.Value?.ToString(), out var num) && num >= Min && num <= Max)
|
||||||
|
value = num;
|
||||||
|
await NotifyValueChanged(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig.CustomDisplays
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@inherits EffectiveConfigValueDisplayBase
|
||||||
|
|
||||||
|
@* local-service: net | host. Pending value shown until save. *@
|
||||||
|
@if (IsActiveEditor && Descriptor.GetSource()?.IsReadOnly != true)
|
||||||
|
{
|
||||||
|
<select class="form-select form-select-sm" style="max-width: 10rem;" value="@(GetEffectiveDisplayValue() as string ?? "")" @onchange="OnChange" @onfocusout="OnCommitRequested">
|
||||||
|
<option value="">(not set)</option>
|
||||||
|
<option value="net">net</option>
|
||||||
|
<option value="host">host</option>
|
||||||
|
</select>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var v = GetEffectiveDisplayValue() as string;
|
||||||
|
@(string.IsNullOrEmpty(v) ? "(not set)" : (v.Trim().ToLowerInvariant() is "net" or "host" ? v.Trim() : v))
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private async Task OnChange(ChangeEventArgs e)
|
||||||
|
{
|
||||||
|
var v = e.Value?.ToString()?.Trim();
|
||||||
|
var value = string.IsNullOrEmpty(v) ? null : (v == "net" || v == "host" ? v : null);
|
||||||
|
await NotifyValueChanged(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig.CustomDisplays
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@inherits EffectiveConfigValueDisplayBase
|
||||||
|
|
||||||
|
@* log-queries: optional value extra|proto|auth. View: Off / On / On (extra|proto|auth). When active editor: dropdown. *@
|
||||||
|
@if (IsActiveEditor && Descriptor.GetSource()?.IsReadOnly != true)
|
||||||
|
{
|
||||||
|
<select class="form-select form-select-sm" style="max-width: 12rem;" value="@GetEditValue()" @onchange="OnChange" @onfocusout="OnCommitRequested">
|
||||||
|
<option value="">Off</option>
|
||||||
|
<option value="on">On</option>
|
||||||
|
<option value="extra">On (extra)</option>
|
||||||
|
<option value="proto">On (proto)</option>
|
||||||
|
<option value="auth">On (auth)</option>
|
||||||
|
</select>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
@GetViewText()
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private string GetEditValue()
|
||||||
|
{
|
||||||
|
var v = GetEffectiveDisplayValue() as string;
|
||||||
|
if (string.IsNullOrEmpty(v)) return "";
|
||||||
|
var lower = v.Trim().ToLowerInvariant();
|
||||||
|
if (lower is "extra" or "proto" or "auth") return lower;
|
||||||
|
return "on";
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetViewText()
|
||||||
|
{
|
||||||
|
var v = GetEffectiveDisplayValue() as string;
|
||||||
|
if (string.IsNullOrEmpty(v)) return "Off";
|
||||||
|
var lower = v.Trim().ToLowerInvariant();
|
||||||
|
return lower switch
|
||||||
|
{
|
||||||
|
"extra" => "On (extra)",
|
||||||
|
"proto" => "On (proto)",
|
||||||
|
"auth" => "On (auth)",
|
||||||
|
_ => "On"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnChange(ChangeEventArgs e)
|
||||||
|
{
|
||||||
|
var sel = e.Value?.ToString()?.Trim().ToLowerInvariant();
|
||||||
|
string? newValue = sel switch
|
||||||
|
{
|
||||||
|
"" or "off" => null,
|
||||||
|
"on" => "",
|
||||||
|
"extra" => "extra",
|
||||||
|
"proto" => "proto",
|
||||||
|
"auth" => "auth",
|
||||||
|
_ => null
|
||||||
|
};
|
||||||
|
await NotifyValueChanged(newValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig.CustomDisplays
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@inherits EffectiveConfigValueDisplayBase
|
||||||
|
|
||||||
|
@* Value-only display for the port option. Pending value shown until save. *@
|
||||||
|
@if (IsActiveEditor && Descriptor.GetSource()?.IsReadOnly != true)
|
||||||
|
{
|
||||||
|
var port = GetEffectiveDisplayValue() is int p ? p : 53;
|
||||||
|
<input type="number" class="form-control form-control-sm" style="max-width: 6rem;" min="1" max="65535" value="@port" @oninput="OnPortInput" @onfocusout="OnCommitRequested" />
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
@(GetEffectiveDisplayValue() is int port ? $"{port} (default DNS port)" : "(not set)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private async Task OnPortInput(ChangeEventArgs e)
|
||||||
|
{
|
||||||
|
if (int.TryParse(e.Value?.ToString(), out var port) && port >= 1 && port <= 65535)
|
||||||
|
await NotifyValueChanged(port);
|
||||||
|
else
|
||||||
|
await NotifyValueChanged(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Config
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Helpers.Config
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Services.EffectiveConfig.Abstractions
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Services.UI.Notifications.Abstractions
|
||||||
|
@using System.Net
|
||||||
|
@using System.Net.Sockets
|
||||||
|
@inject IEffectiveConfigRenderFragmentRegistry RenderFragmentRegistry
|
||||||
|
@inject INotificationService NotificationService
|
||||||
|
|
||||||
|
@* Custom fragment renders only the value; we keep the row shell (label + value slot + badge) here for consistency. Pending value shown until save. *@
|
||||||
|
@if (_customFragment is { } fragment)
|
||||||
|
{
|
||||||
|
var labelTooltip = DnsmasqOptionTooltips.Get(Descriptor.OptionName);
|
||||||
|
var isReadonly = Descriptor.GetSource()?.IsReadOnly == true;
|
||||||
|
var showEditableBadge = !isReadonly;
|
||||||
|
var isActiveEditor = IsEditMode && IsActive;
|
||||||
|
var fragmentWithCallback = isActiveEditor ? _fragmentWithCallback : null;
|
||||||
|
var effectiveValue = _effectiveValue;
|
||||||
|
<li class="ec-field @(isActiveEditor ? "ec-field-editing" : "")" title="@(Descriptor.GetSource()?.GetReadOnlyTooltip())">
|
||||||
|
<OptionHelpLabel AnchorId="@_anchorId" HelpKey="@_optionHelpKey" OptionLabel="@Descriptor.OptionName" Title="@(labelTooltip ?? Descriptor.GetSource()?.GetReadOnlyTooltip())"><strong>@Descriptor.OptionName:</strong></OptionHelpLabel>
|
||||||
|
<span class="ec-field-value">
|
||||||
|
@if (isActiveEditor)
|
||||||
|
{
|
||||||
|
<div class="ec-field-edit-wrapper" @onfocusout="OnBlur" @onclick:stopPropagation="true">
|
||||||
|
<CascadingValue Value="@true">
|
||||||
|
<CascadingValue Value="@(EventCallback.Factory.Create<FocusEventArgs>(this, OnBlur))">
|
||||||
|
@((fragmentWithCallback ?? fragment)(Descriptor))
|
||||||
|
</CascadingValue>
|
||||||
|
</CascadingValue>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<CascadingValue Value="@false">
|
||||||
|
@fragment(Descriptor)
|
||||||
|
</CascadingValue>
|
||||||
|
}
|
||||||
|
<OptionStateBadge AnchorId="@_readonlyBadgeAnchorId" Source="@Descriptor.GetSource()" OptionName="@Descriptor.OptionName" Value="@effectiveValue" IsInteractive="@IsEditMode" ShowEditableBadge="@showEditableBadge" HasPendingChange="@_hasPendingChange" EditableAsButton="true" FieldKey="@FieldKey" IsActiveEditor="@isActiveEditor" OnConfirmRequested="@HandleConfirmEdit" OnCancelRequested="@HandleCancelEdit" OnRevertRequested="@HandleRevertEdit" />
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
else if (Descriptor.IsMultiValue)
|
||||||
|
{
|
||||||
|
@* Multi-value state is computed in OnParametersSet and in HandleMultiValueChanged; we only read cached fields here. *@
|
||||||
|
<EffectiveConfigMultiValueRow Label="@Descriptor.OptionName" Items="@_multiValueItems" LabelTooltip="@_labelTooltip" OptionHelpKey="@_optionHelpKey" OptionHelpAnchorId="@_anchorId"
|
||||||
|
IsActiveEditor="@(IsEditMode && IsActive)" IsEditMode="@IsEditMode" ReadonlyBadgeAnchorIdBase="@_readonlyBadgeAnchorId"
|
||||||
|
Source="@_multiValueRowSource" ShowEditableBadge="@IsEditMode" HasPendingChange="@_multiValueHasPendingOrDraft" FieldKey="@FieldKey"
|
||||||
|
ItemsChanged="@HandleMultiValueChanged" OnConfirmRequested="@HandleConfirmEdit" OnCancelRequested="@HandleCancelEdit" OnRevertRequested="@HandleRevertEdit" />
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var value = _effectiveValue;
|
||||||
|
var displayValue = value == null ? "(not set)" : (value is IReadOnlyList<string> list ? (list.Count == 0 ? "(none)" : string.Join(", ", list)) : value.ToString());
|
||||||
|
var isReadonly = Descriptor.GetSource()?.IsReadOnly == true;
|
||||||
|
var showReadonlyHint = IsEditMode && isReadonly;
|
||||||
|
var isActiveEditor = IsEditMode && IsActive;
|
||||||
|
@if (showReadonlyHint)
|
||||||
|
{
|
||||||
|
<li class="ec-field" title="@(Descriptor.GetSource()?.GetReadOnlyTooltip())">
|
||||||
|
<EffectiveConfigOptionItem Label="@Descriptor.OptionName" DisplayValue="@(displayValue ?? "(not set)")" Source="@Descriptor.GetSource()" LabelTooltip="@_labelTooltip" OptionHelpKey="@_optionHelpKey" OptionHelpAnchorId="@_anchorId"
|
||||||
|
FieldKey="@FieldKey" ReadonlyBadgeAnchorId="@_readonlyBadgeAnchorId" RawValue="@value" HasPendingChange="@_hasPendingChange" />
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<li class="ec-field @(isActiveEditor ? "ec-field-editing" : "")" title="@(Descriptor.GetSource()?.GetReadOnlyTooltip())">
|
||||||
|
<EffectiveConfigOptionItem Label="@Descriptor.OptionName" DisplayValue="@(displayValue ?? "(not set)")" Source="@Descriptor.GetSource()" LabelTooltip="@_labelTooltip" OptionHelpKey="@_optionHelpKey" OptionHelpAnchorId="@_anchorId"
|
||||||
|
ShowEditableBadge="true" FieldKey="@FieldKey" IsActive="@IsActive"
|
||||||
|
ReadonlyBadgeAnchorId="@_readonlyBadgeAnchorId" RawValue="@value" HasPendingChange="@_hasPendingChange"
|
||||||
|
DisplayValueChanged="@HandleDefaultValueChanged" OnBlur="@HandleDefaultBlur" OnConfirmRequested="@HandleConfirmEdit" OnCancelRequested="@HandleCancelEdit" OnRevertRequested="@HandleRevertEdit" />
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public EffectiveConfigFieldDescriptor Descriptor { get; set; } = null!;
|
||||||
|
[Parameter] public string FieldKey { get; set; } = "";
|
||||||
|
[Parameter] public bool IsEditMode { get; set; }
|
||||||
|
[Parameter] public bool IsActive { get; set; }
|
||||||
|
[CascadingParameter] public IEffectiveConfigEditSession? Session { get; set; }
|
||||||
|
|
||||||
|
private readonly string _anchorId = "ec-help-" + Guid.NewGuid().ToString("N")[..8];
|
||||||
|
private readonly string _readonlyBadgeAnchorId = "ec-readonly-" + Guid.NewGuid().ToString("N")[..8];
|
||||||
|
private RenderFragment<EffectiveConfigFieldDescriptor>? _customFragment;
|
||||||
|
private RenderFragment<EffectiveConfigFieldDescriptor>? _fragmentWithCallback;
|
||||||
|
private string? _labelTooltip;
|
||||||
|
private string? _optionHelpKey;
|
||||||
|
private object? _effectiveValue;
|
||||||
|
private bool _hasPendingChange;
|
||||||
|
private object? _valueAtActivation;
|
||||||
|
private object? _draftValue;
|
||||||
|
private bool _wasActive;
|
||||||
|
private ExitAction _exitAction = ExitAction.None;
|
||||||
|
|
||||||
|
/// <summary>Cached for multi-value: items to pass to the row (with sources preserved for draft merge).</summary>
|
||||||
|
private IReadOnlyList<ValueWithSource>? _multiValueItems;
|
||||||
|
/// <summary>Cached for multi-value: true when there is an uncommitted draft list.</summary>
|
||||||
|
private bool _multiValueHasDraft;
|
||||||
|
/// <summary>Cached for multi-value: row-level source for badge (readonly when all items readonly and not edit mode).</summary>
|
||||||
|
private ConfigValueSource? _multiValueRowSource;
|
||||||
|
/// <summary>Cached for multi-value: whether row should show ok/cancel (session pending or local draft).</summary>
|
||||||
|
private bool _multiValueHasPendingOrDraft;
|
||||||
|
|
||||||
|
protected override void OnParametersSet()
|
||||||
|
{
|
||||||
|
_customFragment = RenderFragmentRegistry.BuildFieldComponentFragment(Descriptor.SectionId, Descriptor.OptionName);
|
||||||
|
_fragmentWithCallback = RenderFragmentRegistry.BuildFieldComponentFragment(Descriptor.SectionId, Descriptor.OptionName, EventCallback.Factory.Create<object?>(this, HandleValueChanged));
|
||||||
|
_labelTooltip = DnsmasqOptionTooltips.Get(Descriptor.OptionName);
|
||||||
|
_optionHelpKey = Descriptor.OptionName;
|
||||||
|
var pending = Session?.PendingChanges.FirstOrDefault(c =>
|
||||||
|
string.Equals(c.SectionId, Descriptor.SectionId, StringComparison.OrdinalIgnoreCase) &&
|
||||||
|
string.Equals(c.OptionName, Descriptor.OptionName, StringComparison.OrdinalIgnoreCase));
|
||||||
|
var descriptorValue = Descriptor.IsMultiValue
|
||||||
|
? (Descriptor.GetItems()?.Select(i => i.Value).ToList() ?? new List<string>())
|
||||||
|
: Descriptor.GetValue();
|
||||||
|
_hasPendingChange = pending != null;
|
||||||
|
_effectiveValue = pending != null ? pending.NewValue : descriptorValue;
|
||||||
|
if (Descriptor.IsMultiValue)
|
||||||
|
ComputeMultiValueState(Descriptor.GetItems(), pending?.NewValue as IReadOnlyList<string>, _draftValue as IReadOnlyList<string>);
|
||||||
|
if (!_wasActive && IsActive)
|
||||||
|
_valueAtActivation = descriptorValue;
|
||||||
|
if (_wasActive && !IsActive && _exitAction == ExitAction.None)
|
||||||
|
_ = InvokeAsync(CommitIfChangedAsync);
|
||||||
|
if (_wasActive && !IsActive)
|
||||||
|
_exitAction = ExitAction.None;
|
||||||
|
_wasActive = IsActive;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ComputeMultiValueState(IReadOnlyList<ValueWithSource>? descriptorItems, IReadOnlyList<string>? pendingList, IReadOnlyList<string>? draftList)
|
||||||
|
{
|
||||||
|
var descriptorValues = descriptorItems?.Select(i => i.Value).ToList() ?? new List<string>();
|
||||||
|
_multiValueHasDraft = draftList != null && !ValuesEqual(descriptorValues, draftList);
|
||||||
|
if (_multiValueHasDraft && draftList != null)
|
||||||
|
{
|
||||||
|
_multiValueItems = BuildItemsWithSource(descriptorItems, draftList);
|
||||||
|
}
|
||||||
|
else if (_hasPendingChange && pendingList != null)
|
||||||
|
{
|
||||||
|
_multiValueItems = BuildItemsWithSource(descriptorItems, pendingList);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_multiValueItems = descriptorItems;
|
||||||
|
}
|
||||||
|
var allReadonly = _multiValueItems != null && _multiValueItems.Count > 0 && _multiValueItems.All(i => i.Source?.IsReadOnly == true);
|
||||||
|
_multiValueRowSource = allReadonly && !IsEditMode ? _multiValueItems?.FirstOrDefault()?.Source : null;
|
||||||
|
_multiValueHasPendingOrDraft = _hasPendingChange || _multiValueHasDraft;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<ValueWithSource> BuildItemsWithSource(IReadOnlyList<ValueWithSource>? descriptorItems, IReadOnlyList<string> values)
|
||||||
|
{
|
||||||
|
var pool = descriptorItems?.ToList() ?? new List<ValueWithSource>();
|
||||||
|
var list = new List<ValueWithSource>(values.Count);
|
||||||
|
foreach (var s in values)
|
||||||
|
{
|
||||||
|
var idx = pool.FindIndex(x => string.Equals(x.Value, s, StringComparison.Ordinal));
|
||||||
|
if (idx >= 0)
|
||||||
|
{
|
||||||
|
list.Add(pool[idx]);
|
||||||
|
pool.RemoveAt(idx);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
list.Add(new ValueWithSource(s, null));
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void HandleValueChanged(object? value)
|
||||||
|
{
|
||||||
|
_draftValue = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnBlur(FocusEventArgs _)
|
||||||
|
{
|
||||||
|
if (!IsActive) return;
|
||||||
|
await CommitIfChangedAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<bool> CommitIfChangedAsync()
|
||||||
|
{
|
||||||
|
var newValue = _draftValue ?? _effectiveValue;
|
||||||
|
if (!ValuesEqual(_valueAtActivation, newValue))
|
||||||
|
{
|
||||||
|
var validationError = ValidateDraftValue(newValue);
|
||||||
|
if (validationError != null)
|
||||||
|
{
|
||||||
|
NotificationService.ShowError(validationError);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var source = Descriptor.GetSource();
|
||||||
|
object? valueToCommit = newValue;
|
||||||
|
if (newValue is IReadOnlyList<string> list)
|
||||||
|
{
|
||||||
|
var deduped = list.Distinct(StringComparer.Ordinal).ToList();
|
||||||
|
valueToCommit = deduped;
|
||||||
|
}
|
||||||
|
var args = new EffectiveConfigEditCommittedArgs(Descriptor.SectionId, Descriptor.OptionName, _valueAtActivation, valueToCommit, source?.FilePath);
|
||||||
|
if (Ui != null)
|
||||||
|
await Ui.CommitFieldAsync(args);
|
||||||
|
}
|
||||||
|
_draftValue = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[CascadingParameter] private EffectiveConfigUiContext? Ui { get; set; }
|
||||||
|
|
||||||
|
private void HandleDefaultValueChanged(string value)
|
||||||
|
{
|
||||||
|
_draftValue = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleDefaultBlur(string? value)
|
||||||
|
{
|
||||||
|
if (!IsActive) return;
|
||||||
|
_draftValue = value;
|
||||||
|
if (!await CommitIfChangedAsync() && Ui != null)
|
||||||
|
await Ui.ActivateFieldAsync(FieldKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void HandleMultiValueChanged(IReadOnlyList<string> values)
|
||||||
|
{
|
||||||
|
_draftValue = values.ToList();
|
||||||
|
if (Descriptor.IsMultiValue)
|
||||||
|
ComputeMultiValueState(Descriptor.GetItems(), _effectiveValue as IReadOnlyList<string>, _draftValue as IReadOnlyList<string>);
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleConfirmEdit()
|
||||||
|
{
|
||||||
|
if (!await CommitIfChangedAsync())
|
||||||
|
return;
|
||||||
|
_exitAction = ExitAction.Confirm;
|
||||||
|
if (Ui != null)
|
||||||
|
await Ui.DeactivateFieldAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleCancelEdit()
|
||||||
|
{
|
||||||
|
_draftValue = null;
|
||||||
|
_exitAction = ExitAction.Cancel;
|
||||||
|
if (Ui != null)
|
||||||
|
await Ui.DeactivateFieldAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleRevertEdit()
|
||||||
|
{
|
||||||
|
_draftValue = null;
|
||||||
|
Session?.RevertChange(Descriptor.SectionId, Descriptor.OptionName);
|
||||||
|
_exitAction = ExitAction.Revert;
|
||||||
|
if (Ui != null)
|
||||||
|
await Ui.DeactivateFieldAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private string? ValidateDraftValue(object? value)
|
||||||
|
{
|
||||||
|
if (string.Equals(Descriptor.OptionName, DnsmasqConfKeys.ListenAddress, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
var values = AsStringList(value) ?? (value is string s ? new[] { s } : null);
|
||||||
|
if (values == null) return null;
|
||||||
|
foreach (var raw in values)
|
||||||
|
{
|
||||||
|
var v = raw.Trim();
|
||||||
|
if (!IPAddress.TryParse(v, out var ip) || (ip.AddressFamily != AddressFamily.InterNetwork && ip.AddressFamily != AddressFamily.InterNetworkV6))
|
||||||
|
return $"Invalid value for {DnsmasqConfKeys.ListenAddress}: '{raw}'. Use a valid IPv4 or IPv6 address.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<string>? AsStringList(object? value)
|
||||||
|
{
|
||||||
|
return value as IReadOnlyList<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool ValuesEqual(object? oldValue, object? newValue)
|
||||||
|
{
|
||||||
|
var oldList = AsStringList(oldValue);
|
||||||
|
var newList = AsStringList(newValue);
|
||||||
|
if (oldList != null || newList != null)
|
||||||
|
return (oldList ?? Array.Empty<string>()).SequenceEqual(newList ?? Array.Empty<string>(), StringComparer.Ordinal);
|
||||||
|
return Equals(oldValue, newValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum ExitAction { None, Confirm, Cancel, Revert }
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
|
||||||
|
<span class="ec-field-value-item" title="@(ReadonlyClickActivatesField ? ReadonlyTitleOverride : Source?.GetReadOnlyTooltip())">
|
||||||
|
@Value
|
||||||
|
<OptionStateBadge AnchorId="@(ReadonlyBadgeAnchorId ?? "")" Source="@Source" OptionName="@OptionName" Value="@Value"
|
||||||
|
IsInteractive="@(IsEditMode && !ReadonlyClickActivatesField && !string.IsNullOrEmpty(ReadonlyBadgeAnchorId))"
|
||||||
|
ShowEditableBadge="@(Source?.IsReadOnly != true)" EditableAsButton="@IsEditMode"
|
||||||
|
FieldKey="@FieldKey" ReadonlyClickActivatesField="@ReadonlyClickActivatesField" ReadonlyTitleOverride="@ReadonlyTitleOverride" />
|
||||||
|
</span>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public string Value { get; set; } = "";
|
||||||
|
[Parameter] public ConfigValueSource? Source { get; set; }
|
||||||
|
[Parameter] public string OptionName { get; set; } = "";
|
||||||
|
[Parameter] public bool IsEditMode { get; set; }
|
||||||
|
[Parameter] public string? ReadonlyBadgeAnchorId { get; set; }
|
||||||
|
[Parameter] public string? FieldKey { get; set; }
|
||||||
|
[Parameter] public bool ReadonlyClickActivatesField { get; set; }
|
||||||
|
[Parameter] public string? ReadonlyTitleOverride { get; set; }
|
||||||
|
}
|
||||||
+167
@@ -0,0 +1,167 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
|
||||||
|
<span class="ec-field-value ec-field-value-multi ec-multi-list-editor" @onclick:stopPropagation="true">
|
||||||
|
<ol class="ec-field-value-list">
|
||||||
|
@if (SourceItems?.Count > 0)
|
||||||
|
{
|
||||||
|
@for (var i = 0; i < SourceItems.Count; i++)
|
||||||
|
{
|
||||||
|
var item = SourceItems[i];
|
||||||
|
var anchorId = $"{ReadonlyBadgeAnchorIdBase}-{i}";
|
||||||
|
var itemReadonly = item.Source?.IsReadOnly == true;
|
||||||
|
var rowIndex = i;
|
||||||
|
var rowValue = item.Value;
|
||||||
|
|
||||||
|
<li class="ec-multi-list-row" @key="anchorId">
|
||||||
|
@if (_editingIndex == rowIndex && !itemReadonly)
|
||||||
|
{
|
||||||
|
<input class="form-control form-control-sm ec-multi-list-input"
|
||||||
|
@bind="_draftValue" @bind:event="oninput" />
|
||||||
|
<span class="status-badge-inline">
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.ActionOk" Text="save" Clickable="true"
|
||||||
|
Title="Apply change" AriaLabel="Apply change"
|
||||||
|
PreventBlurOnMouseDown="true" OnClick="@(() => SaveEdit(rowIndex))" Class="status-badge-inline" />
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.ActionCancel" Text="cancel" Clickable="true"
|
||||||
|
Title="Discard edit" AriaLabel="Cancel edit"
|
||||||
|
PreventBlurOnMouseDown="true" OnClick="CancelInline" Class="status-badge-inline" />
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="ec-field-value-item">@rowValue</span>
|
||||||
|
|
||||||
|
<span class="status-badge-inline">
|
||||||
|
<OptionStateBadge
|
||||||
|
AnchorId="@anchorId"
|
||||||
|
Source="@item.Source"
|
||||||
|
OptionName="@OptionName"
|
||||||
|
Value="@rowValue"
|
||||||
|
IsInteractive="@IsEditMode"
|
||||||
|
ShowEditableBadge="@(!itemReadonly)"
|
||||||
|
EditableAsButton="@(!itemReadonly)"
|
||||||
|
OnEditableClickRequested="@(!itemReadonly ? EventCallback.Factory.Create(this, () => { BeginEdit(rowIndex, rowValue); return Task.CompletedTask; }) : default)" />
|
||||||
|
@if (!itemReadonly)
|
||||||
|
{
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.ActionRevert" Text="remove" Clickable="true"
|
||||||
|
Title="Remove this value" AriaLabel="Remove"
|
||||||
|
OnClick="@(() => RemoveAt(rowIndex))" Class="status-badge-inline" />
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<li class="ec-multi-list-row ec-multi-list-empty-hint">
|
||||||
|
<span class="text-muted">(none)</span>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (AllowAddManagedValue)
|
||||||
|
{
|
||||||
|
<li class="ec-multi-list-row ec-multi-list-add-item" @key="AddItemKey">
|
||||||
|
@if (_addingNew)
|
||||||
|
{
|
||||||
|
<input class="form-control form-control-sm ec-multi-list-input"
|
||||||
|
placeholder="New value"
|
||||||
|
@bind="_draftValue" @bind:event="oninput" />
|
||||||
|
<span class="status-badge-inline">
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.ActionOk" Text="add" Clickable="true"
|
||||||
|
Title="Add this value" AriaLabel="Add"
|
||||||
|
PreventBlurOnMouseDown="true" OnClick="SaveNew" Class="status-badge-inline" />
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.ActionCancel" Text="cancel" Clickable="true"
|
||||||
|
Title="Discard" AriaLabel="Cancel"
|
||||||
|
PreventBlurOnMouseDown="true" OnClick="CancelInline" Class="status-badge-inline" />
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.Editable" Text="add item" Clickable="true"
|
||||||
|
Title="Add a new value" AriaLabel="Add item"
|
||||||
|
OnClick="BeginAdd" Class="status-badge-inline ec-multi-list-add-btn" />
|
||||||
|
}
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ol>
|
||||||
|
</span>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public IReadOnlyList<ValueWithSource>? SourceItems { get; set; }
|
||||||
|
[Parameter] public string OptionName { get; set; } = "";
|
||||||
|
[Parameter] public string ReadonlyBadgeAnchorIdBase { get; set; } = "";
|
||||||
|
|
||||||
|
[Parameter] public bool IsEditMode { get; set; }
|
||||||
|
[Parameter] public bool AllowAddManagedValue { get; set; } = true;
|
||||||
|
|
||||||
|
[Parameter] public EventCallback<IReadOnlyList<string>> OnValuesChanged { get; set; }
|
||||||
|
|
||||||
|
private const string AddItemKey = "add-item";
|
||||||
|
private int? _editingIndex;
|
||||||
|
private bool _addingNew;
|
||||||
|
private string _draftValue = "";
|
||||||
|
|
||||||
|
private void BeginEdit(int index, string current)
|
||||||
|
{
|
||||||
|
_addingNew = false;
|
||||||
|
_editingIndex = index;
|
||||||
|
_draftValue = current;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BeginAdd()
|
||||||
|
{
|
||||||
|
_editingIndex = null;
|
||||||
|
_addingNew = true;
|
||||||
|
_draftValue = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CancelInline()
|
||||||
|
{
|
||||||
|
_editingIndex = null;
|
||||||
|
_addingNew = false;
|
||||||
|
_draftValue = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SaveEdit(int index)
|
||||||
|
{
|
||||||
|
var next = (SourceItems ?? Array.Empty<ValueWithSource>())
|
||||||
|
.Select(x => x.Value)
|
||||||
|
.ToList();
|
||||||
|
if (index < 0 || index >= next.Count) return;
|
||||||
|
|
||||||
|
next[index] = (_draftValue ?? "").Trim();
|
||||||
|
await OnValuesChanged.InvokeAsync(next);
|
||||||
|
CancelInline();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SaveNew()
|
||||||
|
{
|
||||||
|
var value = (_draftValue ?? "").Trim();
|
||||||
|
if (value.Length == 0) return;
|
||||||
|
|
||||||
|
var next = (SourceItems ?? Array.Empty<ValueWithSource>())
|
||||||
|
.Select(x => x.Value)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
next.Add(value);
|
||||||
|
await OnValuesChanged.InvokeAsync(next);
|
||||||
|
CancelInline();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RemoveAt(int index)
|
||||||
|
{
|
||||||
|
if (SourceItems == null || index < 0 || index >= SourceItems.Count) return;
|
||||||
|
var item = SourceItems[index];
|
||||||
|
if (item?.Source?.IsReadOnly == true) return;
|
||||||
|
|
||||||
|
var next = (SourceItems ?? Array.Empty<ValueWithSource>())
|
||||||
|
.Select(x => x.Value)
|
||||||
|
.ToList();
|
||||||
|
if (index < 0 || index >= next.Count) return;
|
||||||
|
|
||||||
|
next.RemoveAt(index);
|
||||||
|
await OnValuesChanged.InvokeAsync(next);
|
||||||
|
}
|
||||||
|
}
|
||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
/* Editor block: distinct from display mode (border + background) */
|
||||||
|
.ec-multi-list-editor {
|
||||||
|
display: block;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
border: 1px solid var(--bs-border-color, #dee2e6);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
background-color: var(--bs-body-bg, #fff);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-multi-list-editor .ec-field-value-list {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-multi-list-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
min-height: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-multi-list-row .ec-field-value-item {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-multi-list-row .status-badge-inline {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.25rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-multi-list-row .form-control.ec-multi-list-input {
|
||||||
|
max-width: 28rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-multi-list-empty-hint {
|
||||||
|
list-style: none;
|
||||||
|
margin-left: -1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-multi-list-add-item {
|
||||||
|
list-style: none;
|
||||||
|
margin-left: -1.25rem;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
padding-top: 0.25rem;
|
||||||
|
border-top: 1px dashed var(--bs-border-color, #dee2e6);
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-multi-list-add-item .form-control.ec-multi-list-input {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
max-width: none;
|
||||||
|
min-width: 12rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-multi-list-add-item .status-badge-inline {
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-multi-list-add-btn {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
|
||||||
|
<li class="ec-field">
|
||||||
|
<OptionHelpLabel AnchorId="@(OptionHelpAnchorId ?? "")" HelpKey="@OptionHelpKey" OptionLabel="@Label" Title="@LabelTooltip"><strong>@Label:</strong></OptionHelpLabel>
|
||||||
|
@if (IsActiveEditor)
|
||||||
|
{
|
||||||
|
<EffectiveConfigMultiValueListEditor
|
||||||
|
SourceItems="@(Items ?? Array.Empty<ValueWithSource>())"
|
||||||
|
OptionName="@Label"
|
||||||
|
ReadonlyBadgeAnchorIdBase="@(ReadonlyBadgeAnchorIdBase ?? "")"
|
||||||
|
IsEditMode="@IsEditMode"
|
||||||
|
AllowAddManagedValue="@IsEditMode"
|
||||||
|
OnValuesChanged="@ItemsChanged" />
|
||||||
|
<OptionStateBadge AnchorId="@(ReadonlyBadgeAnchorIdBase ?? "")" Source="@Source" OptionName="@Label" Value="@Items"
|
||||||
|
IsInteractive="@IsEditMode" ShowEditableBadge="@ShowEditableBadge" HasPendingChange="@HasPendingChange"
|
||||||
|
EditableAsButton="true" FieldKey="@FieldKey" IsActiveEditor="@IsActiveEditor"
|
||||||
|
OnConfirmRequested="@OnConfirmRequested" OnCancelRequested="@OnCancelRequested" OnRevertRequested="@OnRevertRequested" />
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="ec-field-value ec-field-value-multi">
|
||||||
|
@if (Items?.Count > 0)
|
||||||
|
{
|
||||||
|
<ol class="ec-field-value-list">
|
||||||
|
@foreach (var (item, index) in Items!.Select((item, index) => (item, index)))
|
||||||
|
{
|
||||||
|
var anchorId = ReadonlyBadgeAnchorIdBase != null ? ReadonlyBadgeAnchorIdBase + "-" + index : "";
|
||||||
|
<li><EffectiveConfigMultiValueItem Value="@item.Value" Source="@item.Source" OptionName="@Label" IsEditMode="@IsEditMode" ReadonlyBadgeAnchorId="@anchorId" FieldKey="@FieldKey" ReadonlyClickActivatesField="true" ReadonlyTitleOverride="New values can still be added. Click to edit." /></li>
|
||||||
|
}
|
||||||
|
</ol>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="text-muted">(none)</span>
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</li>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public string Label { get; set; } = "";
|
||||||
|
[Parameter] public IReadOnlyList<ValueWithSource>? Items { get; set; }
|
||||||
|
[Parameter] public EventCallback<IReadOnlyList<string>> ItemsChanged { get; set; }
|
||||||
|
[Parameter] public string? LabelTooltip { get; set; }
|
||||||
|
[Parameter] public string? OptionHelpKey { get; set; }
|
||||||
|
[Parameter] public string? OptionHelpAnchorId { get; set; }
|
||||||
|
[Parameter] public bool IsActiveEditor { get; set; }
|
||||||
|
[Parameter] public bool IsEditMode { get; set; }
|
||||||
|
[Parameter] public string? ReadonlyBadgeAnchorIdBase { get; set; }
|
||||||
|
[Parameter] public ConfigValueSource? Source { get; set; }
|
||||||
|
[Parameter] public bool ShowEditableBadge { get; set; }
|
||||||
|
[Parameter] public bool HasPendingChange { get; set; }
|
||||||
|
[Parameter] public string FieldKey { get; set; } = "";
|
||||||
|
[Parameter] public EventCallback OnConfirmRequested { get; set; }
|
||||||
|
[Parameter] public EventCallback OnCancelRequested { get; set; }
|
||||||
|
[Parameter] public EventCallback OnRevertRequested { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
|
||||||
|
<OptionHelpLabel AnchorId="@(OptionHelpAnchorId ?? "")" HelpKey="@OptionHelpKey" OptionLabel="@Label" Title="@(LabelTooltip ?? Source?.GetReadOnlyTooltip())"><strong>@Label:</strong></OptionHelpLabel>
|
||||||
|
@if (DisplayMode == EffectiveConfigDisplayMode.Edit && IsActive && Source?.IsReadOnly != true)
|
||||||
|
{
|
||||||
|
<span class="ec-field-value" @onclick:stopPropagation="true">
|
||||||
|
<input type="text" class="form-control form-control-sm" value="@(_editValue ?? DisplayValue)" @oninput="OnValueInput" @onfocusout="OnInputBlur" />
|
||||||
|
<OptionStateBadge AnchorId="@(ReadonlyBadgeAnchorId ?? "")" Source="@Source" OptionName="@Label" Value="@(RawValue ?? DisplayValue)" IsInteractive="@(DisplayMode == EffectiveConfigDisplayMode.Edit && !string.IsNullOrEmpty(ReadonlyBadgeAnchorId))" ShowEditableBadge="@ShowEditableBadge" HasPendingChange="@HasPendingChange" EditableAsButton="true" FieldKey="@FieldKey" IsActiveEditor="true" OnConfirmRequested="@OnConfirmRequested" OnCancelRequested="@OnCancelRequested" OnRevertRequested="@OnRevertRequested" />
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="ec-field-value">
|
||||||
|
@DisplayValue
|
||||||
|
<OptionStateBadge AnchorId="@(ReadonlyBadgeAnchorId ?? "")" Source="@Source" OptionName="@Label" Value="@(RawValue ?? DisplayValue)" IsInteractive="@(DisplayMode == EffectiveConfigDisplayMode.Edit && !string.IsNullOrEmpty(ReadonlyBadgeAnchorId))" ShowEditableBadge="@ShowEditableBadge" HasPendingChange="@HasPendingChange" EditableAsButton="true" FieldKey="@FieldKey" IsActiveEditor="false" OnConfirmRequested="@OnConfirmRequested" OnCancelRequested="@OnCancelRequested" OnRevertRequested="@OnRevertRequested" />
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public string Label { get; set; } = "";
|
||||||
|
[Parameter] public string DisplayValue { get; set; } = "";
|
||||||
|
[Parameter] public ConfigValueSource? Source { get; set; }
|
||||||
|
/// <summary>Optional explainer shown on hover over the label (e.g. from DnsmasqOptionTooltips).</summary>
|
||||||
|
[Parameter] public string? LabelTooltip { get; set; }
|
||||||
|
[Parameter] public string? OptionHelpKey { get; set; }
|
||||||
|
[Parameter] public string? OptionHelpAnchorId { get; set; }
|
||||||
|
/// <summary>When set in edit mode, the readonly badge is rendered as a button with this id so the popover can anchor to it.</summary>
|
||||||
|
[Parameter] public string? ReadonlyBadgeAnchorId { get; set; }
|
||||||
|
/// <summary>Raw value for the readonly popover override line (e.g. from descriptor); falls back to DisplayValue.</summary>
|
||||||
|
[Parameter] public object? RawValue { get; set; }
|
||||||
|
/// <summary>When true, show an 'editable' badge next to non-readonly fields; clicking it activates edit for this field.</summary>
|
||||||
|
[Parameter] public bool ShowEditableBadge { get; set; }
|
||||||
|
/// <summary>When true, badge shows "pending" and warning style to indicate this field has an unsaved change.</summary>
|
||||||
|
[Parameter] public bool HasPendingChange { get; set; }
|
||||||
|
/// <summary>Field key for activation via context when editable badge is clicked.</summary>
|
||||||
|
[Parameter] public string FieldKey { get; set; } = "";
|
||||||
|
/// <summary>When true, add ec-field-editing class and show input when DisplayMode is Edit.</summary>
|
||||||
|
[Parameter] public bool IsActive { get; set; }
|
||||||
|
/// <summary>When Edit and not readonly: raised when the user changes the value. Not yet wired to save.</summary>
|
||||||
|
[Parameter] public EventCallback<string> DisplayValueChanged { get; set; }
|
||||||
|
/// <summary>When Edit and not readonly: raised when the input loses focus; argument is the current value.</summary>
|
||||||
|
[Parameter] public EventCallback<string?> OnBlur { get; set; }
|
||||||
|
/// <summary>When user clicks OK; parent should commit and deactivate.</summary>
|
||||||
|
[Parameter] public EventCallback OnConfirmRequested { get; set; }
|
||||||
|
/// <summary>When user clicks Cancel; parent should clear draft and deactivate.</summary>
|
||||||
|
[Parameter] public EventCallback OnCancelRequested { get; set; }
|
||||||
|
/// <summary>When user clicks Revert; parent should revert pending, clear draft, and deactivate.</summary>
|
||||||
|
[Parameter] public EventCallback OnRevertRequested { get; set; }
|
||||||
|
[CascadingParameter] public EffectiveConfigDisplayMode DisplayMode { get; set; } = EffectiveConfigDisplayMode.View;
|
||||||
|
|
||||||
|
private string? _editValue;
|
||||||
|
|
||||||
|
protected override void OnParametersSet()
|
||||||
|
{
|
||||||
|
if (DisplayMode != EffectiveConfigDisplayMode.Edit)
|
||||||
|
_editValue = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnValueInput(ChangeEventArgs e)
|
||||||
|
{
|
||||||
|
var value = e.Value?.ToString() ?? "";
|
||||||
|
_editValue = value;
|
||||||
|
await DisplayValueChanged.InvokeAsync(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnInputBlur(FocusEventArgs _)
|
||||||
|
{
|
||||||
|
if (OnBlur.HasDelegate)
|
||||||
|
await OnBlur.InvokeAsync(_editValue ?? DisplayValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Extensions.DependencyInjection
|
||||||
|
@using Microsoft.AspNetCore.Components
|
||||||
|
@using Microsoft.JSInterop
|
||||||
|
@using System.Text.Json.Serialization
|
||||||
|
@inject IHttpClientFactory HttpFactory
|
||||||
|
@inject IJSRuntime JSRuntime
|
||||||
|
@implements IAsyncDisposable
|
||||||
|
|
||||||
|
@if (Visible)
|
||||||
|
{
|
||||||
|
<div class="config-option-help-popover" id="@_popoverId" style="@_positionStyle" @onmouseenter="OnModalMouseEnter" @onmouseleave="OnModalMouseLeave">
|
||||||
|
<div class="config-option-help-popover-content">
|
||||||
|
<div class="config-option-help-popover-header">
|
||||||
|
<span class="config-option-help-popover-title">@Title</span>
|
||||||
|
</div>
|
||||||
|
<div class="config-option-help-popover-body">
|
||||||
|
@if (_loading)
|
||||||
|
{
|
||||||
|
<p class="text-muted small mb-0">Loading…</p>
|
||||||
|
}
|
||||||
|
else if (_error != null)
|
||||||
|
{
|
||||||
|
<p class="text-danger small mb-0">@_error</p>
|
||||||
|
}
|
||||||
|
else if (_helpHtml != null)
|
||||||
|
{
|
||||||
|
<div class="option-help">@((MarkupString)_helpHtml)</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public string? HelpKey { get; set; }
|
||||||
|
[Parameter] public string? AnchorId { get; set; }
|
||||||
|
[Parameter] public bool Visible { get; set; }
|
||||||
|
[Parameter] public string Title { get; set; } = "Option help";
|
||||||
|
[Parameter] public EventCallback OnClose { get; set; }
|
||||||
|
[Parameter] public EventCallback OnMouseEnterModal { get; set; }
|
||||||
|
[Parameter] public EventCallback OnMouseLeaveModal { get; set; }
|
||||||
|
|
||||||
|
private string? _helpHtml;
|
||||||
|
private string? _error;
|
||||||
|
private bool _loading;
|
||||||
|
private string? _lastKey;
|
||||||
|
private string _positionStyle = "";
|
||||||
|
private readonly string _popoverId = "config-option-help-popover-" + Guid.NewGuid().ToString("N")[..8];
|
||||||
|
private DotNetObjectReference<ConfigOptionHelpModal>? _dotNetRef;
|
||||||
|
private bool _scrollListenerAdded;
|
||||||
|
private bool _mouseOverModal;
|
||||||
|
private IJSObjectReference? _jsModule;
|
||||||
|
private bool _moduleLoaded;
|
||||||
|
|
||||||
|
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||||
|
{
|
||||||
|
if (firstRender)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/config-option-help.js");
|
||||||
|
_moduleLoaded = true;
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException) { /* prerender */ }
|
||||||
|
catch (JSDisconnectedException) { /* circuit disconnected */ }
|
||||||
|
catch (JSException) { /* import failed */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Visible && !_scrollListenerAdded && _moduleLoaded && _jsModule != null)
|
||||||
|
{
|
||||||
|
_scrollListenerAdded = true;
|
||||||
|
_dotNetRef = DotNetObjectReference.Create(this);
|
||||||
|
await _jsModule.InvokeVoidAsyncSafe("addScrollCloseListener", _dotNetRef);
|
||||||
|
}
|
||||||
|
else if (!Visible && _scrollListenerAdded && _jsModule != null)
|
||||||
|
{
|
||||||
|
_scrollListenerAdded = false;
|
||||||
|
await _jsModule.InvokeVoidAsyncSafe("removeScrollCloseListener");
|
||||||
|
_dotNetRef?.Dispose();
|
||||||
|
_dotNetRef = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[JSInvokable]
|
||||||
|
public async Task OnScrollClose()
|
||||||
|
{
|
||||||
|
await PositionUnderAnchorAsync();
|
||||||
|
StateHasChanged();
|
||||||
|
if (!_mouseOverModal)
|
||||||
|
await OnClose.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
if (_scrollListenerAdded && _jsModule != null)
|
||||||
|
{
|
||||||
|
_scrollListenerAdded = false;
|
||||||
|
await _jsModule.InvokeVoidAsyncSafe("removeScrollCloseListener");
|
||||||
|
_dotNetRef?.Dispose();
|
||||||
|
_dotNetRef = null;
|
||||||
|
}
|
||||||
|
await _jsModule.DisposeAsyncSafe();
|
||||||
|
_jsModule = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task OnParametersSetAsync()
|
||||||
|
{
|
||||||
|
if (!Visible || string.IsNullOrEmpty(HelpKey))
|
||||||
|
{
|
||||||
|
_helpHtml = null;
|
||||||
|
_error = null;
|
||||||
|
_loading = false;
|
||||||
|
_positionStyle = "";
|
||||||
|
_mouseOverModal = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (HelpKey == _lastKey && _helpHtml != null)
|
||||||
|
{
|
||||||
|
await PositionUnderAnchorAsync();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_lastKey = HelpKey;
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
_helpHtml = null;
|
||||||
|
_positionStyle = "visibility: hidden;"; // avoid flash before position is set
|
||||||
|
StateHasChanged();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var http = HttpFactory.CreateClient(ServiceCollectionExtensions.DnsmasqApiClientName);
|
||||||
|
var response = await http.GetAsync($"option-help/{HelpKey}.html");
|
||||||
|
if (response.IsSuccessStatusCode)
|
||||||
|
_helpHtml = await response.Content.ReadAsStringAsync();
|
||||||
|
else
|
||||||
|
_error = "Help not available for this option.";
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
_error = "Could not load help.";
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_loading = false;
|
||||||
|
await PositionUnderAnchorAsync();
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task PositionUnderAnchorAsync()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(AnchorId) || _jsModule == null) return;
|
||||||
|
var rect = await _jsModule.InvokeAsyncSafe<BoundingRect?>("getAnchorRect", AnchorId);
|
||||||
|
if (rect is { } r)
|
||||||
|
{
|
||||||
|
var gap = 4;
|
||||||
|
var topPx = r.Bottom + gap;
|
||||||
|
var leftPx = r.Left;
|
||||||
|
_positionStyle = $"position: fixed; top: {topPx}px; left: {leftPx}px; visibility: visible;";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_positionStyle = "visibility: visible;";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnModalMouseEnter()
|
||||||
|
{
|
||||||
|
_mouseOverModal = true;
|
||||||
|
await OnMouseEnterModal.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnModalMouseLeave()
|
||||||
|
{
|
||||||
|
_mouseOverModal = false;
|
||||||
|
await OnMouseLeaveModal.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record BoundingRect(
|
||||||
|
[property: JsonPropertyName("top")] double Top,
|
||||||
|
[property: JsonPropertyName("left")] double Left,
|
||||||
|
[property: JsonPropertyName("bottom")] double Bottom,
|
||||||
|
[property: JsonPropertyName("width")] double Width,
|
||||||
|
[property: JsonPropertyName("height")] double Height);
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
/* Popover anchored under the label (position set in code from anchor rect) */
|
||||||
|
.config-option-help-popover {
|
||||||
|
position: fixed;
|
||||||
|
z-index: 1060;
|
||||||
|
max-width: min(420px, calc(100vw - 1rem));
|
||||||
|
max-height: min(70vh, 400px);
|
||||||
|
overflow: auto;
|
||||||
|
border: 1px solid var(--bs-border-color, #dee2e6);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
|
||||||
|
background: var(--bs-body-bg, #fff);
|
||||||
|
}
|
||||||
|
|
||||||
|
.config-option-help-popover-content {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.config-option-help-popover-header {
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border-bottom: 1px solid var(--bs-border-color-translucent, rgba(0, 0, 0, 0.075));
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.config-option-help-popover-title {
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.config-option-help-popover-body {
|
||||||
|
padding: 0.75rem;
|
||||||
|
overflow: auto;
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Option help content: man-page fragments (dt/dd, b, p, a) */
|
||||||
|
.config-option-help-popover-body .option-help dt {
|
||||||
|
font-weight: 600;
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
.config-option-help-popover-body .option-help dt:first-child {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
.config-option-help-popover-body .option-help dd {
|
||||||
|
margin-left: 0;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
padding-left: 0.75rem;
|
||||||
|
border-left: 2px solid var(--bs-border-color-translucent, rgba(0, 0, 0, 0.1));
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.config-option-help-popover-body .option-help dd p {
|
||||||
|
margin-bottom: 0.35rem;
|
||||||
|
}
|
||||||
|
.config-option-help-popover-body .option-help dd p:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
.config-option-help-popover-body .option-help b {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.config-option-help-popover-body .option-help a {
|
||||||
|
color: var(--bs-link-color, #0d6efd);
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Services.EffectiveConfig.Abstractions
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Services.UI.Notifications.Abstractions
|
||||||
|
@inject IEffectiveConfigSaveService SaveService
|
||||||
|
@inject INotificationService NotificationService
|
||||||
|
|
||||||
|
@if (ShowModal)
|
||||||
|
{
|
||||||
|
<EffectiveConfigSaveModal
|
||||||
|
PendingChanges="@PendingChanges"
|
||||||
|
Status="@Status"
|
||||||
|
Session="@Session"
|
||||||
|
SaveState="@_saveState"
|
||||||
|
SaveResult="@_saveResult"
|
||||||
|
RestoreResult="@_restoreResult"
|
||||||
|
OnClose="@OnClose"
|
||||||
|
OnSave="@HandleSave"
|
||||||
|
OnRestore="@HandleRestore"
|
||||||
|
OnReverted="@HandleReverted"
|
||||||
|
OnCloseAndEndEdit="@OnCloseAndEndEdit" />
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
public enum SaveUiState
|
||||||
|
{
|
||||||
|
Review,
|
||||||
|
Saving,
|
||||||
|
WriteFailed,
|
||||||
|
ValidateFailed,
|
||||||
|
ReloadFailed,
|
||||||
|
RestoreInProgress,
|
||||||
|
RestoreFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
[Parameter] public bool ShowModal { get; set; }
|
||||||
|
[Parameter] public IReadOnlyList<PendingEffectiveConfigChange> PendingChanges { get; set; } = null!;
|
||||||
|
[Parameter] public DnsmasqServiceStatus? Status { get; set; }
|
||||||
|
[Parameter] public EventCallback OnClose { get; set; }
|
||||||
|
[Parameter] public EventCallback OnSaveCompleted { get; set; }
|
||||||
|
[Parameter] public EventCallback OnCloseAndEndEdit { get; set; }
|
||||||
|
[Parameter] public IEffectiveConfigEditSession Session { get; set; } = null!;
|
||||||
|
|
||||||
|
private SaveUiState _saveState = SaveUiState.Review;
|
||||||
|
private EffectiveConfigSaveResult? _saveResult;
|
||||||
|
private EffectiveConfigRestoreResult? _restoreResult;
|
||||||
|
|
||||||
|
protected override void OnParametersSet()
|
||||||
|
{
|
||||||
|
if (!ShowModal)
|
||||||
|
{
|
||||||
|
_saveState = SaveUiState.Review;
|
||||||
|
_saveResult = null;
|
||||||
|
_restoreResult = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleReverted()
|
||||||
|
{
|
||||||
|
await InvokeAsync(StateHasChanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleSave()
|
||||||
|
{
|
||||||
|
if (Session.PendingChanges.Count == 0) return;
|
||||||
|
|
||||||
|
_saveState = SaveUiState.Saving;
|
||||||
|
_saveResult = null;
|
||||||
|
_restoreResult = null;
|
||||||
|
await InvokeAsync(StateHasChanged);
|
||||||
|
|
||||||
|
var result = await Session.ApplyAsync();
|
||||||
|
|
||||||
|
_saveResult = result;
|
||||||
|
if (result.Saved && result.Restarted)
|
||||||
|
{
|
||||||
|
var message = result.UserMessage ?? "Config saved and dnsmasq restarted.";
|
||||||
|
NotificationService.ShowSuccess(message);
|
||||||
|
_saveState = SaveUiState.Review;
|
||||||
|
_saveResult = null;
|
||||||
|
await OnClose.InvokeAsync();
|
||||||
|
await OnSaveCompleted.InvokeAsync();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.Saved && result.IsValidateFailed)
|
||||||
|
_saveState = SaveUiState.ValidateFailed;
|
||||||
|
else if (result.Saved && !result.Restarted)
|
||||||
|
_saveState = SaveUiState.ReloadFailed;
|
||||||
|
else if (!result.Saved)
|
||||||
|
_saveState = SaveUiState.WriteFailed;
|
||||||
|
else
|
||||||
|
_saveState = SaveUiState.Review;
|
||||||
|
|
||||||
|
await InvokeAsync(StateHasChanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleRestore(string backupPath)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(backupPath)) return;
|
||||||
|
|
||||||
|
_saveState = SaveUiState.RestoreInProgress;
|
||||||
|
_restoreResult = null;
|
||||||
|
await InvokeAsync(StateHasChanged);
|
||||||
|
|
||||||
|
var result = await SaveService.RestoreAsync(backupPath);
|
||||||
|
|
||||||
|
_restoreResult = result;
|
||||||
|
if (result.Restored && result.Restarted)
|
||||||
|
{
|
||||||
|
var message = result.UserMessage ?? "Backup restored and dnsmasq restarted.";
|
||||||
|
NotificationService.ShowSuccess(message);
|
||||||
|
_saveState = SaveUiState.Review;
|
||||||
|
_saveResult = null;
|
||||||
|
_restoreResult = null;
|
||||||
|
await OnClose.InvokeAsync();
|
||||||
|
await OnSaveCompleted.InvokeAsync();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_saveState = SaveUiState.RestoreFailed;
|
||||||
|
await InvokeAsync(StateHasChanged);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Services.EffectiveConfig.Abstractions
|
||||||
|
|
||||||
|
<div class="modal fade show" style="display: block;" tabindex="-1" role="dialog" aria-labelledby="ec-save-modal-title" aria-modal="true">
|
||||||
|
<div class="modal-dialog modal-dialog-scrollable" role="document">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h5 class="modal-title" id="ec-save-modal-title">Save effective config changes</h5>
|
||||||
|
<button type="button" class="btn-close" @onclick="Close" aria-label="Close" disabled="@(SaveState == EffectiveConfigSaveFlow.SaveUiState.Saving || SaveState == EffectiveConfigSaveFlow.SaveUiState.RestoreInProgress)"></button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body ec-save-modal-body">
|
||||||
|
@if (SaveState == EffectiveConfigSaveFlow.SaveUiState.Saving || SaveState == EffectiveConfigSaveFlow.SaveUiState.RestoreInProgress)
|
||||||
|
{
|
||||||
|
<div class="ec-save-modal-loading text-center py-4">
|
||||||
|
<div class="spinner-border text-primary" role="status" aria-hidden="true"></div>
|
||||||
|
<p class="text-muted mt-2 mb-0">@(SaveState == EffectiveConfigSaveFlow.SaveUiState.Saving ? "Saving, validating and restarting…" : "Restoring backup and restarting…")</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else if (SaveState == EffectiveConfigSaveFlow.SaveUiState.ValidateFailed && SaveResult != null)
|
||||||
|
{
|
||||||
|
<div class="ec-save-modal-reload-failed">
|
||||||
|
<div class="alert alert-danger mb-3 d-flex align-items-center gap-2 ec-save-modal-alert">
|
||||||
|
<i class="bi bi-exclamation-triangle-fill ec-save-modal-alert-icon" aria-hidden="true"></i>
|
||||||
|
<div class="ec-save-modal-alert-text">
|
||||||
|
<strong>Config was saved, but validation failed.</strong> Restart was not attempted. You can restore the backup or keep editing.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
@if (SaveResult.BackupPath != null)
|
||||||
|
{
|
||||||
|
<p class="ec-save-modal-backup-path mb-2">
|
||||||
|
<span class="text-muted">Backup:</span> <code class="small ec-save-modal-backup-code">@SaveResult.BackupPath</code>
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
<div class="ec-save-modal-stderr mb-3">
|
||||||
|
<p class="text-muted small mb-1"><strong>Validation output</strong></p>
|
||||||
|
<pre class="ec-save-modal-pre border rounded p-2 bg-light small mb-0 text-body">@GetValidationFailedOutput(SaveResult)</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else if (SaveState == EffectiveConfigSaveFlow.SaveUiState.WriteFailed && SaveResult != null)
|
||||||
|
{
|
||||||
|
<div class="alert alert-danger mb-0">
|
||||||
|
<strong>Save failed.</strong> @SaveResult.UserMessage
|
||||||
|
@if (!string.IsNullOrEmpty(SaveResult.RestartStdErr))
|
||||||
|
{
|
||||||
|
<pre class="ec-save-modal-pre border rounded p-2 bg-light small mt-2 mb-0">@SaveResult.RestartStdErr</pre>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else if (SaveState == EffectiveConfigSaveFlow.SaveUiState.ReloadFailed && SaveResult != null)
|
||||||
|
{
|
||||||
|
<div class="ec-save-modal-reload-failed">
|
||||||
|
<div class="alert alert-danger mb-3 d-flex align-items-center gap-2 ec-save-modal-alert">
|
||||||
|
<i class="bi bi-exclamation-triangle-fill ec-save-modal-alert-icon" aria-hidden="true"></i>
|
||||||
|
<div class="ec-save-modal-alert-text">
|
||||||
|
<strong>Config was saved, but the restart command failed.</strong> You can restore the backup or keep editing.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
@if (SaveResult.BackupPath != null)
|
||||||
|
{
|
||||||
|
<p class="ec-save-modal-backup-path mb-2">
|
||||||
|
<span class="text-muted">Backup:</span> <code class="small ec-save-modal-backup-code">@SaveResult.BackupPath</code>
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
<div class="ec-save-modal-stderr mb-3">
|
||||||
|
<p class="text-muted small mb-1"><strong>Command output</strong></p>
|
||||||
|
<pre class="ec-save-modal-pre border rounded p-2 bg-light small mb-0 text-body">@GetRestartFailedOutput(SaveResult)</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else if (SaveState == EffectiveConfigSaveFlow.SaveUiState.RestoreFailed && RestoreResult != null)
|
||||||
|
{
|
||||||
|
<div class="ec-save-modal-restore-failed">
|
||||||
|
<div class="alert alert-danger mb-3 d-flex align-items-center gap-2 ec-save-modal-alert">
|
||||||
|
<i class="bi bi-exclamation-triangle-fill ec-save-modal-alert-icon" aria-hidden="true"></i>
|
||||||
|
<div class="ec-save-modal-alert-text">@RestoreResult.UserMessage</div>
|
||||||
|
</div>
|
||||||
|
<div class="ec-save-modal-stderr mb-3">
|
||||||
|
<p class="text-muted small mb-1"><strong>Command output</strong></p>
|
||||||
|
<pre class="ec-save-modal-pre border rounded p-2 bg-light small mb-0 text-body">@GetRestoreFailedOutput(RestoreResult)</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="text-muted mb-3">These changes will be written to your config. Remove any you don't want to keep.</p>
|
||||||
|
@if (ManagedFilePath != null)
|
||||||
|
{
|
||||||
|
<p class="ec-save-modal-target mb-3">
|
||||||
|
<span class="text-muted">Target file:</span> <code class="small">@ManagedFilePath</code>
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
@if (PendingChanges.Count == 0)
|
||||||
|
{
|
||||||
|
<div class="ec-save-modal-empty alert alert-light border text-center text-muted py-4 mb-0">
|
||||||
|
No pending changes. Close to continue editing.
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="ec-save-modal-changes list-group list-group-flush">
|
||||||
|
@foreach (var c in PendingChanges)
|
||||||
|
{
|
||||||
|
var change = c;
|
||||||
|
var oldList = AsStringList(change.OldValue);
|
||||||
|
var newList = AsStringList(change.NewValue);
|
||||||
|
var isMultiValue = oldList != null || newList != null;
|
||||||
|
<div class="list-group-item ec-save-modal-item d-flex align-items-start gap-3 py-3 px-0 border-0 border-bottom">
|
||||||
|
<div class="ec-save-modal-item-body flex-grow-1 min-width-0">
|
||||||
|
<div class="d-flex align-items-center gap-2">
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.NeutralPill" Text="@change.OptionName" Class="ec-save-modal-option me-2" />
|
||||||
|
@if (!isMultiValue)
|
||||||
|
{
|
||||||
|
<span class="ec-save-modal-diff text-body">
|
||||||
|
<span class="text-muted text-decoration-line-through">@FormatValue(change.OldValue)</span>
|
||||||
|
<span class="text-muted mx-1" aria-hidden="true">→</span>
|
||||||
|
<span>@FormatValue(change.NewValue)</span>
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (isMultiValue)
|
||||||
|
{
|
||||||
|
var added = (newList ?? Array.Empty<string>()).Except(oldList ?? Array.Empty<string>()).ToList();
|
||||||
|
var removed = (oldList ?? Array.Empty<string>()).Except(newList ?? Array.Empty<string>()).ToList();
|
||||||
|
<div class="ec-save-modal-multidiff ps-3 mt-1 small">
|
||||||
|
@foreach (var val in removed)
|
||||||
|
{
|
||||||
|
<div class="text-muted text-decoration-line-through">− @val</div>
|
||||||
|
}
|
||||||
|
@foreach (var val in added)
|
||||||
|
{
|
||||||
|
<div class="text-success">+ @val</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (change.CurrentSourceFilePath != null)
|
||||||
|
{
|
||||||
|
<div class="ec-save-modal-override small text-muted mt-1">Overrides @System.IO.Path.GetFileName(change.CurrentSourceFilePath)</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<button type="button" class="btn btn-sm btn-outline-danger flex-shrink-0" @onclick="() => Revert(change)" title="Revert this change" aria-label="Revert @change.OptionName">
|
||||||
|
<i class="bi bi-arrow-counterclockwise me-1" aria-hidden="true"></i>Revert
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer ec-save-modal-footer">
|
||||||
|
@if ((SaveState == EffectiveConfigSaveFlow.SaveUiState.ReloadFailed || SaveState == EffectiveConfigSaveFlow.SaveUiState.ValidateFailed) && SaveResult?.BackupPath != null)
|
||||||
|
{
|
||||||
|
<button type="button" class="btn btn-primary" @onclick="() => Restore(SaveResult.BackupPath)"><i class="bi bi-arrow-counterclockwise me-1" aria-hidden="true"></i>Restore backup</button>
|
||||||
|
<button type="button" class="btn btn-outline-warning" @onclick="Close"><i class="bi bi-pencil me-1" aria-hidden="true"></i>Continue editing</button>
|
||||||
|
<button type="button" class="btn btn-danger" @onclick="CloseAndEndEdit"><i class="bi bi-x-circle me-1" aria-hidden="true"></i>Stop editing</button>
|
||||||
|
}
|
||||||
|
else if (SaveState == EffectiveConfigSaveFlow.SaveUiState.RestoreFailed)
|
||||||
|
{
|
||||||
|
<button type="button" class="btn btn-outline-warning" @onclick="Close"><i class="bi bi-pencil me-1" aria-hidden="true"></i>Continue editing</button>
|
||||||
|
<button type="button" class="btn btn-danger" @onclick="CloseAndEndEdit"><i class="bi bi-x-circle me-1" aria-hidden="true"></i>Stop editing</button>
|
||||||
|
}
|
||||||
|
else if (SaveState == EffectiveConfigSaveFlow.SaveUiState.WriteFailed)
|
||||||
|
{
|
||||||
|
<button type="button" class="btn btn-outline-warning" @onclick="Close"><i class="bi bi-pencil me-1" aria-hidden="true"></i>Continue editing</button>
|
||||||
|
}
|
||||||
|
else if (SaveState != EffectiveConfigSaveFlow.SaveUiState.Saving && SaveState != EffectiveConfigSaveFlow.SaveUiState.RestoreInProgress)
|
||||||
|
{
|
||||||
|
<button type="button" class="btn btn-secondary" @onclick="Close"><i class="bi bi-x me-1" aria-hidden="true"></i>Cancel</button>
|
||||||
|
<button type="button" class="btn btn-primary" @onclick="Save" disabled="@(PendingChanges.Count == 0)"><i class="bi bi-floppy-fill me-1" aria-hidden="true"></i>Save</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="modal-backdrop fade show" style="display: block;" @onclick="OnBackdropClick"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public IReadOnlyList<PendingEffectiveConfigChange> PendingChanges { get; set; } = null!;
|
||||||
|
[Parameter] public DnsmasqServiceStatus? Status { get; set; }
|
||||||
|
[Parameter] public IEffectiveConfigEditSession Session { get; set; } = null!;
|
||||||
|
[Parameter] public EffectiveConfigSaveFlow.SaveUiState SaveState { get; set; }
|
||||||
|
[Parameter] public EffectiveConfigSaveResult? SaveResult { get; set; }
|
||||||
|
[Parameter] public EffectiveConfigRestoreResult? RestoreResult { get; set; }
|
||||||
|
[Parameter] public EventCallback OnClose { get; set; }
|
||||||
|
[Parameter] public EventCallback OnSave { get; set; }
|
||||||
|
[Parameter] public EventCallback<string> OnRestore { get; set; }
|
||||||
|
[Parameter] public EventCallback OnReverted { get; set; }
|
||||||
|
[Parameter] public EventCallback OnCloseAndEndEdit { get; set; }
|
||||||
|
|
||||||
|
private bool AllowClose => SaveState != EffectiveConfigSaveFlow.SaveUiState.Saving && SaveState != EffectiveConfigSaveFlow.SaveUiState.RestoreInProgress;
|
||||||
|
|
||||||
|
private string? ManagedFilePath => Status?.ManagedFilePath;
|
||||||
|
|
||||||
|
private static string GetValidationFailedOutput(EffectiveConfigSaveResult result)
|
||||||
|
{
|
||||||
|
var err = (result.ValidationStdErr ?? "").Trim();
|
||||||
|
var outp = (result.ValidationStdOut ?? "").Trim();
|
||||||
|
if (err.Length > 0 && outp.Length > 0)
|
||||||
|
return err + "\n\n" + outp;
|
||||||
|
if (err.Length > 0) return err;
|
||||||
|
if (outp.Length > 0) return outp;
|
||||||
|
var exitInfo = result.ValidationExitCode >= 0 ? $"Exit code: {result.ValidationExitCode}." : "";
|
||||||
|
return string.IsNullOrEmpty(exitInfo) ? "(No output captured)" : exitInfo + " (No output captured)";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GetRestartFailedOutput(EffectiveConfigSaveResult result)
|
||||||
|
{
|
||||||
|
var err = (result.RestartStdErr ?? "").Trim();
|
||||||
|
var outp = (result.RestartStdOut ?? "").Trim();
|
||||||
|
if (err.Length > 0 && outp.Length > 0)
|
||||||
|
return err + "\n\n" + outp;
|
||||||
|
if (err.Length > 0) return err;
|
||||||
|
if (outp.Length > 0) return outp;
|
||||||
|
var exitInfo = result.RestartExitCode >= 0 ? $"Exit code: {result.RestartExitCode}." : "";
|
||||||
|
return string.IsNullOrEmpty(exitInfo) ? "(No output captured)" : exitInfo + " (No output captured)";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GetRestoreFailedOutput(EffectiveConfigRestoreResult result)
|
||||||
|
{
|
||||||
|
var err = (result.RestartStdErr ?? "").Trim();
|
||||||
|
if (err.Length > 0) return err;
|
||||||
|
var exitInfo = result.RestartExitCode >= 0 ? $"Exit code: {result.RestartExitCode}." : "";
|
||||||
|
return string.IsNullOrEmpty(exitInfo) ? "(No output captured)" : exitInfo + " (No output captured)";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>If the value is a list of strings (multi-value option), return it; otherwise null.</summary>
|
||||||
|
private static IReadOnlyList<string>? AsStringList(object? v)
|
||||||
|
{
|
||||||
|
if (v == null) return null;
|
||||||
|
if (v is IReadOnlyList<string> ro) return ro;
|
||||||
|
if (v is List<string> list) return list;
|
||||||
|
if (v is string[] arr) return arr;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FormatValue(object? v)
|
||||||
|
{
|
||||||
|
if (v == null) return "(not set)";
|
||||||
|
if (v is bool b) return b ? "on" : "off";
|
||||||
|
var list = AsStringList(v);
|
||||||
|
if (list != null) return list.Count == 0 ? "(none)" : string.Join(", ", list);
|
||||||
|
return v.ToString() ?? "(not set)";
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Revert(PendingEffectiveConfigChange change)
|
||||||
|
{
|
||||||
|
Session.RevertChange(change.SectionId, change.OptionName);
|
||||||
|
await OnReverted.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnBackdropClick()
|
||||||
|
{
|
||||||
|
if (!AllowClose) return;
|
||||||
|
await Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Close()
|
||||||
|
{
|
||||||
|
if (!AllowClose) return;
|
||||||
|
await OnClose.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Save()
|
||||||
|
{
|
||||||
|
await OnSave.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Restore(string backupPath)
|
||||||
|
{
|
||||||
|
await OnRestore.InvokeAsync(backupPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task CloseAndEndEdit()
|
||||||
|
{
|
||||||
|
if (!AllowClose) return;
|
||||||
|
await OnCloseAndEndEdit.InvokeAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
/* Keep footer buttons on one line */
|
||||||
|
.ec-save-modal-footer {
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Ensure the dialog stacks above the backdrop when both are siblings inside .modal */
|
||||||
|
.modal-dialog {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1056;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-backdrop {
|
||||||
|
z-index: 1050;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-body {
|
||||||
|
padding-top: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-target {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-changes {
|
||||||
|
margin: 0 -1rem;
|
||||||
|
padding: 0 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-item:last-child {
|
||||||
|
border-bottom: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-option {
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-diff {
|
||||||
|
font-size: 0.9375rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-override {
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-empty {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-loading {
|
||||||
|
min-height: 6rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-backup-path {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-backup-code {
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Command output: ensure text is always visible (avoid inherited color/visibility issues) */
|
||||||
|
.ec-save-modal-pre {
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
max-height: 12rem;
|
||||||
|
overflow: auto;
|
||||||
|
color: var(--bs-body-color, #212529);
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
min-height: 2.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Alert icon in reload/restore failed states: larger, spacing, aligned with text */
|
||||||
|
.ec-save-modal-alert {
|
||||||
|
--ec-save-modal-alert-icon-gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-alert-icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
margin-right: var(--ec-save-modal-alert-icon-gap);
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-save-modal-alert-text {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
|
||||||
|
<ConfigOptionHelpModal HelpKey="@HelpKey" AnchorId="@AnchorId" Visible="@Visible" Title="@Title"
|
||||||
|
OnClose="RequestClose" OnMouseEnterModal="CancelCloseTimer" OnMouseLeaveModal="ScheduleClose" />
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public bool Visible { get; set; }
|
||||||
|
[Parameter] public string? HelpKey { get; set; }
|
||||||
|
[Parameter] public string? AnchorId { get; set; }
|
||||||
|
[Parameter] public string Title { get; set; } = "Option help";
|
||||||
|
[Parameter] public EventCallback OnCloseRequested { get; set; }
|
||||||
|
|
||||||
|
private CancellationTokenSource? _closeCts;
|
||||||
|
|
||||||
|
private void CancelCloseTimer()
|
||||||
|
{
|
||||||
|
_closeCts?.Cancel();
|
||||||
|
_closeCts = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ScheduleClose()
|
||||||
|
{
|
||||||
|
_closeCts?.Cancel();
|
||||||
|
_closeCts = new CancellationTokenSource();
|
||||||
|
var token = _closeCts.Token;
|
||||||
|
_ = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
try { await Task.Delay(300, token); }
|
||||||
|
catch (OperationCanceledException) { return; }
|
||||||
|
await InvokeAsync(async () =>
|
||||||
|
{
|
||||||
|
if (token.IsCancellationRequested) return;
|
||||||
|
_closeCts = null;
|
||||||
|
await OnCloseRequested.InvokeAsync();
|
||||||
|
});
|
||||||
|
}, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RequestClose()
|
||||||
|
{
|
||||||
|
CancelCloseTimer();
|
||||||
|
await OnCloseRequested.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Called by the section when the label loses mouse (so we schedule close; if user moves to modal, OnMouseEnterModal cancels).</summary>
|
||||||
|
public void ScheduleCloseFromLabelLeave()
|
||||||
|
{
|
||||||
|
ScheduleClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Called when opening or switching help (e.g. user clicked another label); cancels any pending 300ms close so the timer from a previous label leave does not dismiss the new help.</summary>
|
||||||
|
public void CancelCloseFromLabelEnter()
|
||||||
|
{
|
||||||
|
CancelCloseTimer();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
|
||||||
|
<span id="@AnchorId" class="@EffectiveCssClass" title="@Title" @onclick="OnClick" @onmouseleave="OnMouseLeave">
|
||||||
|
@ChildContent
|
||||||
|
</span>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public string AnchorId { get; set; } = "";
|
||||||
|
[Parameter] public string? HelpKey { get; set; }
|
||||||
|
[Parameter] public string OptionLabel { get; set; } = "";
|
||||||
|
[Parameter] public string? CssClass { get; set; }
|
||||||
|
|
||||||
|
private string EffectiveCssClass =>
|
||||||
|
CssClass ?? (!string.IsNullOrEmpty(HelpKey) ? "ec-field-label ec-field-label-help" : "ec-field-label");
|
||||||
|
[Parameter] public string? Title { get; set; }
|
||||||
|
[CascadingParameter] public EffectiveConfigUiContext? Ui { get; set; }
|
||||||
|
[Parameter] public RenderFragment? ChildContent { get; set; }
|
||||||
|
|
||||||
|
private Task OnClick()
|
||||||
|
{
|
||||||
|
if (Ui == null || string.IsNullOrEmpty(HelpKey)) return Task.CompletedTask;
|
||||||
|
return Ui.RequestOptionHelpAsync(new ConfigOptionHelpRequestEventArgs
|
||||||
|
{
|
||||||
|
HelpKey = HelpKey,
|
||||||
|
OptionLabel = OptionLabel,
|
||||||
|
AnchorId = AnchorId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task OnMouseLeave()
|
||||||
|
{
|
||||||
|
if (Ui == null) return Task.CompletedTask;
|
||||||
|
return Ui.RequestOptionHelpAsync(new ConfigOptionHelpRequestEventArgs
|
||||||
|
{
|
||||||
|
AnchorId = AnchorId,
|
||||||
|
IsLabelMouseLeave = true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
|
||||||
|
@if (Source?.IsReadOnly == true)
|
||||||
|
{
|
||||||
|
var readonlyTitle = !string.IsNullOrEmpty(ReadonlyTitleOverride) ? ReadonlyTitleOverride : Source?.GetReadOnlyTooltip();
|
||||||
|
if (ReadonlyClickActivatesField && Ui != null && !string.IsNullOrEmpty(FieldKey))
|
||||||
|
{
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.ReadOnly" Text="readonly" Clickable="true"
|
||||||
|
Id="@AnchorId" Title="@readonlyTitle"
|
||||||
|
OnClick="OnEditableClick"
|
||||||
|
Class="status-badge-inline" />
|
||||||
|
}
|
||||||
|
else if (IsInteractive && Ui != null)
|
||||||
|
{
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.ReadOnly" Text="readonly" Clickable="true"
|
||||||
|
Id="@AnchorId" Title="@readonlyTitle"
|
||||||
|
OnClick="OnReadonlyClick" OnMouseLeave="OnReadonlyMouseLeave"
|
||||||
|
Class="status-badge-inline" />
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.ReadOnly" Text="readonly"
|
||||||
|
Title="@readonlyTitle"
|
||||||
|
Class="status-badge-inline" />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (ShowEditableBadge)
|
||||||
|
{
|
||||||
|
@if (EditableAsButton)
|
||||||
|
{
|
||||||
|
@if (IsActiveEditor)
|
||||||
|
{
|
||||||
|
<span class="status-badge-inline">
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.ActionOk" Text="ok" Clickable="true"
|
||||||
|
Title="Apply this field change" AriaLabel="Apply change"
|
||||||
|
PreventBlurOnMouseDown="true" OnClick="OnConfirmClick" />
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.ActionCancel" Text="cancel" Clickable="true"
|
||||||
|
Title="Discard in-progress edits for this field" AriaLabel="Cancel edit"
|
||||||
|
PreventBlurOnMouseDown="true" OnClick="OnCancelClick" />
|
||||||
|
@if (HasPendingChange)
|
||||||
|
{
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.ActionRevert" Text="revert" Clickable="true"
|
||||||
|
Title="Remove this field from pending changes" AriaLabel="Revert pending change"
|
||||||
|
PreventBlurOnMouseDown="true" OnClick="OnRevertClick" />
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<StatusBadge Kind="@(HasPendingChange ? StatusBadgeKind.Pending : StatusBadgeKind.Editable)"
|
||||||
|
Text="@(HasPendingChange ? "pending" : "editable")"
|
||||||
|
Clickable="true"
|
||||||
|
Title="@(HasPendingChange ? "Pending change" : "Edit this field")"
|
||||||
|
AriaLabel="Edit"
|
||||||
|
OnClick="OnEditableClick"
|
||||||
|
Class="status-badge-inline" />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<StatusBadge Kind="StatusBadgeKind.Editable" Text="editable"
|
||||||
|
Class="status-badge-inline" />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public string AnchorId { get; set; } = "";
|
||||||
|
[Parameter] public ConfigValueSource? Source { get; set; }
|
||||||
|
[Parameter] public string OptionName { get; set; } = "";
|
||||||
|
[Parameter] public object? Value { get; set; }
|
||||||
|
[Parameter] public bool IsInteractive { get; set; }
|
||||||
|
[Parameter] public bool ShowEditableBadge { get; set; }
|
||||||
|
[Parameter] public bool HasPendingChange { get; set; }
|
||||||
|
[Parameter] public bool EditableAsButton { get; set; } = true;
|
||||||
|
[Parameter] public bool IsActiveEditor { get; set; }
|
||||||
|
[Parameter] public EventCallback OnConfirmRequested { get; set; }
|
||||||
|
[Parameter] public EventCallback OnCancelRequested { get; set; }
|
||||||
|
[Parameter] public EventCallback OnRevertRequested { get; set; }
|
||||||
|
[Parameter] public string? FieldKey { get; set; }
|
||||||
|
/// <summary>Optional: when set, editable-badge click invokes this instead of activating the field by key (e.g. list editor per-item edit).</summary>
|
||||||
|
[Parameter] public EventCallback OnEditableClickRequested { get; set; }
|
||||||
|
/// <summary>When true, readonly badge click activates the field for editing instead of showing the readonly popover (e.g. for multi-value where new items can still be added).</summary>
|
||||||
|
[Parameter] public bool ReadonlyClickActivatesField { get; set; }
|
||||||
|
/// <summary>Optional tooltip for readonly badge when <see cref="ReadonlyClickActivatesField"/> is true (e.g. "New values can still be added. Click to edit.").</summary>
|
||||||
|
[Parameter] public string? ReadonlyTitleOverride { get; set; }
|
||||||
|
[CascadingParameter] public EffectiveConfigUiContext? Ui { get; set; }
|
||||||
|
|
||||||
|
private async Task OnConfirmClick()
|
||||||
|
{
|
||||||
|
if (OnConfirmRequested.HasDelegate)
|
||||||
|
await OnConfirmRequested.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnCancelClick()
|
||||||
|
{
|
||||||
|
if (OnCancelRequested.HasDelegate)
|
||||||
|
await OnCancelRequested.InvokeAsync();
|
||||||
|
else if (Ui != null)
|
||||||
|
await Ui.DeactivateFieldAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnRevertClick()
|
||||||
|
{
|
||||||
|
if (OnRevertRequested.HasDelegate)
|
||||||
|
await OnRevertRequested.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnEditableClick()
|
||||||
|
{
|
||||||
|
if (OnEditableClickRequested.HasDelegate)
|
||||||
|
{
|
||||||
|
await OnEditableClickRequested.InvokeAsync();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (Ui != null && !string.IsNullOrEmpty(FieldKey))
|
||||||
|
await Ui.ActivateFieldAsync(FieldKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task OnReadonlyClick()
|
||||||
|
{
|
||||||
|
if (Ui == null || Source == null) return Task.CompletedTask;
|
||||||
|
return Ui.RequestReadonlyPopoverAsync(new ReadonlyBadgeClickedEventArgs(AnchorId, Source, OptionName, Value));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task OnReadonlyMouseLeave()
|
||||||
|
{
|
||||||
|
if (Ui == null) return Task.CompletedTask;
|
||||||
|
return Ui.ScheduleReadonlyPopoverCloseAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Helpers.Config
|
||||||
|
|
||||||
|
@if (Source is { IsReadOnly: true })
|
||||||
|
{
|
||||||
|
<div class="ec-readonly-hint small text-muted mt-1">
|
||||||
|
<span class="d-block">@ReadonlyConfigCommandGenerator.GetEditFileHint(Source)</span>
|
||||||
|
@if (!string.IsNullOrEmpty(_removeCommand))
|
||||||
|
{
|
||||||
|
<div class="mt-1">
|
||||||
|
<CopyableCodeLine Text="@_removeCommand" CssClass="small" CodeCssClass="small text-break" CopyTitle="Copy command" />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (!string.IsNullOrEmpty(_overrideLine))
|
||||||
|
{
|
||||||
|
<span class="d-block mt-1">@ReadonlyConfigCommandGenerator.GetOverrideHint(OptionName, Value, ManagedFilePath)</span>
|
||||||
|
<div class="mt-1">
|
||||||
|
<CopyableCodeLine Text="@_overrideLine" CodeCssClass="small" CopyTitle="Copy line" />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public ConfigValueSource? Source { get; set; }
|
||||||
|
[Parameter] public string OptionName { get; set; } = "";
|
||||||
|
[Parameter] public object? Value { get; set; }
|
||||||
|
[Parameter] public string? ManagedFilePath { get; set; }
|
||||||
|
|
||||||
|
private string _removeCommand = "";
|
||||||
|
private string _overrideLine = "";
|
||||||
|
|
||||||
|
protected override void OnParametersSet()
|
||||||
|
{
|
||||||
|
if (Source is { IsReadOnly: true })
|
||||||
|
{
|
||||||
|
_removeCommand = ReadonlyConfigCommandGenerator.GetRemoveLineCommand(Source, OptionName);
|
||||||
|
_overrideLine = ReadonlyConfigCommandGenerator.GetOverrideLine(OptionName, Value, ManagedFilePath);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_removeCommand = "";
|
||||||
|
_overrideLine = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Helpers.Config
|
||||||
|
@using DnsmasqWebUI.Extensions
|
||||||
|
@using Microsoft.AspNetCore.Components
|
||||||
|
@using Microsoft.JSInterop
|
||||||
|
@using System.Text.Json.Serialization
|
||||||
|
@inject IJSRuntime JSRuntime
|
||||||
|
@implements IAsyncDisposable
|
||||||
|
|
||||||
|
@if (Visible && Source != null)
|
||||||
|
{
|
||||||
|
<div class="ec-readonly-popover" id="@_popoverId" style="@_positionStyle" @onmouseenter="OnPopoverMouseEnter" @onmouseleave="OnPopoverMouseLeave">
|
||||||
|
<div class="ec-readonly-popover-content">
|
||||||
|
<div class="ec-readonly-popover-header">
|
||||||
|
<span class="ec-readonly-popover-title">Read-only: @OptionName</span>
|
||||||
|
</div>
|
||||||
|
<div class="ec-readonly-popover-body small">
|
||||||
|
<p class="text-muted mb-2">@ReadonlyConfigCommandGenerator.GetEditFileHint(Source)</p>
|
||||||
|
@if (!string.IsNullOrEmpty(_removeCommand))
|
||||||
|
{
|
||||||
|
<div class="mb-2">
|
||||||
|
<CopyableCodeLine Text="@_removeCommand" CodeCssClass="small" CopyTitle="Copy command" />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (!string.IsNullOrEmpty(_overrideLine))
|
||||||
|
{
|
||||||
|
<p class="text-muted mb-1">@ReadonlyConfigCommandGenerator.GetOverrideHint(OptionName, Value, ManagedFilePath)</p>
|
||||||
|
<CopyableCodeLine Text="@_overrideLine" CodeCssClass="small" CopyTitle="Copy line" />
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public bool Visible { get; set; }
|
||||||
|
[Parameter] public string? AnchorId { get; set; }
|
||||||
|
[Parameter] public ConfigValueSource? Source { get; set; }
|
||||||
|
[Parameter] public string OptionName { get; set; } = "";
|
||||||
|
[Parameter] public object? Value { get; set; }
|
||||||
|
[Parameter] public string? ManagedFilePath { get; set; }
|
||||||
|
[Parameter] public EventCallback OnClose { get; set; }
|
||||||
|
[Parameter] public EventCallback OnMouseEnterPopover { get; set; }
|
||||||
|
[Parameter] public EventCallback OnMouseLeavePopover { get; set; }
|
||||||
|
|
||||||
|
private const string HiddenPositionStyle = "position: fixed; z-index: 1060; left: 0; top: 0; visibility: hidden;";
|
||||||
|
private const string VisiblePositionStyleFormat = "position: fixed; top: {0}px; left: {1}px; visibility: visible;";
|
||||||
|
|
||||||
|
private string _positionStyle = "";
|
||||||
|
private readonly string _popoverId = "ec-readonly-popover-" + Guid.NewGuid().ToString("N")[..8];
|
||||||
|
private DotNetObjectReference<ReadonlyEditPopover>? _dotNetRef;
|
||||||
|
private bool _scrollListenerAdded;
|
||||||
|
private bool _mouseOverPopover;
|
||||||
|
private IJSObjectReference? _jsModule;
|
||||||
|
private bool _moduleLoaded;
|
||||||
|
private string _removeCommand = "";
|
||||||
|
private string _overrideLine = "";
|
||||||
|
|
||||||
|
protected override void OnParametersSet()
|
||||||
|
{
|
||||||
|
if (Source is { IsReadOnly: true })
|
||||||
|
{
|
||||||
|
_removeCommand = ReadonlyConfigCommandGenerator.GetRemoveLineCommand(Source, OptionName);
|
||||||
|
_overrideLine = ReadonlyConfigCommandGenerator.GetOverrideLine(OptionName, Value, ManagedFilePath);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_removeCommand = "";
|
||||||
|
_overrideLine = "";
|
||||||
|
}
|
||||||
|
if (Visible && string.IsNullOrEmpty(_positionStyle))
|
||||||
|
_positionStyle = HiddenPositionStyle;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||||
|
{
|
||||||
|
if (firstRender)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/config-option-help.js");
|
||||||
|
_moduleLoaded = true;
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException) { }
|
||||||
|
catch (JSDisconnectedException) { }
|
||||||
|
catch (JSException) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Visible && !_scrollListenerAdded && _moduleLoaded && _jsModule != null)
|
||||||
|
{
|
||||||
|
_scrollListenerAdded = true;
|
||||||
|
_dotNetRef = DotNetObjectReference.Create(this);
|
||||||
|
await _jsModule.InvokeVoidAsyncSafe("addScrollCloseListener", _dotNetRef);
|
||||||
|
}
|
||||||
|
else if (!Visible && _scrollListenerAdded && _jsModule != null)
|
||||||
|
{
|
||||||
|
_scrollListenerAdded = false;
|
||||||
|
await _jsModule.InvokeVoidAsyncSafe("removeScrollCloseListener");
|
||||||
|
_dotNetRef?.Dispose();
|
||||||
|
_dotNetRef = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Visible)
|
||||||
|
_positionStyle = "";
|
||||||
|
|
||||||
|
if (Visible && _moduleLoaded && _jsModule != null)
|
||||||
|
{
|
||||||
|
await PositionUnderAnchorAsync();
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[JSInvokable]
|
||||||
|
public async Task OnScrollClose()
|
||||||
|
{
|
||||||
|
await PositionUnderAnchorAsync();
|
||||||
|
StateHasChanged();
|
||||||
|
if (!_mouseOverPopover)
|
||||||
|
await OnClose.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
if (_scrollListenerAdded && _jsModule != null)
|
||||||
|
{
|
||||||
|
_scrollListenerAdded = false;
|
||||||
|
await _jsModule.InvokeVoidAsyncSafe("removeScrollCloseListener");
|
||||||
|
_dotNetRef?.Dispose();
|
||||||
|
_dotNetRef = null;
|
||||||
|
}
|
||||||
|
await _jsModule.DisposeAsyncSafe();
|
||||||
|
_jsModule = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task PositionUnderAnchorAsync()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(AnchorId) || _jsModule == null) return;
|
||||||
|
var rect = await _jsModule.InvokeAsyncSafe<BoundingRect?>("getAnchorRect", AnchorId);
|
||||||
|
if (rect is { } r)
|
||||||
|
{
|
||||||
|
var gap = 4;
|
||||||
|
var topPx = r.Bottom + gap;
|
||||||
|
var leftPx = r.Left;
|
||||||
|
_positionStyle = string.Format(VisiblePositionStyleFormat, topPx, leftPx);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_positionStyle = HiddenPositionStyle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnPopoverMouseEnter()
|
||||||
|
{
|
||||||
|
_mouseOverPopover = true;
|
||||||
|
await OnMouseEnterPopover.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnPopoverMouseLeave()
|
||||||
|
{
|
||||||
|
_mouseOverPopover = false;
|
||||||
|
await OnMouseLeavePopover.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record BoundingRect(
|
||||||
|
[property: JsonPropertyName("top")] double Top,
|
||||||
|
[property: JsonPropertyName("left")] double Left,
|
||||||
|
[property: JsonPropertyName("bottom")] double Bottom,
|
||||||
|
[property: JsonPropertyName("width")] double Width,
|
||||||
|
[property: JsonPropertyName("height")] double Height);
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
/* Readonly edit popover: anchored under the badge; same look as option help popover */
|
||||||
|
.ec-readonly-popover {
|
||||||
|
position: fixed;
|
||||||
|
z-index: 1060;
|
||||||
|
max-width: min(420px, calc(100vw - 1rem));
|
||||||
|
max-height: min(70vh, 400px);
|
||||||
|
overflow: auto;
|
||||||
|
border: 1px solid var(--bs-border-color, #dee2e6);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
|
||||||
|
background: var(--bs-body-bg, #fff);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-readonly-popover-content {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-readonly-popover-header {
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border-bottom: 1px solid var(--bs-border-color-translucent, rgba(0, 0, 0, 0.075));
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-readonly-popover-title {
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ec-readonly-popover-body {
|
||||||
|
padding: 0.75rem;
|
||||||
|
overflow: auto;
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
@namespace DnsmasqWebUI.Components.EffectiveConfig
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq
|
||||||
|
@using DnsmasqWebUI.Models.Dnsmasq.EffectiveConfig
|
||||||
|
|
||||||
|
<ReadonlyEditPopover Visible="@Visible" AnchorId="@AnchorId" Source="@Source" OptionName="@OptionName" Value="@Value" ManagedFilePath="@ManagedFilePath"
|
||||||
|
OnClose="RequestClose" OnMouseEnterPopover="CancelCloseTimer" OnMouseLeavePopover="ScheduleClose" />
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public bool Visible { get; set; }
|
||||||
|
[Parameter] public string? AnchorId { get; set; }
|
||||||
|
[Parameter] public ConfigValueSource? Source { get; set; }
|
||||||
|
[Parameter] public string OptionName { get; set; } = "";
|
||||||
|
[Parameter] public object? Value { get; set; }
|
||||||
|
[Parameter] public string? ManagedFilePath { get; set; }
|
||||||
|
[Parameter] public EventCallback OnCloseRequested { get; set; }
|
||||||
|
|
||||||
|
private CancellationTokenSource? _closeCts;
|
||||||
|
|
||||||
|
private void CancelCloseTimer()
|
||||||
|
{
|
||||||
|
_closeCts?.Cancel();
|
||||||
|
_closeCts = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ScheduleClose()
|
||||||
|
{
|
||||||
|
_closeCts?.Cancel();
|
||||||
|
_closeCts = new CancellationTokenSource();
|
||||||
|
var token = _closeCts.Token;
|
||||||
|
_ = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
try { await Task.Delay(300, token); }
|
||||||
|
catch (OperationCanceledException) { return; }
|
||||||
|
await InvokeAsync(async () =>
|
||||||
|
{
|
||||||
|
if (token.IsCancellationRequested) return;
|
||||||
|
_closeCts = null;
|
||||||
|
await OnCloseRequested.InvokeAsync();
|
||||||
|
});
|
||||||
|
}, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RequestClose()
|
||||||
|
{
|
||||||
|
CancelCloseTimer();
|
||||||
|
await OnCloseRequested.InvokeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Called when mouse leaves readonly badge; close unless pointer enters popover quickly.
|
||||||
|
/// </summary>
|
||||||
|
public void ScheduleCloseFromBadgeLeave()
|
||||||
|
{
|
||||||
|
ScheduleClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Called when readonly badge is interacted with to keep popover open.
|
||||||
|
/// </summary>
|
||||||
|
public void CancelCloseFromBadgeEnter()
|
||||||
|
{
|
||||||
|
CancelCloseTimer();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,11 +4,11 @@
|
|||||||
@Path
|
@Path
|
||||||
@if (IsEditable)
|
@if (IsEditable)
|
||||||
{
|
{
|
||||||
<span class="badge bg-primary ms-1">editable</span>
|
<StatusBadge Kind="StatusBadgeKind.Editable" Text="editable" Class="ms-1" />
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
<span class="badge bg-secondary ms-1"> read-only</span>
|
<StatusBadge Kind="StatusBadgeKind.ReadOnly" Text="read-only" Class="ms-1" />
|
||||||
}
|
}
|
||||||
</h3>
|
</h3>
|
||||||
<div class="table-responsive-cards">
|
<div class="table-responsive-cards">
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
@inherits LayoutComponentBase
|
@inherits LayoutComponentBase
|
||||||
@namespace DnsmasqWebUI.Components.Layout
|
@namespace DnsmasqWebUI.Components.Layout
|
||||||
|
@using DnsmasqWebUI.Components.Shared
|
||||||
|
@inject ISettingsModalService SettingsModalService
|
||||||
|
@implements IDisposable
|
||||||
|
|
||||||
<div class="page">
|
<div class="page">
|
||||||
<div class="sidebar">
|
<div class="sidebar">
|
||||||
@@ -14,8 +17,42 @@
|
|||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<SettingsModal IsVisible="_settingsModalOpen" Title="@_settingsModalTitle" SettingsContext="_settingsModalContext" OnClose="CloseSettingsModal" />
|
||||||
|
<NotificationHost />
|
||||||
|
|
||||||
<div id="blazor-error-ui" data-nosnippet>
|
<div id="blazor-error-ui" data-nosnippet>
|
||||||
An unhandled error has occurred.
|
An unhandled error has occurred.
|
||||||
<a href="." class="reload">Reload</a>
|
<a href="." class="reload">Reload</a>
|
||||||
<span class="dismiss" aria-label="Dismiss">×</span>
|
<span class="dismiss" aria-label="Dismiss">×</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private bool _settingsModalOpen;
|
||||||
|
private string _settingsModalTitle = "Settings";
|
||||||
|
private SettingsModalContext _settingsModalContext = SettingsModalContext.All;
|
||||||
|
|
||||||
|
protected override void OnInitialized()
|
||||||
|
{
|
||||||
|
SettingsModalService.OpenRequested += OnSettingsOpenRequested;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnSettingsOpenRequested(SettingsModalContext context, string title)
|
||||||
|
{
|
||||||
|
_settingsModalContext = context;
|
||||||
|
_settingsModalTitle = title;
|
||||||
|
_settingsModalOpen = true;
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task CloseSettingsModal()
|
||||||
|
{
|
||||||
|
_settingsModalOpen = false;
|
||||||
|
SettingsModalService.NotifySettingsChanged();
|
||||||
|
await InvokeAsync(StateHasChanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
SettingsModalService.OpenRequested -= OnSettingsOpenRequested;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ main.main {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.sidebar {
|
.sidebar {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
background: linear-gradient(180deg, #052767 0%, #3a0647 70%);
|
background: linear-gradient(180deg, #052767 0%, #3a0647 70%);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,25 @@
|
|||||||
@namespace DnsmasqWebUI.Components.Layout
|
@namespace DnsmasqWebUI.Components.Layout
|
||||||
|
@using System.Reflection
|
||||||
|
@using DnsmasqWebUI.Infrastructure.Services.UI.Notifications.Abstractions
|
||||||
@inject IOptions<ApplicationOptions> AppOptions
|
@inject IOptions<ApplicationOptions> AppOptions
|
||||||
|
@inject ISettingsModalService SettingsModalService
|
||||||
|
@inject IUpdateCheckService UpdateCheckService
|
||||||
|
@inject INotificationService NotificationService
|
||||||
|
@implements IDisposable
|
||||||
|
|
||||||
<div class="top-row ps-3 navbar navbar-dark">
|
<div class="top-row ps-3 navbar navbar-dark">
|
||||||
<div class="container-fluid d-flex align-items-center">
|
<div class="top-row-inner">
|
||||||
<a class="navbar-brand d-flex align-items-center gap-2" href="" aria-label="@AppTitle home">
|
<a class="navbar-brand d-flex align-items-center gap-2" href="" aria-label="@AppTitle home">
|
||||||
<span class="brand-logo-wrap"><img src="logo.webp" alt="" class="brand-logo" /></span>
|
<span class="brand-logo-wrap"><img src="logo.webp" alt="" class="brand-logo" /></span>
|
||||||
<span>@AppTitle</span>
|
<span>@AppTitle</span>
|
||||||
</a>
|
</a>
|
||||||
|
<div class="nav-top-controls">
|
||||||
|
<button type="button" class="nav-settings-btn" aria-label="Settings" title="Settings" @onclick="OpenAllSettings">
|
||||||
|
<i class="bi bi-gear-fill" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
<input type="checkbox" title="Navigation menu" class="navbar-toggler" id="nav-toggler" aria-label="Toggle navigation" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<input type="checkbox" title="Navigation menu" class="navbar-toggler" id="nav-toggler" aria-label="Toggle navigation" />
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="nav-scrollable" onclick="document.getElementById('nav-toggler')?.click()">
|
<div class="nav-scrollable" onclick="document.getElementById('nav-toggler')?.click()">
|
||||||
@@ -29,8 +40,85 @@
|
|||||||
</NavLink>
|
</NavLink>
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
|
<div class="nav-footer px-3 py-2" aria-label="Links and version">
|
||||||
|
<a class="nav-footer-link" href="https://github.com/alexhopeoconnor/dnsmasq-webui" target="_blank" rel="noopener noreferrer" title="dnsmasq-webui project on GitHub">Project</a>
|
||||||
|
<span class="nav-footer-sep" aria-hidden="true">·</span>
|
||||||
|
<a class="nav-footer-link" href="https://thekelleys.org.uk/dnsmasq/doc.html" target="_blank" rel="noopener noreferrer" title="Official dnsmasq documentation">Docs</a>
|
||||||
|
<span class="nav-footer-sep" aria-hidden="true">·</span>
|
||||||
|
<a class="nav-footer-link" href="@ReleaseUrl" target="_blank" rel="noopener noreferrer" title="View release on GitHub">v@(BaseVersion(Version))</a>
|
||||||
|
<span class="nav-footer-version-actions" aria-hidden="true">[
|
||||||
|
@if (UpdateCheckService.NewerVersionAvailable)
|
||||||
|
{
|
||||||
|
<a class="nav-footer-link nav-footer-new-release" href="@UpdateCheckService.NewerVersionUrl" target="_blank" rel="noopener noreferrer" title="New version @(UpdateCheckService.NewerVersionTag ?? "") is available" aria-label="New version @(UpdateCheckService.NewerVersionTag ?? "") is available">
|
||||||
|
<i class="bi bi-download" aria-hidden="true"></i>
|
||||||
|
</a>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<button type="button" class="nav-footer-link nav-footer-check-btn" @onclick="ForceCheckAsync" disabled="@UpdateCheckService.CheckInProgress" title="@GetCheckButtonTooltip()" aria-label="@GetCheckButtonTooltip()">
|
||||||
|
<i class="bi bi-arrow-repeat nav-footer-check-icon @(UpdateCheckService.CheckInProgress ? "nav-footer-spin" : null)" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
]</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@code {
|
@code {
|
||||||
|
private const string ReleasesBaseUrl = "https://github.com/alexhopeoconnor/dnsmasq-webui/releases";
|
||||||
|
private static readonly string Version = typeof(NavMenu).Assembly
|
||||||
|
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "?";
|
||||||
|
|
||||||
|
/// <summary>Base version without build metadata (e.g. 0.0.4+abc123 -> 0.0.4) for GitHub tag URLs.</summary>
|
||||||
|
private static string BaseVersion(string v)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(v) || v == "?") return v;
|
||||||
|
var i = v.IndexOf('+');
|
||||||
|
return i >= 0 ? v[..i] : v;
|
||||||
|
}
|
||||||
|
private string ReleaseUrl => Version != "?"
|
||||||
|
? $"{ReleasesBaseUrl}/tag/v{BaseVersion(Version)}"
|
||||||
|
: ReleasesBaseUrl;
|
||||||
private string? AppTitle => AppOptions?.Value?.EffectiveTitle;
|
private string? AppTitle => AppOptions?.Value?.EffectiveTitle;
|
||||||
|
|
||||||
|
protected override void OnInitialized()
|
||||||
|
{
|
||||||
|
UpdateCheckService.ResultChanged += OnUpdateCheckResultChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
UpdateCheckService.ResultChanged -= OnUpdateCheckResultChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnUpdateCheckResultChanged(object? sender, EventArgs e)
|
||||||
|
{
|
||||||
|
_ = InvokeAsync(StateHasChanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetCheckButtonTooltip()
|
||||||
|
{
|
||||||
|
if (UpdateCheckService.CheckInProgress)
|
||||||
|
return "Checking…";
|
||||||
|
var last = UpdateCheckService.LastCheckTime;
|
||||||
|
if (last.HasValue)
|
||||||
|
{
|
||||||
|
var local = last.Value.ToLocalTime();
|
||||||
|
var format = local.Date == DateTime.Now.Date ? "t" : "g"; // time only today, short date+time otherwise
|
||||||
|
return $"No new update available. Checked at {local.ToString(format)}. Check again.";
|
||||||
|
}
|
||||||
|
return "Check for updates";
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ForceCheckAsync()
|
||||||
|
{
|
||||||
|
await UpdateCheckService.CheckNowAsync();
|
||||||
|
if (UpdateCheckService.LastCheckFailed)
|
||||||
|
NotificationService.ShowError("Update check failed: " + (UpdateCheckService.LastCheckErrorMessage ?? "Unknown error."));
|
||||||
|
else if (UpdateCheckService.NewerVersionAvailable)
|
||||||
|
NotificationService.ShowSuccess($"New version {UpdateCheckService.NewerVersionTag} is available.");
|
||||||
|
else
|
||||||
|
NotificationService.ShowInfo("You're up to date.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OpenAllSettings() => SettingsModalService.Open(SettingsModalContext.All, "Settings");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,34 @@
|
|||||||
|
.top-row {
|
||||||
|
min-height: 3.5rem;
|
||||||
|
background-color: rgba(0,0,0,0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Flex row: brand left, controls right; single line, aligned with brand. */
|
||||||
|
.top-row-inner {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.5rem 1rem 0.5rem 0.75rem;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Settings + hamburger: push right, align with brand */
|
||||||
|
.nav-top-controls {
|
||||||
|
margin-left: auto;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.navbar-toggler {
|
.navbar-toggler {
|
||||||
appearance: none;
|
appearance: none;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
flex-shrink: 0;
|
||||||
width: 3.5rem;
|
width: 3.5rem;
|
||||||
height: 2.5rem;
|
height: 2.5rem;
|
||||||
color: white;
|
color: white;
|
||||||
position: absolute;
|
|
||||||
top: 50%;
|
|
||||||
right: 1rem;
|
|
||||||
transform: translateY(-50%);
|
|
||||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||||
background: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e") no-repeat center/1.75rem rgba(255, 255, 255, 0.1);
|
background: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e") no-repeat center/1.75rem rgba(255, 255, 255, 0.1);
|
||||||
}
|
}
|
||||||
@@ -16,10 +37,29 @@
|
|||||||
background-color: rgba(255, 255, 255, 0.5);
|
background-color: rgba(255, 255, 255, 0.5);
|
||||||
}
|
}
|
||||||
|
|
||||||
.top-row {
|
/* Settings button: same height as toggler on mobile for alignment */
|
||||||
position: relative;
|
.nav-settings-btn {
|
||||||
min-height: 3.5rem;
|
padding: 0.375rem 0.5rem;
|
||||||
background-color: rgba(0,0,0,0.4);
|
height: 2.5rem;
|
||||||
|
box-sizing: border-box;
|
||||||
|
background: transparent;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
color: rgba(255, 255, 255, 0.9);
|
||||||
|
cursor: pointer;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
transition: background-color 0.15s ease, color 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-settings-btn:hover {
|
||||||
|
background-color: rgba(255, 255, 255, 0.12);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-settings-btn .bi-gear-fill {
|
||||||
|
font-size: 1.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.navbar-brand {
|
.navbar-brand {
|
||||||
@@ -27,13 +67,24 @@
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
color: rgba(255, 255, 255, 0.95) !important;
|
color: rgba(255, 255, 255, 0.95) !important;
|
||||||
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.navbar-brand:hover {
|
.navbar-brand:hover {
|
||||||
color: white !important;
|
color: white !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Logo size/alignment: see app.css .sidebar .navbar-brand .brand-logo-wrap / .brand-logo */
|
/* Smaller logo on mobile so controls align with brand text */
|
||||||
|
@media (max-width: 640.98px) {
|
||||||
|
.top-row .navbar-brand .brand-logo-wrap {
|
||||||
|
width: 2.5rem;
|
||||||
|
height: 2.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.top-row .navbar-brand .brand-logo {
|
||||||
|
height: 2.5rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* Bootstrap Icons in nav: white, sized to match link text */
|
/* Bootstrap Icons in nav: white, sized to match link text */
|
||||||
.nav-item .nav-icon {
|
.nav-item .nav-icon {
|
||||||
@@ -80,12 +131,86 @@
|
|||||||
color: white;
|
color: white;
|
||||||
}
|
}
|
||||||
|
|
||||||
.nav-scrollable {
|
.nav-footer {
|
||||||
display: none;
|
margin-top: auto;
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
text-align: right;
|
||||||
}
|
}
|
||||||
|
|
||||||
.navbar-toggler:checked ~ .nav-scrollable {
|
.nav-footer-link {
|
||||||
display: block;
|
color: rgba(255, 255, 255, 0.65) !important;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-footer-link:hover {
|
||||||
|
color: rgba(255, 255, 255, 0.9) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-footer-sep {
|
||||||
|
color: rgba(255, 255, 255, 0.45);
|
||||||
|
margin: 0 0.35rem;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-footer-version-actions {
|
||||||
|
margin-left: 0.15rem;
|
||||||
|
color: rgba(255, 255, 255, 0.65);
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-footer-version-actions .nav-footer-link,
|
||||||
|
.nav-footer-version-actions .nav-footer-check-btn {
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-footer-new-release {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-footer-new-release:hover {
|
||||||
|
color: rgba(255, 255, 255, 0.9) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-footer-check-btn {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
padding: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
font: inherit;
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-footer-check-btn:disabled {
|
||||||
|
cursor: default;
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-footer-check-btn:hover:not(:disabled) {
|
||||||
|
color: rgba(255, 255, 255, 0.9) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-footer-check-icon {
|
||||||
|
display: inline-block; /* required for transform animation */
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-footer-spin {
|
||||||
|
animation: nav-footer-spin 0.8s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes nav-footer-spin {
|
||||||
|
from { transform: rotate(0deg); }
|
||||||
|
to { transform: rotate(360deg); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-scrollable {
|
||||||
|
display: none;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Toggler is inside top-row; nav-scrollable is sibling of top-row */
|
||||||
|
.top-row:has(.navbar-toggler:checked) ~ .nav-scrollable {
|
||||||
|
display: flex;
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (min-width: 641px) {
|
@media (min-width: 641px) {
|
||||||
@@ -94,11 +219,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.nav-scrollable {
|
.nav-scrollable {
|
||||||
/* Never collapse the sidebar for wide screens */
|
/* Never collapse the sidebar for wide screens; flex to fill remaining sidebar height */
|
||||||
display: block;
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
/* Allow sidebar to scroll for tall menus */
|
min-height: 0;
|
||||||
height: calc(100vh - 3.5rem);
|
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
@implements IAsyncDisposable
|
@implements IAsyncDisposable
|
||||||
@inject IJSRuntime JSRuntime
|
@inject IJSRuntime JSRuntime
|
||||||
@inject IClientSettingsService ClientSettingsService
|
@inject IClientSettingsService ClientSettingsService
|
||||||
|
@inject ILogger<SettingsModal> Logger
|
||||||
|
|
||||||
@if (IsVisible)
|
@if (IsVisible)
|
||||||
{
|
{
|
||||||
@@ -12,45 +13,141 @@
|
|||||||
<button type="button" class="btn-close" @onclick="Close" aria-label="Close"></button>
|
<button type="button" class="btn-close" @onclick="Close" aria-label="Close"></button>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-body">
|
<div class="modal-body">
|
||||||
|
@if (_validationErrors.Count > 0)
|
||||||
|
{
|
||||||
|
<div class="alert alert-danger mb-3" role="alert">
|
||||||
|
<strong>Please fix the following:</strong>
|
||||||
|
<ul class="mb-0 mt-1">
|
||||||
|
@foreach (var err in _validationErrors)
|
||||||
|
{
|
||||||
|
<li>@err</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
@if (SettingsContext == SettingsModalContext.All)
|
@if (SettingsContext == SettingsModalContext.All)
|
||||||
{
|
{
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label class="form-label">Search settings</label>
|
<div class="d-flex align-items-center gap-2 mb-1">
|
||||||
<input type="search" class="form-control" placeholder="Search..."
|
<label class="form-label mb-0">Search settings</label>
|
||||||
@bind="_searchTerm" @bind:event="oninput" />
|
<div class="d-flex gap-1 ms-auto" role="group" aria-label="Expand or collapse all sections">
|
||||||
|
<button type="button" class="btn btn-sm btn-outline-secondary settings-expand-collapse-btn" title="Expand all sections" aria-label="Expand all sections" @onclick="ExpandAllGroups">
|
||||||
|
<i class="bi bi-arrows-expand" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-sm btn-outline-secondary settings-expand-collapse-btn" title="Collapse all sections" aria-label="Collapse all sections" @onclick="CollapseAllGroups">
|
||||||
|
<i class="bi bi-arrows-collapse" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<input type="search" class="form-control" placeholder="Search..." autocomplete="off"
|
||||||
|
@bind="_searchTerm" @bind:event="oninput" @bind:after="FilterSettings" />
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@if (ShouldShowSection("ServiceStatus"))
|
@foreach (var group in GetVisibleGroups())
|
||||||
{
|
{
|
||||||
<section class="mb-4">
|
var isAllSections = SettingsContext == SettingsModalContext.All;
|
||||||
<h6 class="text-muted">Service status</h6>
|
var isExpanded = isAllSections ? IsGroupExpanded(group) : true;
|
||||||
<label for="status-interval" class="form-label">Polling interval (seconds)</label>
|
<div class="settings-group">
|
||||||
<input id="status-interval" type="number" class="form-control" min="5" step="1"
|
@if (isAllSections)
|
||||||
@bind="_editingSettings.ServiceStatusPollingIntervalSeconds" />
|
{
|
||||||
</section>
|
<button type="button" class="settings-group-header @(isExpanded ? "expanded" : "")"
|
||||||
}
|
@onclick="() => ToggleGroup(group.Id)"
|
||||||
@if (ShouldShowSection("Logs"))
|
aria-expanded="@isExpanded"
|
||||||
{
|
aria-controls="group-@group.Id">
|
||||||
<section class="mb-4">
|
<span class="settings-group-title">@group.DisplayName</span>
|
||||||
<h6 class="text-muted">Recent logs</h6>
|
<span class="settings-group-chevron" aria-hidden="true"></span>
|
||||||
<label for="logs-interval" class="form-label">Polling interval (seconds)</label>
|
</button>
|
||||||
<input id="logs-interval" type="number" class="form-control" min="5" step="1"
|
}
|
||||||
@bind="_editingSettings.RecentLogsPollingIntervalSeconds" />
|
else
|
||||||
</section>
|
{
|
||||||
}
|
<h6 class="settings-group-title settings-group-title-static mb-2 mt-3">@group.DisplayName</h6>
|
||||||
@if (ShouldShowSection("Leases"))
|
}
|
||||||
{
|
<div id="group-@group.Id" class="settings-group-content @(isExpanded ? "expanded" : "")"
|
||||||
<section class="mb-4">
|
role="region" aria-label="@group.DisplayName">
|
||||||
<h6 class="text-muted">DHCP leases</h6>
|
@foreach (var key in group.SectionKeys)
|
||||||
<label for="leases-interval" class="form-label">Refresh interval (seconds)</label>
|
{
|
||||||
<input id="leases-interval" type="number" class="form-control" min="5" step="1"
|
@if (ShouldShowSection(key))
|
||||||
@bind="_editingSettings.LeasesPollingIntervalSeconds" />
|
{
|
||||||
</section>
|
<div class="settings-section">
|
||||||
|
@switch (key)
|
||||||
|
{
|
||||||
|
case SettingsModalSections.ServiceStatus:
|
||||||
|
{
|
||||||
|
var meta = SettingsModalSections.All[SettingsModalSections.ServiceStatus];
|
||||||
|
var field = ClientSettingsFields.ServiceStatusPollingInterval;
|
||||||
|
<label for="status-interval" class="form-label">@meta.FieldLabel</label>
|
||||||
|
<input id="status-interval" type="number" class="form-control" min="@field.Min" max="@field.Max" step="1"
|
||||||
|
@bind="field.Value" />
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case SettingsModalSections.Logs:
|
||||||
|
{
|
||||||
|
var meta = SettingsModalSections.All[SettingsModalSections.Logs];
|
||||||
|
var field = ClientSettingsFields.RecentLogsPollingInterval;
|
||||||
|
<label for="logs-interval" class="form-label">@meta.FieldLabel</label>
|
||||||
|
<input id="logs-interval" type="number" class="form-control" min="@field.Min" max="@field.Max" step="1"
|
||||||
|
@bind="field.Value" />
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case SettingsModalSections.AppLogs:
|
||||||
|
{
|
||||||
|
var meta = SettingsModalSections.All[SettingsModalSections.AppLogs];
|
||||||
|
var field = ClientSettingsFields.AppLogsPollingInterval;
|
||||||
|
<label for="app-logs-interval" class="form-label">@meta.FieldLabel</label>
|
||||||
|
<input id="app-logs-interval" type="number" class="form-control" min="@field.Min" max="@field.Max" step="1"
|
||||||
|
@bind="field.Value" />
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case SettingsModalSections.Leases:
|
||||||
|
{
|
||||||
|
var meta = SettingsModalSections.All[SettingsModalSections.Leases];
|
||||||
|
var field = ClientSettingsFields.LeasesPollingInterval;
|
||||||
|
<label for="leases-interval" class="form-label">@meta.FieldLabel</label>
|
||||||
|
<input id="leases-interval" type="number" class="form-control" min="@field.Min" max="@field.Max" step="1"
|
||||||
|
@bind="field.Value" />
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case SettingsModalSections.RecentLogsDisplay:
|
||||||
|
{
|
||||||
|
var maxLinesField = ClientSettingsFields.RecentLogsMaxLines;
|
||||||
|
var autoScrollField = ClientSettingsFields.RecentLogsAutoScroll;
|
||||||
|
<div class="mb-2">
|
||||||
|
<label for="recent-logs-max-lines" class="form-label">Max lines</label>
|
||||||
|
<input id="recent-logs-max-lines" type="number" class="form-control" min="@maxLinesField.Min" max="@maxLinesField.Max" step="1"
|
||||||
|
@bind="maxLinesField.Value" />
|
||||||
|
</div>
|
||||||
|
<div class="form-check">
|
||||||
|
<input id="recent-logs-auto-scroll" type="checkbox" class="form-check-input" @bind="autoScrollField.Value" />
|
||||||
|
<label for="recent-logs-auto-scroll" class="form-check-label">Auto-scroll when new logs arrive</label>
|
||||||
|
</div>
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case SettingsModalSections.AppLogsDisplay:
|
||||||
|
{
|
||||||
|
var maxLinesField = ClientSettingsFields.AppLogsMaxLines;
|
||||||
|
var autoScrollField = ClientSettingsFields.AppLogsAutoScroll;
|
||||||
|
<div class="mb-2">
|
||||||
|
<label for="app-logs-max-lines" class="form-label">Max lines</label>
|
||||||
|
<input id="app-logs-max-lines" type="number" class="form-control" min="@maxLinesField.Min" max="@maxLinesField.Max" step="1"
|
||||||
|
@bind="maxLinesField.Value" />
|
||||||
|
</div>
|
||||||
|
<div class="form-check">
|
||||||
|
<input id="app-logs-auto-scroll" type="checkbox" class="form-check-input" @bind="autoScrollField.Value" />
|
||||||
|
<label for="app-logs-auto-scroll" class="form-check-label">Auto-scroll when new logs arrive</label>
|
||||||
|
</div>
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
<button type="button" class="btn btn-secondary" @onclick="Close">Cancel</button>
|
<button type="button" class="btn btn-secondary" @onclick="Close"><i class="bi bi-x me-1" aria-hidden="true"></i>Cancel</button>
|
||||||
<button type="button" class="btn btn-primary" @onclick="Save">Save</button>
|
<button type="button" class="btn btn-primary" @onclick="Save"><i class="bi bi-floppy-fill me-1" aria-hidden="true"></i>Save</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using DnsmasqWebUI.Client.Models;
|
using DnsmasqWebUI.Models.Client;
|
||||||
using DnsmasqWebUI.Client.Services.Abstractions;
|
using DnsmasqWebUI.Extensions.Interop;
|
||||||
|
using DnsmasqWebUI.Infrastructure.Services.UI.Settings.Abstractions;
|
||||||
using Microsoft.AspNetCore.Components;
|
using Microsoft.AspNetCore.Components;
|
||||||
using Microsoft.AspNetCore.Components.Web;
|
using Microsoft.AspNetCore.Components.Web;
|
||||||
using Microsoft.JSInterop;
|
using Microsoft.JSInterop;
|
||||||
@@ -15,8 +16,9 @@ public partial class SettingsModal : IAsyncDisposable
|
|||||||
private ElementReference _dialogRef;
|
private ElementReference _dialogRef;
|
||||||
private IJSObjectReference? _jsModule;
|
private IJSObjectReference? _jsModule;
|
||||||
private DotNetObjectReference<SettingsModal>? _dotNetRef;
|
private DotNetObjectReference<SettingsModal>? _dotNetRef;
|
||||||
private ClientSettings _editingSettings = new();
|
private List<string> _validationErrors = new();
|
||||||
private string _searchTerm = string.Empty;
|
private string _searchTerm = string.Empty;
|
||||||
|
private HashSet<string> _expandedGroupIds = new(StringComparer.OrdinalIgnoreCase);
|
||||||
private bool _moduleLoaded;
|
private bool _moduleLoaded;
|
||||||
private bool _dialogInitialized;
|
private bool _dialogInitialized;
|
||||||
private bool _wasVisible;
|
private bool _wasVisible;
|
||||||
@@ -38,13 +40,13 @@ public partial class SettingsModal : IAsyncDisposable
|
|||||||
// Only load from storage when the modal opens; parent re-renders (e.g. refresh timer) must not overwrite in-progress edits
|
// Only load from storage when the modal opens; parent re-renders (e.g. refresh timer) must not overwrite in-progress edits
|
||||||
if (justOpened)
|
if (justOpened)
|
||||||
{
|
{
|
||||||
_editingSettings = await ClientSettingsService.LoadSettingsAsync();
|
_searchTerm = string.Empty;
|
||||||
_editingSettings = new ClientSettings
|
_expandedGroupIds.Clear();
|
||||||
{
|
var visible = SettingsModalSections.Groups.Where(g => SettingsModalSections.GroupMatchesContextOrSearch(g, SettingsContext, _searchTerm)).ToList();
|
||||||
ServiceStatusPollingIntervalSeconds = _editingSettings.ServiceStatusPollingIntervalSeconds,
|
if (visible.Count > 0)
|
||||||
RecentLogsPollingIntervalSeconds = _editingSettings.RecentLogsPollingIntervalSeconds,
|
_expandedGroupIds.Add(visible[0].Id);
|
||||||
LeasesPollingIntervalSeconds = _editingSettings.LeasesPollingIntervalSeconds
|
_validationErrors.Clear();
|
||||||
};
|
await ClientSettingsService.LoadSettingsAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,64 +54,100 @@ public partial class SettingsModal : IAsyncDisposable
|
|||||||
{
|
{
|
||||||
if (firstRender)
|
if (firstRender)
|
||||||
{
|
{
|
||||||
_jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/settings-modal.js");
|
try
|
||||||
_dotNetRef = DotNetObjectReference.Create(this);
|
{
|
||||||
_moduleLoaded = true;
|
_jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/dialog.js");
|
||||||
|
_dotNetRef = DotNetObjectReference.Create(this);
|
||||||
|
_moduleLoaded = true;
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex) { Logger.LogDebug(ex, "SettingsModal: JS import skipped (prerender)"); }
|
||||||
|
catch (JSDisconnectedException ex) { Logger.LogDebug(ex, "SettingsModal: JS import skipped (circuit disconnected)"); }
|
||||||
|
catch (JSException ex) { Logger.LogDebug(ex, "SettingsModal: JS import failed"); }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (IsVisible && _moduleLoaded && _jsModule != null)
|
if (IsVisible && _moduleLoaded && _jsModule != null)
|
||||||
{
|
{
|
||||||
if (!_dialogInitialized)
|
if (!_dialogInitialized)
|
||||||
{
|
{
|
||||||
await _jsModule.InvokeVoidAsync("initDialog", _dialogRef, _dotNetRef);
|
await _jsModule.InvokeVoidAsyncSafe("initDialog", _dialogRef, _dotNetRef);
|
||||||
_dialogInitialized = true;
|
_dialogInitialized = true;
|
||||||
}
|
}
|
||||||
await _jsModule.InvokeVoidAsync("showModal", _dialogRef);
|
await _jsModule.InvokeVoidAsyncSafe("showModal", _dialogRef);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void FilterSettings() => StateHasChanged();
|
||||||
|
|
||||||
|
private IEnumerable<SettingsModalSections.CollapsibleGroup> GetVisibleGroups() =>
|
||||||
|
SettingsModalSections.Groups.Where(g => SettingsModalSections.GroupMatchesContextOrSearch(g, SettingsContext, _searchTerm));
|
||||||
|
|
||||||
|
private bool IsGroupExpanded(SettingsModalSections.CollapsibleGroup group)
|
||||||
|
{
|
||||||
|
var hasActiveFilter = SettingsContext == SettingsModalContext.All && !string.IsNullOrWhiteSpace(_searchTerm);
|
||||||
|
if (hasActiveFilter)
|
||||||
|
return true;
|
||||||
|
return _expandedGroupIds.Contains(group.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ToggleGroup(string groupId)
|
||||||
|
{
|
||||||
|
if (_expandedGroupIds.Contains(groupId))
|
||||||
|
_expandedGroupIds.Remove(groupId);
|
||||||
|
else
|
||||||
|
_expandedGroupIds.Add(groupId);
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ExpandAllGroups()
|
||||||
|
{
|
||||||
|
foreach (var g in GetVisibleGroups())
|
||||||
|
_expandedGroupIds.Add(g.Id);
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CollapseAllGroups()
|
||||||
|
{
|
||||||
|
_expandedGroupIds.Clear();
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
private bool ShouldShowSection(string key)
|
private bool ShouldShowSection(string key)
|
||||||
{
|
{
|
||||||
if (SettingsContext == SettingsModalContext.ServicePolling)
|
var keys = SettingsModalSections.GetSectionKeysForContext(SettingsContext);
|
||||||
return key == "ServiceStatus";
|
if (keys != null)
|
||||||
if (SettingsContext == SettingsModalContext.LogsPolling)
|
return keys.Any(k => string.Equals(key, k, StringComparison.OrdinalIgnoreCase));
|
||||||
return key == "Logs";
|
return SettingsModalSections.MatchesSearch(key, _searchTerm);
|
||||||
if (SettingsContext == SettingsModalContext.LeasesPolling)
|
}
|
||||||
return key == "Leases";
|
|
||||||
if (SettingsContext == SettingsModalContext.All)
|
private void RunValidation()
|
||||||
|
{
|
||||||
|
_validationErrors.Clear();
|
||||||
|
foreach (var (section, field) in ClientSettingsFields.ValidationChecks)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(_searchTerm)) return true;
|
if (ShouldShowSection(section) && field.Validate() is { } err)
|
||||||
var term = _searchTerm.Trim();
|
_validationErrors.Add(err);
|
||||||
return key switch
|
|
||||||
{
|
|
||||||
"ServiceStatus" => "service status polling".Contains(term, StringComparison.OrdinalIgnoreCase),
|
|
||||||
"Logs" => "recent logs polling".Contains(term, StringComparison.OrdinalIgnoreCase),
|
|
||||||
"Leases" => "dhcp leases refresh polling".Contains(term, StringComparison.OrdinalIgnoreCase),
|
|
||||||
_ => false
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task Save()
|
private async Task Save()
|
||||||
{
|
{
|
||||||
_editingSettings.ServiceStatusPollingIntervalSeconds = Math.Clamp(
|
RunValidation();
|
||||||
_editingSettings.ServiceStatusPollingIntervalSeconds, 5, 300);
|
if (_validationErrors.Count > 0)
|
||||||
_editingSettings.RecentLogsPollingIntervalSeconds = Math.Clamp(
|
{
|
||||||
_editingSettings.RecentLogsPollingIntervalSeconds, 5, 300);
|
await InvokeAsync(StateHasChanged);
|
||||||
_editingSettings.LeasesPollingIntervalSeconds = Math.Clamp(
|
return;
|
||||||
_editingSettings.LeasesPollingIntervalSeconds, 5, 300);
|
}
|
||||||
|
|
||||||
await ClientSettingsService.SaveSettingsAsync(_editingSettings);
|
await ClientSettingsService.SaveSettingsAsync(ClientSettingsFields.ToDto());
|
||||||
if (_jsModule != null)
|
if (_jsModule != null)
|
||||||
await _jsModule.InvokeVoidAsync("closeModal", _dialogRef);
|
await _jsModule.InvokeVoidAsyncSafe("closeModal", _dialogRef);
|
||||||
await OnClose.InvokeAsync();
|
await OnClose.InvokeAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task Close()
|
private async Task Close()
|
||||||
{
|
{
|
||||||
if (_jsModule != null)
|
if (_jsModule != null)
|
||||||
await _jsModule.InvokeVoidAsync("closeModal", _dialogRef);
|
await _jsModule.InvokeVoidAsyncSafe("closeModal", _dialogRef);
|
||||||
await OnClose.InvokeAsync();
|
await OnClose.InvokeAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,15 +163,8 @@ public partial class SettingsModal : IAsyncDisposable
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public async ValueTask DisposeAsync()
|
public async ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
try
|
await _jsModule.DisposeAsyncSafe();
|
||||||
{
|
_jsModule = null;
|
||||||
if (_jsModule != null)
|
|
||||||
await _jsModule.DisposeAsync();
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_jsModule = null;
|
|
||||||
}
|
|
||||||
_dotNetRef?.Dispose();
|
_dotNetRef?.Dispose();
|
||||||
_dotNetRef = null;
|
_dotNetRef = null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,8 +28,98 @@
|
|||||||
padding: 1.25rem;
|
padding: 1.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.settings-expand-collapse-btn {
|
||||||
|
padding: 0.25rem 0.4rem;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-expand-collapse-btn .bi {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
.settings-modal-dialog .modal-footer {
|
.settings-modal-dialog .modal-footer {
|
||||||
padding: 1rem 1.25rem;
|
padding: 1rem 1.25rem;
|
||||||
border-top: 1px solid rgba(0, 0, 0, 0.125);
|
border-top: 1px solid rgba(0, 0, 0, 0.125);
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Collapsible section groups */
|
||||||
|
.settings-group {
|
||||||
|
border: 1px solid rgba(0, 0, 0, 0.1);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-group:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-group-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.625rem 0.75rem;
|
||||||
|
font-size: 0.9375rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: #212529;
|
||||||
|
background: rgba(0, 0, 0, 0.03);
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: left;
|
||||||
|
transition: background-color 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-group-header:hover {
|
||||||
|
background: rgba(0, 0, 0, 0.06);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-group-header.expanded {
|
||||||
|
background: rgba(0, 0, 0, 0.05);
|
||||||
|
border-bottom: 1px solid rgba(0, 0, 0, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-group-chevron {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 0.75rem;
|
||||||
|
height: 0.75rem;
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
border-right: 2px solid #6c757d;
|
||||||
|
border-bottom: 2px solid #6c757d;
|
||||||
|
transform: rotate(-45deg);
|
||||||
|
transition: transform 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-group-header.expanded .settings-group-chevron {
|
||||||
|
transform: rotate(135deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-group-title-static {
|
||||||
|
margin-left: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-group-content {
|
||||||
|
max-height: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
transition: max-height 0.25s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-group-content.expanded {
|
||||||
|
max-height: 500px;
|
||||||
|
transition: max-height 0.35s ease-in;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-group-content > * {
|
||||||
|
padding: 1rem 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-section {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-section + .settings-section {
|
||||||
|
border-top: 1px solid rgba(0, 0, 0, 0.06);
|
||||||
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user