Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
750564ab7e | ||
|
|
3fadee87d3 | ||
|
|
ba231e7187 | ||
|
|
a1915f070b | ||
|
|
dc0f159447 | ||
|
|
58492be021 | ||
|
|
db9657c01c | ||
|
|
fb73ac3a9f | ||
|
|
2f2aaf6c34 | ||
|
|
caed976e63 | ||
|
|
8e7c15ad56 | ||
|
|
4f12ca19e7 | ||
|
|
edeb1506fd | ||
|
|
7a6370aa9e | ||
|
|
466ca6c7b0 | ||
|
|
fd9543ce68 | ||
|
|
31a2065f05 | ||
|
|
2b98abdba4 | ||
|
|
1a2f0b327e | ||
|
|
5768856d76 | ||
|
|
972e522518 | ||
|
|
29b1d7dfd7 | ||
|
|
6444722d14 | ||
|
|
34293fb8e5 | ||
|
|
70a932b8ea | ||
|
|
e657742b52 | ||
|
|
aa8256bc60 | ||
|
|
82ab86848e |
No files matched your search
@@ -1,18 +1,31 @@
|
||||
name: Build packages
|
||||
|
||||
# A tag vX.Y.Z builds luci-app-dawnline as .ipk (OpenWrt 24.10, opkg) and .apk
|
||||
# (OpenWrt 25.12, apk) with the OpenWrt SDK and publishes a GitHub release with
|
||||
# both packages and sha256sums.txt, the files install.sh and the in-app updater
|
||||
# download. Run it by hand to get the packages as workflow artifacts only.
|
||||
# A tag vX.Y.Z builds luci-app-dawnline and its translation packages
|
||||
# (luci-i18n-dawnline-<lang>) as .ipk (OpenWrt 24.10, opkg) and .apk (OpenWrt
|
||||
# 25.12, apk) with the OpenWrt SDK and publishes a GitHub release with the
|
||||
# packages and sha256sums.txt, the files install.sh and the in-app updater
|
||||
# download. The release notes list what changed since the previous tag, from the
|
||||
# commits (scripts/release-notes.sh). Run it by hand to get the packages as
|
||||
# workflow artifacts only.
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
|
||||
# Read-only by default; only the release job may write (publish the release).
|
||||
# Everything that runs here is pinned to a digest or a commit: the packages
|
||||
# it publishes are installed as root on every router with automatic updates
|
||||
# on, so a re-pointed tag must not be able to change what gets built.
|
||||
permissions:
|
||||
contents: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
# The same checks as on main (ci.yml), on the tag itself: nothing is built or
|
||||
# published until they pass.
|
||||
ci:
|
||||
name: CI
|
||||
uses: ./.github/workflows/ci.yml
|
||||
|
||||
version:
|
||||
name: Version
|
||||
runs-on: ubuntu-24.04
|
||||
@@ -20,7 +33,9 @@ jobs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Read and check the version
|
||||
id: version
|
||||
@@ -39,19 +54,21 @@ jobs:
|
||||
build:
|
||||
name: Build ${{ matrix.type }}
|
||||
runs-on: ubuntu-24.04
|
||||
needs: version
|
||||
needs: [version, ci]
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
include:
|
||||
- { type: ipk, sdk: 'itdoginfo/openwrt-sdk-ipk:24.10.6' }
|
||||
- { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3' }
|
||||
- { type: ipk, sdk: 'itdoginfo/openwrt-sdk-ipk:24.10.6@sha256:a6bd28c380b251ebdb1d6d5f83e55ecb0a3c1808b5a8f4841424abc8019a903f' }
|
||||
- { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3@sha256:6d832008ddd1b8ec4edc84f5e6e0bf22a13ba2d6888083a8e69fa26d752c276f' }
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v5
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
@@ -70,10 +87,11 @@ jobs:
|
||||
run: scripts/build-packages.sh ${{ matrix.type }}
|
||||
|
||||
- name: Upload
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: package-${{ matrix.type }}
|
||||
path: dist/luci-app-dawnline-${{ needs.version.outputs.version }}.${{ matrix.type }}
|
||||
# The app and its translation packages (luci-i18n-dawnline-<lang>).
|
||||
path: dist/luci-*-${{ needs.version.outputs.version }}.${{ matrix.type }}
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
@@ -82,9 +100,23 @@ jobs:
|
||||
runs-on: ubuntu-24.04
|
||||
needs: [version, build]
|
||||
if: github.ref_type == 'tag'
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
# The whole history and the tags: the notes list the commits since the previous tag.
|
||||
- name: Checkout
|
||||
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Release notes
|
||||
run: |
|
||||
sh scripts/release-notes.sh "${GITHUB_REF_NAME}" "${GITHUB_REPOSITORY}" > notes.md
|
||||
cat notes.md
|
||||
|
||||
- name: Download packages
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
with:
|
||||
pattern: package-*
|
||||
path: release
|
||||
@@ -93,21 +125,13 @@ jobs:
|
||||
- name: Checksums
|
||||
working-directory: release
|
||||
run: |
|
||||
sha256sum luci-app-dawnline-* > sha256sums.txt
|
||||
sha256sum luci-* > sha256sums.txt
|
||||
cat sha256sums.txt
|
||||
|
||||
- name: Publish the release
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
with:
|
||||
name: Dawnline ${{ github.ref_name }}
|
||||
tag_name: ${{ github.ref_name }}
|
||||
files: release/*
|
||||
generate_release_notes: true
|
||||
body: |
|
||||
Install or upgrade on the router (OpenWrt 24.10 with opkg, or 25.12 with apk):
|
||||
|
||||
```sh
|
||||
sh -c "$(wget -qO- https://raw.githubusercontent.com/${{ github.repository }}/main/install.sh)"
|
||||
```
|
||||
|
||||
Or upgrade from LuCI → Network → Dawnline → Updates.
|
||||
body_path: notes.md
|
||||
@@ -1,9 +1,12 @@
|
||||
name: CI
|
||||
|
||||
# Every push to main and every pull request; also called by build.yml, so a
|
||||
# tag never publishes a release without these checks passing on it.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -22,6 +25,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v5
|
||||
@@ -41,20 +46,35 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Sources and the test files (tsconfig.test.json).
|
||||
- name: Type check
|
||||
id: types
|
||||
run: npm run --silent typecheck
|
||||
|
||||
# The catalogs follow the code: every string collected, translated, its placeholders kept.
|
||||
- name: Translations
|
||||
id: i18n
|
||||
run: |
|
||||
if ! npm run --silent i18n:check; then
|
||||
echo "::error::The translation catalogs are out of date or incomplete. Run 'npm run i18n' in web/, translate the new entries in each ru.po and commit them (rules/i18n.md)."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Tests
|
||||
id: tests
|
||||
run: npm test
|
||||
|
||||
# The bundles under package/ are committed: a build must change nothing
|
||||
# and leave no new file behind (an output nobody added to git would be
|
||||
# missing from the package).
|
||||
- name: Build bundles and check they are committed
|
||||
id: build
|
||||
run: |
|
||||
npm run --silent build
|
||||
if ! git diff --exit-code -- ../package; then
|
||||
echo "::error::The committed bundles are out of date. Run 'npm run build' in web/ and commit the result."
|
||||
changed="$(git status --porcelain --untracked-files=all -- ../package)"
|
||||
if [ -n "$changed" ]; then
|
||||
echo "$changed"
|
||||
echo "::error::The committed bundles are out of date or the build left new files. Run 'npm run build' in web/ and commit the result."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -68,6 +88,7 @@ jobs:
|
||||
echo "|---|---|"
|
||||
echo "| Formatting | ${{ steps.format.outcome }} |"
|
||||
echo "| Types | ${{ steps.types.outcome }} |"
|
||||
echo "| Translations | ${{ steps.i18n.outcome }} |"
|
||||
echo "| Tests | ${{ steps.tests.outcome }} |"
|
||||
echo "| Bundles | ${{ steps.build.outcome }} |"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -78,16 +99,28 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# Every shell script by its shebang (the init script's is "/bin/sh
|
||||
# /etc/rc.common"), so a new hotplug or libexec script is covered the
|
||||
# day it appears. Files without a shebang (keep.d lists) are not shell.
|
||||
- name: ShellCheck
|
||||
run: |
|
||||
shellcheck --version
|
||||
shellcheck -S warning \
|
||||
install.sh \
|
||||
package/luci-app-dawnline/root/etc/init.d/dawnline \
|
||||
package/luci-app-dawnline/root/etc/uci-defaults/90_dawnline \
|
||||
package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline \
|
||||
scripts/*.sh
|
||||
files="$(grep -rlIE '^#!(/usr)?/bin/(sh|bash|env (sh|bash))( |$)' \
|
||||
install.sh uninstall.sh package/luci-app-dawnline/root scripts tests | sort)"
|
||||
echo "$files"
|
||||
for f in package/luci-app-dawnline/root/etc/init.d/dawnline \
|
||||
package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline \
|
||||
package/luci-app-dawnline/root/usr/libexec/dawnline/resolver \
|
||||
package/luci-app-dawnline/root/usr/libexec/dawnline/heartbeat \
|
||||
package/luci-app-dawnline/root/usr/libexec/dawnline/postupdate \
|
||||
package/luci-app-dawnline/root/usr/share/dawnline/portal/www/cgi-bin/portal; do
|
||||
echo "$files" | grep -qx "$f" || { echo "::error file=$f::not found by the shebang scan"; exit 1; }
|
||||
done
|
||||
# shellcheck disable=SC2086
|
||||
shellcheck -S warning $files
|
||||
|
||||
ucode:
|
||||
name: ucode static checks
|
||||
@@ -95,21 +128,55 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Use before definition
|
||||
- name: Lint (use before definition, exports, POSIX regexes, rpcd methods)
|
||||
run: python3 scripts/lint-ucode.py
|
||||
|
||||
- name: Executables keep their mode
|
||||
run: |
|
||||
cd package/luci-app-dawnline/root
|
||||
for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver \
|
||||
etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do
|
||||
for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver usr/libexec/dawnline/heartbeat usr/libexec/dawnline/postupdate \
|
||||
etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal usr/share/dawnline/portal/cgi.uc; do
|
||||
[ -x "package/luci-app-dawnline/root/$f" ] || { echo "::error file=package/luci-app-dawnline/root/$f::not executable (git update-index --chmod=+x $f)"; exit 1; }
|
||||
done
|
||||
for f in scripts/check-ucode.sh scripts/compile-ucode.sh scripts/ucode-container.sh tests/ucode/run.sh tests/ucode/fixtures/bin/awg; do
|
||||
[ -x "$f" ] || { echo "::error file=$f::not executable (git update-index --chmod=+x $f)"; exit 1; }
|
||||
done
|
||||
|
||||
- name: Versions agree
|
||||
run: |
|
||||
v="$(sed -n 's/^PKG_VERSION:=//p' package/luci-app-dawnline/Makefile)"
|
||||
grep -q "^export const VERSION = '$v';" package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc
|
||||
grep -q "\"version\": \"$v\"" web/package.json
|
||||
grep -q "^export const VERSION = '$v';" package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc ||
|
||||
{ echo "::error::util.uc VERSION differs from the Makefile ($v)"; exit 1; }
|
||||
grep -q "\"version\": \"$v\"" web/package.json ||
|
||||
{ echo "::error::web/package.json version differs from the Makefile ($v)"; exit 1; }
|
||||
python3 - "$v" <<'PY'
|
||||
import json, sys
|
||||
v = sys.argv[1]
|
||||
lock = json.load(open('web/package-lock.json'))
|
||||
got = (lock.get('version'), lock.get('packages', {}).get('', {}).get('version'))
|
||||
if got != (v, v):
|
||||
print(f"::error::web/package-lock.json says {got}, the Makefile {v}: run 'npm install' in web/")
|
||||
sys.exit(1)
|
||||
PY
|
||||
echo "Version $v"
|
||||
|
||||
ucode-compile:
|
||||
# scripts/compile-ucode.sh and tests/ucode on the release's own ucode and
|
||||
# libuci, in the OpenWrt rootfs containers scripts/ucode-container.sh pins
|
||||
# by digest (24.10 = opkg, 25.12 = apk: the two the packages are built for).
|
||||
name: ucode compiles and tests pass (OpenWrt ${{ matrix.release }})
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
release: ['24.10', '25.12']
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Compile every ucode file and run tests/ucode
|
||||
run: scripts/ucode-container.sh ${{ matrix.release }}
|
||||
@@ -0,0 +1,41 @@
|
||||
# AGENTS.md — Dawnline
|
||||
|
||||
Guidance for coding agents working in this repository (`tickcount/luci-app-dawnline`): an AmneziaWG access server for OpenWrt with a LuCI admin UI and a personal portal. `CLAUDE.md` points here.
|
||||
|
||||
## Rules
|
||||
|
||||
- `rules/code-standards.md` — how all code is written: decomposition, one locked writer, fail closed, validation at the boundary, comments and commits.
|
||||
- `rules/backend.md` — ucode on the router: module layers, conventions, what things cost there (CGI portal, rpcd, the agent's watcher).
|
||||
- `rules/frontend.md` — TypeScript admin UI and portal: layout of `web/src`, pollers and the live revision.
|
||||
- `rules/shell.md` — install, uninstall, init and CI scripts.
|
||||
- `rules/ui-design.md` — how the admin UI and the portal look: modern product quality, mock first from the real CSS and components, verified in the browser.
|
||||
- `DESIGN.md` — the personal portal's design system: tokens, components, layout and motion, measured on the live page. Read it before any work on the portal (`web/src/portal`, and what it uses from `web/src/shared`); a change to how the portal looks or moves updates it in the same change.
|
||||
- `rules/i18n.md` — translations: every visible string and backend message wrapped, the catalogs, the Russian style guide and glossary. Anything added to the admin UI or the portal is localized in the same change; anything removed takes its catalog entries with it.
|
||||
|
||||
This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its rules apply to anything that touches the router: read-only first, backup before mutating, router shell as a literal stdin heredoc over SSH (`../rules/`).
|
||||
|
||||
## Layout
|
||||
|
||||
- `package/luci-app-dawnline/root/` — what lands on the router: ucode modules in `usr/share/ucode/dawnline/` (`rpc/` for the LuCI backend), the agent and updater in `usr/libexec/dawnline/`, the portal in `usr/share/dawnline/portal/`, the init script, rpcd ACL.
|
||||
- `web/` — TypeScript sources of the admin UI (`src/admin`) and the portal (`src/portal`), shared code in `src/shared`; the built bundles are committed under `package/`. `web/i18n/` — the string catalogs' tools (`extract.ts`, `po.ts`, `lmo.ts`).
|
||||
- `package/luci-app-dawnline/po/` — the admin's catalog (`templates/dawnline.pot`, `ru/dawnline.po`): luci.mk builds the `luci-i18n-dawnline-ru` package from it. The portal's catalog is `web/src/portal/i18n/ru.po`, bundled into the portal.
|
||||
- `install.sh`, `uninstall.sh` — the standalone installer and uninstaller (both have `--dry-run`).
|
||||
- `scripts/` — `lint-ucode.py`, `compile-ucode.sh` (compiles every ucode file of a tree wherever ucode runs), `check-ucode.sh` (the same on the router, without installing), `ucode-container.sh` (compile and unit tests in the OpenWrt rootfs containers CI uses), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`.
|
||||
- `tests/ucode/` — unit tests of the ucode modules (`run.uc` runs every `*.test.uc`; fixtures for `/etc/config` and a stand-in `awg`), run in a container by `run.sh`.
|
||||
|
||||
## Checks before a commit or deploy
|
||||
|
||||
- `python3 scripts/lint-ucode.py` (use before definition, exports, POSIX regexes, rpcd methods; layering notes are informational).
|
||||
- `scripts/ucode-container.sh` (needs docker): compiles every ucode file and runs `tests/ucode` on OpenWrt 24.10 and 25.12, exactly what CI does. `scripts/check-ucode.sh` compiles on the router instead when there is no docker. New ucode entry points are added to the compile list in `scripts/compile-ucode.sh`, to `lint-ucode.py`, and to the executables list in `.github/workflows/ci.yml`; a pure function gets a case in `tests/ucode/<module>.test.uc`.
|
||||
- In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm run i18n:check` (after changing visible text: `npm run i18n`, translate the new entries in each `ru.po`), `npm test`, `npm run build` — and commit the rebuilt bundles and the catalogs (CI fails on a changed or new file under `package/`).
|
||||
- `shellcheck -S warning` for the shell scripts (CI finds them by shebang).
|
||||
- A tag builds only after CI passes on it (`build.yml` calls `ci.yml`).
|
||||
|
||||
## Releases
|
||||
|
||||
- A release is one commit on `main` titled `Dawnline X.Y.Z`; its body is `- ` points, which become the GitHub release notes and the Components "What's new". Work from a branch is squashed into that one commit.
|
||||
- Bump the version in `package/luci-app-dawnline/Makefile` (`PKG_VERSION`), `util.uc` (`VERSION`), `web/package.json` and `web/package-lock.json` (CI checks they agree).
|
||||
- No `Co-Authored-By` or other agent attribution in commits.
|
||||
- Push `main`, then an annotated tag `vX.Y.Z` ("Dawnline X.Y.Z"); the "Build packages" workflow publishes the `.ipk`, `.apk` (the app and `luci-i18n-dawnline-ru`) and `sha256sums.txt`.
|
||||
- Re-cutting a release (fixes before anyone installs) rewrites `main`: force-push, `gh release delete vX.Y.Z --cleanup-tag`, cancel a running build of the old tag, tag again. Only with the user's go-ahead.
|
||||
- On the router, install a release the way Components does: `/usr/libexec/dawnline/updater install app@vX.Y.Z` (verified against the release's sha256).
|
||||
@@ -1,133 +1,397 @@
|
||||
# Dawnline
|
||||
<div align="center">
|
||||
|
||||
[](https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml)
|
||||
[](https://github.com/tickcount/luci-app-dawnline/actions/workflows/build.yml)
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
|
||||
<img alt="Dawnline" src="docs/assets/logo-light.svg" width="88" height="88">
|
||||
</picture>
|
||||
|
||||
Your OpenWrt router as a private VPN for the people you choose.
|
||||
<h1>Dawnline</h1>
|
||||
|
||||
Dawnline runs an [AmneziaWG](https://docs.amnezia.org/) server on the router
|
||||
and gives every person a personal link. They open it, add their own devices
|
||||
(up to the limit you set) and connect with AmneziaVPN or AmneziaWG. You decide
|
||||
what each person may reach: the home network, the internet, or both.
|
||||
**Your OpenWrt router as a private VPN for the people you choose.**
|
||||
|
||||
Dawnline is the successor of [Liminal](https://github.com/tickcount/openwrt-liminal):
|
||||
the same idea rebuilt around people instead of peers, with a personal portal,
|
||||
limits, live traffic and a LuCI admin that follows a modern design.
|
||||
<a href="https://github.com/tickcount/luci-app-dawnline/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Latest release" src="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||
<a href="https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="CI" src="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||
<a href="https://github.com/tickcount/luci-app-dawnline/releases"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Downloads" src="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||
<a href="LICENSE"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="License" src="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||
<br>
|
||||
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 24.10" src="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
|
||||
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 25.12" src="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
|
||||
<a href="https://docs.amnezia.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=dark"><img alt="AmneziaWG 2.0 and 3.1" src="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=light"></picture></a>
|
||||
|
||||

|
||||
[**Quick start**](#-quick-start) · [**Live demo**](https://dawnline-demo.vercel.app) · [Features](#-features) · [How it works](#-how-it-works) · [Screenshots](#-a-closer-look) · [FAQ](#-faq) · [Development](#-development)
|
||||
|
||||
| People | A person |
|
||||
**English** · [Русский](README_ru.md)
|
||||
|
||||
</div>
|
||||
|
||||
<br>
|
||||
|
||||
Dawnline runs an [AmneziaWG] server on your OpenWrt router and gives every
|
||||
person you invite **a personal link**. They open it, **add their own phones and
|
||||
computers** and connect with AmneziaVPN, AmneziaWG or WireGuard. You decide
|
||||
**what each of them may reach** (the home network, the internet, or both) and
|
||||
**for how long, how much and when**.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal.png" alt="The personal portal: devices and access, and adding a phone in three steps" width="860"></a>
|
||||
<br>
|
||||
<sub>A person's own page: their devices and access. Adding a phone takes three steps, and the page sees it connect.
|
||||
<a href="https://dawnline-demo.vercel.app"><b>Try it in the live demo</b></a>: nothing installs and nothing connects.</sub>
|
||||
</p>
|
||||
|
||||
## 💡 Why Dawnline?
|
||||
|
||||
Sharing a home VPN usually means making a config file by hand, sending it over
|
||||
a messenger and hoping nobody shares it further. Dawnline turns that around:
|
||||
|
||||
| | A VPN by hand | With Dawnline |
|
||||
|---|---|---|
|
||||
| **Setting up a device** | You make a config and send it | They add it themselves from their link |
|
||||
| **Who can do what** | Everyone gets the same | Home, internet or both, per person |
|
||||
| **Ending access** | Find and delete their peers | A date, a data limit, or one click |
|
||||
| **Knowing what goes on** | Read `wg show` | Who is online, traffic, places, a log |
|
||||
| **When something breaks** | You find out from them | A watchdog notices and repairs it |
|
||||
|
||||
It is the successor of [Liminal]: the same idea rebuilt around people instead
|
||||
of peers, with a personal portal, limits, live traffic and a LuCI admin that
|
||||
follows a modern design.
|
||||
|
||||
## 🚀 Quick start
|
||||
|
||||
1. **Install** on the router (it asks before it changes anything):
|
||||
|
||||
```sh
|
||||
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
||||
```
|
||||
|
||||
2. **Set up** in LuCI: <kbd>Network</kbd> › <kbd>Dawnline</kbd>, and follow the
|
||||
wizard. It suggests the port, the public address and the networks.
|
||||
3. **Invite** someone: <kbd>Add person</kbd>, then send them the link or the
|
||||
invite card with its QR code. They do the rest.
|
||||
|
||||
> [!TIP]
|
||||
> Behind Cloudflare, give the portal a port Cloudflare proxies: 2053, 2083,
|
||||
> 2087, 2096 or 8443.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<h3>🔗 A link, not an account</h3>
|
||||
<p>Three words, like <code>vpn.example.com/kamiro-telosu-bavine</code>. The link is the key: no sign-up, no password, and a new link locks the old one out at once.</p>
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<h3>📱 Their own devices</h3>
|
||||
<p>People add, rename and remove devices up to their limit. Adding one walks them through it: the right app, then a QR code, a link, a key or a file.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>👥 People, not peers</h3>
|
||||
<p>One card per person with their devices, who is online, traffic, end date and data limit. Filter by who needs attention or is paused.</p>
|
||||
</td>
|
||||
<td valign="top">
|
||||
<h3>🧭 Who reaches what</h3>
|
||||
<p>The home network, the internet or both; only some networks or devices at home (a NAS, Home Assistant). Family sees family, guests see guests.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>⏳ Limits</h3>
|
||||
<p>End dates, monthly or total data limits, allowed hours, a pause button. Changes apply at once, without dropping anyone else's connection.</p>
|
||||
</td>
|
||||
<td valign="top">
|
||||
<h3>🕶️ Disguise</h3>
|
||||
<p>Presets that make the VPN traffic harder to spot and block, with what each one needs from the apps.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>🏠 Internet like a home device</h3>
|
||||
<p>Turn it on and people's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too. Off by default: it costs speed.</p>
|
||||
</td>
|
||||
<td valign="top">
|
||||
<h3>🗺️ Overview and places</h3>
|
||||
<p>Who is online with what, speed now, the last 30 days, and a map of where people connect from, at city level.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>🩺 Repairs itself</h3>
|
||||
<p>Health checks with one-click fixes, and a watchdog that checks the tunnels, access rules and portal every minute and mends them.</p>
|
||||
</td>
|
||||
<td valign="top">
|
||||
<h3>📦 Updates and backups</h3>
|
||||
<p>Dawnline and AmneziaWG built for your firmware in one place; nightly backups, and export and import to move to another router.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>🌐 English and Russian</h3>
|
||||
<p>The portal follows the visitor's language and switches in its header. The admin pages and the router's messages come in Russian with the <code>luci-i18n-dawnline-ru</code> package.</p>
|
||||
</td>
|
||||
<td valign="top"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 🧩 How it works
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
you(["🛠️ You, in LuCI"]) -- "add a person" --> link["🔗 Their link"]
|
||||
link -- "they open it" --> portal["📱 Their portal"]
|
||||
portal -- "add a device" --> app["App and connection"]
|
||||
app == "AmneziaWG tunnel" ==> router["🌅 Dawnline<br>on your router"]
|
||||
router -- "if allowed" --> home["🏠 Home network"]
|
||||
router -- "if allowed" --> net["🌍 Internet"]
|
||||
```
|
||||
|
||||
1. **You add a person** in LuCI and choose what they may reach, their device
|
||||
limit, an end date or a data limit.
|
||||
2. **They open their link** on any device. The portal is theirs alone: it shows
|
||||
their devices and their access; access and limits stay yours to change.
|
||||
3. **They add a device.** The portal points them to the app for that system and
|
||||
hands over the connection; the router gives each device its own keys.
|
||||
4. **The device connects** through the router's AmneziaWG server, and Dawnline
|
||||
lets through what that person may reach, counts their traffic and keeps to
|
||||
their limits.
|
||||
|
||||
## 📸 A closer look
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/screenshots/overview.png" alt="Overview: who is online, speed, the last 30 days and where people connect from" width="720">
|
||||
<br>
|
||||
<sub><b>Overview</b>: who is online, speed now, the last 30 days and a map of where people connect from.</sub>
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<img alt="People: everyone on the server, with their devices, data and state" src="docs/screenshots/people.png">
|
||||
<p align="center"><sub><b>People</b>: online, ending soon, over the limit, outside their hours, paused.</sub></p>
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<img alt="A person: their devices, traffic, places and limits" src="docs/screenshots/person.png">
|
||||
<p align="center"><sub><b>A person</b>: their devices, traffic, places and limits.</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 📋 Requirements
|
||||
|
||||
| | What Dawnline needs |
|
||||
|---|---|
|
||||
|  |  |
|
||||
| **OpenWrt** | 24.10 (opkg, `.ipk`) or 25.12 (apk, `.apk`) |
|
||||
| **AmneziaWG** | `kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`: the installer adds a build made for your firmware when they are missing |
|
||||
| **Free flash** | about 2 MB |
|
||||
|
||||
| Personal portal | Where people connect from |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||
## Features
|
||||
|
||||
- **People, not peers.** One card per person with device chips, live status,
|
||||
traffic, end date and data limit. Add a person, send them the link or the
|
||||
invite card (QR code), and they do the rest.
|
||||
- **Personal portal.** Every person gets a link made of three words
|
||||
(`https://vpn.example.com/kamiro-telosu-bavine`). The link is the key: no
|
||||
accounts, no sessions, and a new link locks the old one out at once. People
|
||||
add, rename and remove their devices and get each one as a QR code,
|
||||
"Open in AmneziaVPN" (`vpn://`), a key or a `.conf` file. They cannot change
|
||||
access or limits. Links work on 443 with a Let's Encrypt certificate (via
|
||||
ACME), several addresses at once (a Cloudflare-proxied name, a plain IP), the
|
||||
same link at home, and wrong links can redirect to your website.
|
||||
- **Access per person**, enforced in an `inet dawnline` nftables table on the
|
||||
tunnel interface: home network only, internet only, or both, and optionally
|
||||
only some home services.
|
||||
- **Limits.** End dates (pause, keep, or remove devices when they pass), monthly
|
||||
or total data limits, allowed hours, pause one person or everyone. Devices
|
||||
drop off the tunnel at once (`awg syncconf`, no interface restart).
|
||||
- **Disguise presets** for AmneziaWG obfuscation (junk packets,
|
||||
header and padding parameters), with what each preset needs from the apps.
|
||||
- **Internet like a home device.** Tunnel clients' internet traffic enters the
|
||||
router from the LAN, through a small network namespace on the LAN bridge
|
||||
(needs `kmod-veth`). Whatever handles LAN traffic on the router (proxies, DPI
|
||||
bypass, DNS filters, the `lan` zone) handles VPN clients too, with no
|
||||
per-tool integration.
|
||||
- **Overview.** Who is online with what, speed now, today and the last 30 days,
|
||||
and a map of where people connect from (city level).
|
||||
- **Health** checks with one-click fixes, including the ones that matter for
|
||||
reaching the portal from outside (DNS, port forwards, reply routing behind
|
||||
proxies such as SSClash/Mihomo, certificate coverage).
|
||||
- **Updates.** Dawnline itself, AmneziaWG builds for your firmware (choose
|
||||
between [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt)
|
||||
and [2Grey](https://github.com/2Grey/awg-openwrt), AmneziaWG 2.0 or 3.1), and
|
||||
the few OpenWrt packages Dawnline adds.
|
||||
- **Backups** nightly and before risky operations, JSON export/import to move
|
||||
to another router.
|
||||
|
||||
## Requirements
|
||||
|
||||
- OpenWrt **24.10** (opkg, `.ipk`) or **25.12** (apk, `.apk`)
|
||||
- AmneziaWG (`kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`):
|
||||
the installer adds a build made for your firmware when it is missing
|
||||
- About 2 MB of free flash
|
||||
|
||||
## Install
|
||||
|
||||
On the router:
|
||||
## 📥 Install
|
||||
|
||||
```sh
|
||||
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
||||
```
|
||||
|
||||
The installer checks the firmware, installs AmneziaWG for it if needed, then
|
||||
downloads the Dawnline package for your package manager from the latest
|
||||
release, checks it against `sha256sums.txt` and installs it with its
|
||||
dependencies. Then open **LuCI → Network → Dawnline** and run the setup wizard.
|
||||
The installer checks the firmware, the clock, free space and DNS, lets you pick
|
||||
a release (the latest is the default), shows the plan and asks before it
|
||||
changes anything. It downloads the package for your package manager, checks it
|
||||
against `sha256sums.txt`, installs AmneziaWG built for your firmware if it is
|
||||
missing, then installs Dawnline (with its Russian translation when LuCI is in
|
||||
Russian) and checks that LuCI can reach it.
|
||||
|
||||
Options:
|
||||
> [!NOTE]
|
||||
> Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
|
||||
> and the service state to `/etc/dawnline/installer-backups/` (the newest three
|
||||
> are kept), and puts them back if a step fails. Packages are not rolled back:
|
||||
> to return to an older release, run the installer with `--tag`. Everything it
|
||||
> does is logged to `/tmp/dawnline-install.log`.
|
||||
|
||||
<details>
|
||||
<summary><b>Installer options</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
With options, download it first:
|
||||
|
||||
```sh
|
||||
sh install.sh 0.1.0 # a given release
|
||||
DAWNLINE_AWG=grey sh install.sh # AmneziaWG from 2Grey (default: Slava-Shchipunov, then 2Grey)
|
||||
DAWNLINE_AWG=skip sh install.sh # never install AmneziaWG
|
||||
wget -O /tmp/dawnline-install.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh
|
||||
sh /tmp/dawnline-install.sh --dry-run # check everything, change nothing
|
||||
sh /tmp/dawnline-install.sh -y --tag 0.3.1 # a given release, no questions
|
||||
sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey
|
||||
sh /tmp/dawnline-install.sh --lang ru # with the admin's Russian translation
|
||||
```
|
||||
|
||||
By hand, from a [release](https://github.com/tickcount/luci-app-dawnline/releases):
|
||||
| Option | |
|
||||
|---|---|
|
||||
| `-y`, `--yes` | No questions: the latest release (or `--tag`) and the recommended choices |
|
||||
| `-n`, `--dry-run` | Check the system, resolve, download and verify the release; change nothing |
|
||||
| `-v`, `--verbose` / `-q`, `--quiet` | More detail / only warnings and errors |
|
||||
| `--tag X.Y.Z` | A given release (`sh install.sh 0.3.1` works too) |
|
||||
| `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov], then [2Grey] (`auto`, the default), only one of them, or not at all (install it later from **Dawnline → Components**). `DAWNLINE_AWG` does the same |
|
||||
| `--no-awg` | Same as `--awg skip` |
|
||||
| `--lang auto\|ru\|none` | The admin's translation, `luci-i18n-dawnline-<lang>`: `auto` (the default) adds it when LuCI is set to that language or has its LuCI translation; `none` adds none. An installed one is always kept up to date. Later: **Dawnline → Components → Translation**. `DAWNLINE_LANG` does the same |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>When GitHub is slow or blocked</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
The installer retries downloads through `ghfast.top` and `gh-proxy.com` on its
|
||||
own. To fetch the installer itself through a mirror:
|
||||
|
||||
```sh
|
||||
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)"
|
||||
sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Installing by hand</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
From a [release](https://github.com/tickcount/luci-app-dawnline/releases):
|
||||
|
||||
```sh
|
||||
opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10
|
||||
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
|
||||
```
|
||||
|
||||
**Upgrade** from **Dawnline → Updates**, or run the installer again. Settings,
|
||||
keys and history are kept, and a backup is made first.
|
||||
The Russian translation is `luci-i18n-dawnline-ru-<version>` from the same
|
||||
release, installed the same way after the app (then `/etc/init.d/uhttpd restart`).
|
||||
|
||||
**Remove**: **Settings → Remove Dawnline from this router** (keeps a backup),
|
||||
then `opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`.
|
||||
</details>
|
||||
|
||||
## What Dawnline changes on the router
|
||||
**Upgrade** from <kbd>Dawnline</kbd> › <kbd>Components</kbd>, or run the installer
|
||||
again. Settings, keys and history are kept, and a backup is made first.
|
||||
|
||||
### Remove
|
||||
|
||||
```sh
|
||||
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
|
||||
```
|
||||
|
||||
It backs up the configuration to `/etc/dawnline/backups`, runs Dawnline's own
|
||||
removal (the same as <kbd>Settings</kbd> › <kbd>Remove Dawnline from this router</kbd>),
|
||||
removes the package and cleans up what is left. After installing Dawnline
|
||||
again, restore the backup in <kbd>Settings</kbd> › <kbd>Backups</kbd>.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> AmneziaWG stays installed, since other tunnels may use it. Add `--remove-awg`
|
||||
> to take it away too.
|
||||
|
||||
<details>
|
||||
<summary><b>Uninstaller options</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
With options, download it first:
|
||||
|
||||
```sh
|
||||
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
|
||||
sh /tmp/dawnline-uninstall.sh --dry-run
|
||||
```
|
||||
|
||||
| Option | |
|
||||
|---|---|
|
||||
| `-y`, `--yes` | Do not ask for confirmation |
|
||||
| `-p`, `--purge` | Also delete the configuration, keys, history and every backup (`/etc/config/dawnline`, `/etc/dawnline`); no backup is made |
|
||||
| `--remove-awg` | Also remove AmneziaWG, unless another interface still uses it (`--keep-awg`, the default, keeps it) |
|
||||
| `-n`, `--dry-run` | Show what would be removed; change nothing |
|
||||
|
||||
By hand: <kbd>Settings</kbd> › <kbd>Remove Dawnline from this router</kbd>
|
||||
(keeps a backup), then `opkg remove luci-app-dawnline` or
|
||||
`apk del luci-app-dawnline`.
|
||||
|
||||
</details>
|
||||
|
||||
## ❓ FAQ
|
||||
|
||||
<details>
|
||||
<summary><b>Which apps do people use?</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
AmneziaVPN or AmneziaWG on phones and computers, and plain WireGuard when the
|
||||
disguise is off. The portal shows each person the app for their system and how
|
||||
to add the connection in it.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>What happens when someone loses their link?</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
Make a new one on their page. The old link stops working at once; their devices
|
||||
keep working, unless you tick the ones to remove with it.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Does it touch the rest of my router?</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
Only what it created, and `dawnline teardown` removes all of it. The full list
|
||||
is under [What Dawnline changes on the router](#-what-dawnline-changes-on-the-router).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>How do I move to another router?</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
<kbd>Export JSON</kbd> in <kbd>Settings</kbd> › <kbd>Backups</kbd> on the old
|
||||
one, install Dawnline on the new one and import the file there.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Where do the places on the map come from?</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
From the address a device connects from, looked up at city level and cached on
|
||||
the router. It can be turned off in <kbd>Settings</kbd>.
|
||||
|
||||
</details>
|
||||
|
||||
## 🧾 What Dawnline changes on the router
|
||||
|
||||
Only objects it created: network interfaces tagged `_dawnline`, firewall
|
||||
sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline`,
|
||||
the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the
|
||||
latter a port of the LAN bridge), policy rules for the tunnel interfaces with
|
||||
one routing table, a second dnsmasq instance on port 5354
|
||||
(`/var/etc/dawnline-dns.conf`) and, while the portal is on, a uhttpd instance
|
||||
for it. `dawnline teardown` removes all of them.
|
||||
latter a port of the LAN bridge, which needs `kmod-veth`), policy rules for the
|
||||
tunnel interfaces with one routing table, a second dnsmasq instance on port
|
||||
5354 (`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat
|
||||
check and, while the portal is on, a uhttpd instance for it.
|
||||
`dawnline teardown` removes all of them.
|
||||
|
||||
Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and
|
||||
`/etc/dawnline/` (usage, events, issued configurations, backups). Live counters
|
||||
are kept in `/var/run/dawnline` and flushed to flash at most hourly.
|
||||
are kept in `/var/run/dawnline` and flushed to flash at most hourly. Access
|
||||
changes reach the tunnel with `awg syncconf`, without restarting the interface;
|
||||
`dawnline log` on the router shows the service log.
|
||||
|
||||
## Development
|
||||
## 🧰 Development
|
||||
|
||||
```
|
||||
package/luci-app-dawnline/
|
||||
root/usr/share/ucode/dawnline/ ucode library (model, apply, live, ops, view, loop)
|
||||
root/usr/share/ucode/dawnline/ ucode library: model (core), AmneziaWG (awg), apply, live,
|
||||
ops, view, loop, portal
|
||||
root/usr/share/rpcd/ucode/ luci.dawnline RPC object
|
||||
root/usr/libexec/dawnline/ agent (usage, limits, presence) and updater
|
||||
root/usr/share/dawnline/portal/ portal CGI and its (minified) assets
|
||||
root/usr/share/dawnline/portal/ portal CGI wrapper and its (minified) assets
|
||||
root/usr/bin/dawnline command line (`dawnline help`)
|
||||
htdocs/ LuCI views and the generated module dawnline/app.js
|
||||
po/ the admin's string catalog (dawnline.pot, ru/dawnline.po)
|
||||
web/ TypeScript sources of the admin UI and the portal
|
||||
web/i18n/ catalog tools: collect strings, merge .po files, compile .lmo
|
||||
build/Dockerfile package build with the OpenWrt SDK
|
||||
scripts/ build, deploy and check scripts
|
||||
```
|
||||
@@ -136,19 +400,30 @@ scripts/ build, deploy and check scripts
|
||||
cd web
|
||||
npm ci
|
||||
npm run format # Prettier
|
||||
npm run ci # format check, types, tests, minified bundles
|
||||
npm run ci # format check, types, catalogs, tests, minified bundles
|
||||
npm run i18n # collect new strings into the catalogs (then translate them in ru.po)
|
||||
|
||||
scripts/lint-ucode.py # static ucode checks
|
||||
scripts/check-ucode.sh root@router # compile every ucode file on a router
|
||||
scripts/deploy.sh root@router # install the working tree (backs up configs first)
|
||||
scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
|
||||
scripts/frame-screenshots.py # frame docs/screenshots/raw/*.png for this README
|
||||
scripts/lint-ucode.py # static ucode checks
|
||||
scripts/check-ucode.sh root@router # compile every ucode file on a router
|
||||
scripts/deploy.sh root@router # install the working tree (backs up configs first)
|
||||
scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
|
||||
scripts/capture-screenshots.mjs --demo # the admin's README screenshots from a router, a demo cast in place of its people
|
||||
scripts/capture-portal.mjs # the portal's from its demo, in English and Russian
|
||||
scripts/frame-screenshots.py # frame them for this README
|
||||
```
|
||||
|
||||
The web bundles are committed: CI fails when they are out of date. Pushing a
|
||||
tag `vX.Y.Z` (matching `PKG_VERSION`) builds both packages with the OpenWrt SDK
|
||||
and publishes a release with `sha256sums.txt`.
|
||||
The web bundles and the catalogs are committed: CI fails when they are out of
|
||||
date or a string is untranslated (`rules/i18n.md`). Pushing a tag `vX.Y.Z`
|
||||
(matching `PKG_VERSION`) builds the packages and their translations with the
|
||||
OpenWrt SDK and publishes a release with `sha256sums.txt`.
|
||||
|
||||
## License
|
||||
---
|
||||
|
||||
[MIT](LICENSE)
|
||||
<div align="center">
|
||||
<sub>Made for OpenWrt · <a href="LICENSE">MIT license</a> · <a href="#readme">Back to top ↑</a></sub>
|
||||
</div>
|
||||
|
||||
[AmneziaWG]: https://docs.amnezia.org/
|
||||
[Liminal]: https://github.com/tickcount/openwrt-liminal
|
||||
[Slava-Shchipunov]: https://github.com/Slava-Shchipunov/awg-openwrt
|
||||
[2Grey]: https://github.com/2Grey/awg-openwrt
|
||||
@@ -0,0 +1,432 @@
|
||||
<div align="center">
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
|
||||
<img alt="Dawnline" src="docs/assets/logo-light.svg" width="88" height="88">
|
||||
</picture>
|
||||
|
||||
<h1>Dawnline</h1>
|
||||
|
||||
**Ваш роутер на OpenWrt как личный VPN для тех, кого вы выберете.**
|
||||
|
||||
<a href="https://github.com/tickcount/luci-app-dawnline/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Последний релиз" src="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||
<a href="https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="CI" src="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||
<a href="https://github.com/tickcount/luci-app-dawnline/releases"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Загрузки" src="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||
<a href="LICENSE"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Лицензия" src="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||
<br>
|
||||
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 24.10" src="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
|
||||
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 25.12" src="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
|
||||
<a href="https://docs.amnezia.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=dark"><img alt="AmneziaWG 2.0 и 3.1" src="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=light"></picture></a>
|
||||
|
||||
[**Быстрый старт**](#-быстрый-старт) · [**Демо**](https://dawnline-demo.vercel.app) · [Возможности](#-возможности) · [Как это работает](#-как-это-работает) · [Скриншоты](#-как-это-выглядит) · [Вопросы](#-вопросы-и-ответы) · [Разработка](#-разработка)
|
||||
|
||||
[English](README.md) · **Русский**
|
||||
|
||||
</div>
|
||||
|
||||
<br>
|
||||
|
||||
Dawnline запускает сервер [AmneziaWG] на вашем роутере с OpenWrt и даёт каждому,
|
||||
кого вы пригласите, **личную ссылку**. По ней человек **сам добавляет свои
|
||||
телефоны и компьютеры** и подключается через AmneziaVPN, AmneziaWG или WireGuard.
|
||||
Вы решаете, **что ему доступно** (домашняя сеть, интернет или и то и другое), и
|
||||
**на какой срок, сколько трафика и в какие часы**.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal-ru.png" alt="Личный портал: устройства и доступ, добавление телефона в три шага" width="860"></a>
|
||||
<br>
|
||||
<sub>Личная страница человека: его устройства и доступ. Телефон добавляется в три шага, и страница видит, когда он подключился.
|
||||
<a href="https://dawnline-demo.vercel.app"><b>Попробуйте в демо</b></a>: ничего не устанавливается и никуда не подключается.</sub>
|
||||
</p>
|
||||
|
||||
## 💡 Почему Dawnline?
|
||||
|
||||
Обычно, чтобы поделиться домашним VPN, приходится вручную делать файл
|
||||
конфигурации, отправлять его в мессенджере и надеяться, что дальше он никуда не
|
||||
уйдёт. Dawnline делает наоборот:
|
||||
|
||||
| | VPN вручную | С Dawnline |
|
||||
|---|---|---|
|
||||
| **Настройка устройства** | Вы делаете конфиг и отправляете его | Человек добавляет устройство сам по своей ссылке |
|
||||
| **Кому что можно** | Всем одно и то же | Дом, интернет или и то и другое, для каждого своё |
|
||||
| **Конец доступа** | Найти и удалить его пиры | Дата, лимит трафика или один клик |
|
||||
| **Что происходит** | Читать `wg show` | Кто в сети, трафик, места, журнал |
|
||||
| **Когда что-то ломается** | Узнаёте от людей | Автовосстановление замечает и чинит |
|
||||
|
||||
Это преемник [Liminal]: та же идея, перестроенная вокруг людей, а не пиров, с
|
||||
личным порталом, лимитами, трафиком в реальном времени и современной админкой
|
||||
в LuCI.
|
||||
|
||||
## 🚀 Быстрый старт
|
||||
|
||||
1. **Установите** на роутер (установщик спрашивает, прежде чем что-то менять):
|
||||
|
||||
```sh
|
||||
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
||||
```
|
||||
|
||||
2. **Настройте** в LuCI: <kbd>Network</kbd> › <kbd>Dawnline</kbd>, дальше по
|
||||
мастеру. Он предложит порт, публичный адрес и сети.
|
||||
3. **Пригласите** человека: <kbd>Добавить человека</kbd>, затем отправьте ему
|
||||
ссылку или карточку приглашения с QR-кодом. Остальное он сделает сам.
|
||||
|
||||
> [!TIP]
|
||||
> Если портал за Cloudflare, дайте ему порт, который Cloudflare проксирует:
|
||||
> 2053, 2083, 2087, 2096 или 8443.
|
||||
|
||||
## ✨ Возможности
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<h3>🔗 Ссылка вместо аккаунта</h3>
|
||||
<p>Три слова, например <code>vpn.example.com/kamiro-telosu-bavine</code>. Ссылка и есть ключ: без регистрации и пароля, а новая ссылка сразу отключает старую.</p>
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<h3>📱 Свои устройства</h3>
|
||||
<p>Люди сами добавляют, переименовывают и удаляют устройства в пределах лимита. При добавлении портал ведёт по шагам: нужное приложение, затем QR-код, ссылка, ключ или файл.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>👥 Люди, а не пиры</h3>
|
||||
<p>Карточка на каждого человека: устройства, кто в сети, трафик, дата окончания и лимит. Фильтры по тем, кто требует внимания или на паузе.</p>
|
||||
</td>
|
||||
<td valign="top">
|
||||
<h3>🧭 Кому что доступно</h3>
|
||||
<p>Домашняя сеть, интернет или и то и другое; только часть домашних сетей или устройств (NAS, Home Assistant). Семья видит семью, гости видят гостей.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>⏳ Лимиты</h3>
|
||||
<p>Даты окончания, лимит трафика на месяц или за всё время, часы доступа, кнопка паузы. Изменения применяются сразу и не обрывают подключения остальных.</p>
|
||||
</td>
|
||||
<td valign="top">
|
||||
<h3>🕶️ Маскировка</h3>
|
||||
<p>Пресеты, которые мешают распознать и заблокировать VPN-трафик, и что каждый из них требует от приложений.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>🏠 Интернет как у домашних устройств</h3>
|
||||
<p>Включите, и устройства людей выйдут в интернет так же, как домашние: ваши прокси, фильтры рекламы и DNS сработают и для них. По умолчанию выключено: это стоит скорости.</p>
|
||||
</td>
|
||||
<td valign="top">
|
||||
<h3>🗺️ Обзор и места</h3>
|
||||
<p>Кто в сети и с чего, скорость сейчас, последние 30 дней и карта, откуда подключаются, с точностью до города.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>🩺 Чинит себя сам</h3>
|
||||
<p>Проверки состояния с исправлением в один клик и автовосстановление, которое каждую минуту проверяет туннели, правила доступа и портал и чинит их.</p>
|
||||
</td>
|
||||
<td valign="top">
|
||||
<h3>📦 Обновления и резервные копии</h3>
|
||||
<p>Dawnline и AmneziaWG, собранный под вашу прошивку, в одном месте; ночные резервные копии, экспорт и импорт для переезда на другой роутер.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>🌐 Английский и русский</h3>
|
||||
<p>Портал подстраивается под язык посетителя и переключается в шапке. Админка и сообщения роутера на русском с пакетом <code>luci-i18n-dawnline-ru</code>.</p>
|
||||
</td>
|
||||
<td valign="top"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 🧩 Как это работает
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
you(["🛠️ Вы, в LuCI"]) -- "добавляете человека" --> link["🔗 Его ссылка"]
|
||||
link -- "он открывает её" --> portal["📱 Его портал"]
|
||||
portal -- "добавляет устройство" --> app["Приложение и подключение"]
|
||||
app == "туннель AmneziaWG" ==> router["🌅 Dawnline<br>на вашем роутере"]
|
||||
router -- "если разрешено" --> home["🏠 Домашняя сеть"]
|
||||
router -- "если разрешено" --> net["🌍 Интернет"]
|
||||
```
|
||||
|
||||
1. **Вы добавляете человека** в LuCI и выбираете, что ему доступно, лимит
|
||||
устройств, дату окончания или лимит трафика.
|
||||
2. **Он открывает свою ссылку** на любом устройстве. Портал только его: там его
|
||||
устройства и его доступ; доступ и лимиты меняете только вы.
|
||||
3. **Он добавляет устройство.** Портал подсказывает приложение для его системы и
|
||||
передаёт подключение; роутер выдаёт каждому устройству свои ключи.
|
||||
4. **Устройство подключается** через сервер AmneziaWG на роутере, а Dawnline
|
||||
пропускает только то, что доступно этому человеку, считает его трафик и
|
||||
следит за лимитами.
|
||||
|
||||
## 📸 Как это выглядит
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/screenshots/overview-ru.png" alt="Обзор: кто в сети, скорость, последние 30 дней и откуда подключаются" width="720">
|
||||
<br>
|
||||
<sub><b>Обзор</b>: кто в сети, скорость сейчас, последние 30 дней и карта, откуда подключаются.</sub>
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<img alt="Люди: все на сервере, с устройствами, трафиком и состоянием" src="docs/screenshots/people-ru.png">
|
||||
<p align="center"><sub><b>Люди</b>: в сети, доступ скоро закончится, сверх лимита, вне часов доступа, на паузе.</sub></p>
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<img alt="Человек: его устройства, трафик, места и лимиты" src="docs/screenshots/person-ru.png">
|
||||
<p align="center"><sub><b>Человек</b>: его устройства, трафик, места и лимиты.</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 📋 Требования
|
||||
|
||||
| | Что нужно Dawnline |
|
||||
|---|---|
|
||||
| **OpenWrt** | 24.10 (opkg, `.ipk`) или 25.12 (apk, `.apk`) |
|
||||
| **AmneziaWG** | `kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`: если их нет, установщик поставит сборку для вашей прошивки |
|
||||
| **Свободная флеш-память** | около 2 МБ |
|
||||
|
||||
## 📥 Установка
|
||||
|
||||
```sh
|
||||
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
||||
```
|
||||
|
||||
Установщик проверяет прошивку, часы, свободное место и DNS, даёт выбрать релиз
|
||||
(по умолчанию последний), показывает план и спрашивает, прежде чем что-то
|
||||
менять. Он скачивает пакет для вашего менеджера пакетов, сверяет его с
|
||||
`sha256sums.txt`, ставит AmneziaWG для вашей прошивки, если его нет, затем
|
||||
ставит Dawnline (с русским переводом, если LuCI на русском) и проверяет, что
|
||||
LuCI его видит.
|
||||
|
||||
> [!NOTE]
|
||||
> Прежде чем что-то менять, он сохраняет `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
|
||||
> и состояние служб в `/etc/dawnline/installer-backups/` (хранятся три последние
|
||||
> копии) и возвращает их, если какой-то шаг не удался. Пакеты не откатываются:
|
||||
> чтобы вернуться к старому релизу, запустите установщик с `--tag`. Всё, что он
|
||||
> делает, записывается в `/tmp/dawnline-install.log`.
|
||||
|
||||
<details>
|
||||
<summary><b>Параметры установщика</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
С параметрами его нужно сначала скачать:
|
||||
|
||||
```sh
|
||||
wget -O /tmp/dawnline-install.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh
|
||||
sh /tmp/dawnline-install.sh --dry-run # всё проверить, ничего не менять
|
||||
sh /tmp/dawnline-install.sh -y --tag 0.3.1 # конкретный релиз, без вопросов
|
||||
sh /tmp/dawnline-install.sh --awg grey # AmneziaWG от 2Grey
|
||||
sh /tmp/dawnline-install.sh --lang ru # с русским переводом админки
|
||||
```
|
||||
|
||||
| Параметр | |
|
||||
|---|---|
|
||||
| `-y`, `--yes` | Без вопросов: последний релиз (или `--tag`) и рекомендуемые варианты |
|
||||
| `-n`, `--dry-run` | Проверить систему, найти, скачать и проверить релиз; ничего не менять |
|
||||
| `-v`, `--verbose` / `-q`, `--quiet` | Подробнее / только предупреждения и ошибки |
|
||||
| `--tag X.Y.Z` | Конкретный релиз (`sh install.sh 0.3.1` тоже работает) |
|
||||
| `--awg auto\|slava\|grey\|skip` | Откуда брать AmneziaWG, если его нет: [Slava-Shchipunov], затем [2Grey] (`auto`, по умолчанию), только один из них или вообще не ставить (потом можно в **Dawnline → Компоненты**). То же самое делает `DAWNLINE_AWG` |
|
||||
| `--no-awg` | То же, что `--awg skip` |
|
||||
| `--lang auto\|ru\|none` | Перевод админки, `luci-i18n-dawnline-<язык>`: `auto` (по умолчанию) ставит его, если LuCI настроен на этот язык или в нём стоит перевод LuCI на него; `none` не ставит. Уже установленный перевод всегда обновляется вместе с Dawnline. Позже: **Dawnline → Компоненты → Перевод**. То же самое делает `DAWNLINE_LANG` |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Если GitHub медленный или заблокирован</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
Установщик сам повторяет загрузки через `ghfast.top` и `gh-proxy.com`. Чтобы
|
||||
скачать сам установщик через зеркало:
|
||||
|
||||
```sh
|
||||
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)"
|
||||
sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Установка вручную</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
Из [релиза](https://github.com/tickcount/luci-app-dawnline/releases):
|
||||
|
||||
```sh
|
||||
opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10
|
||||
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
|
||||
```
|
||||
|
||||
Русский перевод: `luci-i18n-dawnline-ru-<версия>` из того же релиза, ставится
|
||||
так же, после приложения (затем `/etc/init.d/uhttpd restart`).
|
||||
|
||||
</details>
|
||||
|
||||
**Обновление**: в <kbd>Dawnline</kbd> › <kbd>Компоненты</kbd> или повторным
|
||||
запуском установщика. Настройки, ключи и история сохраняются, перед обновлением
|
||||
делается резервная копия.
|
||||
|
||||
### Удаление
|
||||
|
||||
```sh
|
||||
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
|
||||
```
|
||||
|
||||
Деинсталлятор сохраняет конфигурацию в `/etc/dawnline/backups`, запускает
|
||||
удаление средствами самого Dawnline (как <kbd>Настройки</kbd> › <kbd>Удалить
|
||||
Dawnline с этого роутера</kbd>), удаляет пакет и подчищает остатки. После
|
||||
повторной установки Dawnline восстановите копию в <kbd>Настройки</kbd> ›
|
||||
<kbd>Резервные копии</kbd>.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> AmneziaWG остаётся установленным: его могут использовать другие туннели.
|
||||
> Чтобы удалить и его, добавьте `--remove-awg`.
|
||||
|
||||
<details>
|
||||
<summary><b>Параметры деинсталлятора</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
С параметрами его нужно сначала скачать:
|
||||
|
||||
```sh
|
||||
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
|
||||
sh /tmp/dawnline-uninstall.sh --dry-run
|
||||
```
|
||||
|
||||
| Параметр | |
|
||||
|---|---|
|
||||
| `-y`, `--yes` | Не спрашивать подтверждения |
|
||||
| `-p`, `--purge` | Удалить также конфигурацию, ключи, историю и все резервные копии (`/etc/config/dawnline`, `/etc/dawnline`); копия не делается |
|
||||
| `--remove-awg` | Удалить также AmneziaWG, если его не использует другой интерфейс (`--keep-awg`, по умолчанию, оставляет его) |
|
||||
| `-n`, `--dry-run` | Показать, что будет удалено; ничего не менять |
|
||||
|
||||
Вручную: <kbd>Настройки</kbd> › <kbd>Удалить Dawnline с этого роутера</kbd>
|
||||
(резервная копия сохраняется), затем `opkg remove luci-app-dawnline` или
|
||||
`apk del luci-app-dawnline`.
|
||||
|
||||
</details>
|
||||
|
||||
## ❓ Вопросы и ответы
|
||||
|
||||
<details>
|
||||
<summary><b>Какими приложениями пользуются люди?</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
AmneziaVPN или AmneziaWG на телефонах и компьютерах, а обычный WireGuard, если
|
||||
маскировка выключена. Портал показывает каждому приложение для его системы и
|
||||
как добавить в нём подключение.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Что делать, если человек потерял ссылку?</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
Создайте новую на его странице. Старая ссылка сразу перестанет работать; его
|
||||
устройства продолжат работать, если не отметить те, что нужно удалить вместе с
|
||||
ней.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Затрагивает ли он остальной роутер?</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
Только то, что создал сам, и `dawnline teardown` убирает всё это. Полный список:
|
||||
[Что Dawnline меняет на роутере](#-что-dawnline-меняет-на-роутере).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Как переехать на другой роутер?</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
<kbd>Экспорт JSON</kbd> в <kbd>Настройки</kbd> › <kbd>Резервные копии</kbd> на
|
||||
старом роутере, установите Dawnline на новый и импортируйте там этот файл.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Откуда берутся места на карте?</b></summary>
|
||||
|
||||
<br>
|
||||
|
||||
Из адреса, с которого подключается устройство: город определяется по нему и
|
||||
кешируется на роутере. Это можно выключить в <kbd>Настройках</kbd>.
|
||||
|
||||
</details>
|
||||
|
||||
## 🧾 Что Dawnline меняет на роутере
|
||||
|
||||
Только то, что создал сам: сетевые интерфейсы с меткой `_dawnline`, секции
|
||||
межсетевого экрана `dawnline_*`, таблицу nft `inet dawnline`, `/tmp/hosts/dawnline`,
|
||||
сетевое пространство имён `dawnline` с двумя veth-связями (`dlx0` и `dll0`,
|
||||
вторая подключена к мосту LAN и требует `kmod-veth`), правила маршрутизации для
|
||||
интерфейсов туннелей с одной таблицей маршрутизации, второй экземпляр dnsmasq на
|
||||
порту 5354 (`/var/etc/dawnline-dns.conf`), строку cron для проверки пульса
|
||||
агента и, пока портал включён, экземпляр uhttpd для него. `dawnline teardown`
|
||||
убирает всё это.
|
||||
|
||||
Данные хранятся в `/etc/config/dawnline` (права 0600, там приватные ключи) и в
|
||||
`/etc/dawnline/` (трафик, события, выданные конфигурации, резервные копии).
|
||||
Текущие счётчики живут в `/var/run/dawnline` и записываются во флеш-память не
|
||||
чаще раза в час. Изменения доступа доходят до туннеля через `awg syncconf`, без
|
||||
перезапуска интерфейса; `dawnline log` на роутере показывает журнал служб.
|
||||
|
||||
## 🧰 Разработка
|
||||
|
||||
```
|
||||
package/luci-app-dawnline/
|
||||
root/usr/share/ucode/dawnline/ библиотека на ucode: модель (core), AmneziaWG (awg), apply, live,
|
||||
ops, view, loop, portal
|
||||
root/usr/share/rpcd/ucode/ объект RPC luci.dawnline
|
||||
root/usr/libexec/dawnline/ агент (трафик, лимиты, присутствие) и апдейтер
|
||||
root/usr/share/dawnline/portal/ CGI-обёртка портала и его (минифицированные) файлы
|
||||
root/usr/bin/dawnline командная строка (`dawnline help`)
|
||||
htdocs/ представления LuCI и сгенерированный модуль dawnline/app.js
|
||||
po/ каталог строк админки (dawnline.pot, ru/dawnline.po)
|
||||
web/ исходники админки и портала на TypeScript
|
||||
web/i18n/ инструменты каталогов: сбор строк, слияние .po, сборка .lmo
|
||||
build/Dockerfile сборка пакетов в OpenWrt SDK
|
||||
scripts/ скрипты сборки, деплоя и проверок
|
||||
```
|
||||
|
||||
```sh
|
||||
cd web
|
||||
npm ci
|
||||
npm run format # Prettier
|
||||
npm run ci # форматирование, типы, каталоги, тесты, минифицированные бандлы
|
||||
npm run i18n # собрать новые строки в каталоги (затем перевести их в ru.po)
|
||||
|
||||
scripts/lint-ucode.py # статические проверки ucode
|
||||
scripts/check-ucode.sh root@router # скомпилировать все файлы ucode на роутере
|
||||
scripts/deploy.sh root@router # поставить рабочую копию (сначала сохраняет конфиги)
|
||||
scripts/build-packages.sh all # .ipk и .apk в OpenWrt SDK в Docker
|
||||
scripts/capture-screenshots.mjs --demo # скриншоты админки для README с роутера, с демо-людьми вместо настоящих
|
||||
scripts/capture-portal.mjs # скриншоты портала для README из его демо, на английском и русском
|
||||
scripts/frame-screenshots.py # оформить их для README
|
||||
```
|
||||
|
||||
Бандлы и каталоги лежат в репозитории: CI падает, если они устарели или строка
|
||||
не переведена (`rules/i18n.md`). Тег `vX.Y.Z` (совпадающий с `PKG_VERSION`)
|
||||
собирает пакеты и переводы в OpenWrt SDK и публикует релиз с `sha256sums.txt`.
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<sub>Сделано для OpenWrt · <a href="LICENSE">лицензия MIT</a> · <a href="#readme">Наверх ↑</a></sub>
|
||||
</div>
|
||||
|
||||
[AmneziaWG]: https://docs.amnezia.org/
|
||||
[Liminal]: https://github.com/tickcount/openwrt-liminal
|
||||
[Slava-Shchipunov]: https://github.com/Slava-Shchipunov/awg-openwrt
|
||||
[2Grey]: https://github.com/2Grey/awg-openwrt
|
||||
@@ -9,13 +9,17 @@ COPY package/luci-app-dawnline /builder/package/feeds/luci/luci-app-dawnline
|
||||
|
||||
# The SDK's default config builds every kernel module and every package in the
|
||||
# feeds; turn that off and select only this package (it ships scripts and web
|
||||
# files, so nothing else needs building).
|
||||
# files, so nothing else needs building) and its translations: luci.mk makes
|
||||
# luci-i18n-dawnline-<lang> from po/<lang> when LuCI's language <lang> is selected.
|
||||
RUN make defconfig && \
|
||||
sed -i -e 's/^CONFIG_ALL_KMODS=y/# CONFIG_ALL_KMODS is not set/' \
|
||||
-e 's/^CONFIG_ALL_NONSHARED=y/# CONFIG_ALL_NONSHARED is not set/' \
|
||||
-e 's/^CONFIG_ALL=y/# CONFIG_ALL is not set/' .config && \
|
||||
echo 'CONFIG_PACKAGE_luci-app-dawnline=m' >> .config && \
|
||||
for l in $(ls /builder/package/feeds/luci/luci-app-dawnline/po | grep -v '^templates$'); do \
|
||||
sed -i "/CONFIG_LUCI_LANG_$l[= ]/d" .config && echo "CONFIG_LUCI_LANG_$l=y" >> .config; done && \
|
||||
make defconfig && \
|
||||
make package/luci-app-dawnline/compile V=s -j4 && \
|
||||
mkdir -p /builder/out && \
|
||||
find /builder/bin/packages -name 'luci-app-dawnline*' \( -name '*.ipk' -o -name '*.apk' \) -exec cp {} /builder/out/ \;
|
||||
find /builder/bin/packages \( -name 'luci-app-dawnline*' -o -name 'luci-i18n-dawnline-*' \) \
|
||||
\( -name '*.ipk' -o -name '*.apk' \) -exec cp {} /builder/out/ \;
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#ffffff"/><path d="M14 38a18 18 0 0 1 36 0z" fill="#0a0a0a"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#0a0a0a" fill-opacity=".5"/></svg>
|
||||
|
After Width: | Height: | Size: 254 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#0a0a0a"/><path d="M14 38a18 18 0 0 1 36 0z" fill="#ffffff"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#ffffff" fill-opacity=".5"/></svg>
|
||||
|
After Width: | Height: | Size: 254 B |
|
Before Width: | Height: | Size: 418 KiB |
|
After Width: | Height: | Size: 446 KiB |
|
Before Width: | Height: | Size: 277 KiB After Width: | Height: | Size: 457 KiB |
|
After Width: | Height: | Size: 419 KiB |
|
Before Width: | Height: | Size: 283 KiB After Width: | Height: | Size: 397 KiB |
|
After Width: | Height: | Size: 436 KiB |
|
Before Width: | Height: | Size: 301 KiB After Width: | Height: | Size: 430 KiB |
|
After Width: | Height: | Size: 403 KiB |
|
Before Width: | Height: | Size: 291 KiB After Width: | Height: | Size: 387 KiB |
|
Before Width: | Height: | Size: 328 KiB |
|
After Width: | Height: | Size: 423 KiB |
|
Before Width: | Height: | Size: 153 KiB After Width: | Height: | Size: 435 KiB |
|
After Width: | Height: | Size: 395 KiB |
|
Before Width: | Height: | Size: 159 KiB After Width: | Height: | Size: 373 KiB |
|
After Width: | Height: | Size: 412 KiB |
|
Before Width: | Height: | Size: 176 KiB After Width: | Height: | Size: 407 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 86 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 184 KiB |
|
Before Width: | Height: | Size: 169 KiB After Width: | Height: | Size: 186 KiB |
|
After Width: | Height: | Size: 214 KiB |
@@ -6,13 +6,16 @@
|
||||
include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=luci-app-dawnline
|
||||
PKG_VERSION:=0.1.1
|
||||
PKG_VERSION:=0.15.1
|
||||
PKG_RELEASE:=1
|
||||
PKG_LICENSE:=MIT
|
||||
# po/<lang>/dawnline.po becomes luci-i18n-dawnline-<lang> (luci.mk), released
|
||||
# with the app and at its version (luci.mk would take a git revision otherwise).
|
||||
PKG_PO_VERSION:=$(PKG_VERSION)-r$(PKG_RELEASE)
|
||||
|
||||
LUCI_TITLE:=Dawnline - AmneziaWG access server
|
||||
# AmneziaWG itself (kmod-amneziawg, amneziawg-tools, luci-proto-amneziawg) is not
|
||||
# in the OpenWrt feeds: install.sh and the Updates page install a build made for
|
||||
# in the OpenWrt feeds: install.sh and the Components page install a build made for
|
||||
# the router's firmware. The portal's HTTPS needs any libustream TLS module and
|
||||
# openssl-util; Settings offers to install them when the portal is turned on.
|
||||
# Runtime dependencies only (control file Depends): the package ships scripts
|
||||
@@ -34,6 +37,10 @@ define Package/luci-app-dawnline/conffiles
|
||||
/etc/config/dawnline
|
||||
endef
|
||||
|
||||
# /etc/dawnline (keys, backups, usage, history) survives a sysupgrade too:
|
||||
# root/lib/upgrade/keep.d/dawnline-data (the package's own keep.d file is
|
||||
# generated from conffiles).
|
||||
|
||||
define Package/luci-app-dawnline/prerm
|
||||
#!/bin/sh
|
||||
[ -n "$${IPKG_INSTROOT}" ] && exit 0
|
||||
@@ -41,6 +48,11 @@ define Package/luci-app-dawnline/prerm
|
||||
[ "$$1" = "upgrade" ] && exit 0
|
||||
/etc/init.d/dawnline stop 2>/dev/null
|
||||
/usr/bin/dawnline teardown 2>/dev/null
|
||||
# The heartbeat check would point at a removed file.
|
||||
grep -qs /usr/libexec/dawnline/ /etc/crontabs/root && {
|
||||
sed -i '\#/usr/libexec/dawnline/#d' /etc/crontabs/root
|
||||
/etc/init.d/cron restart 2>/dev/null
|
||||
}
|
||||
exit 0
|
||||
endef
|
||||
|
||||
|
||||
@@ -2,18 +2,30 @@
|
||||
'use strict';
|
||||
'require baseclass';
|
||||
'require dom';
|
||||
'require form';
|
||||
'require poll';
|
||||
'require rpc';
|
||||
'require uci';
|
||||
'require ui';
|
||||
var yn=Object.create;var Ft=Object.defineProperty;var kn=Object.getOwnPropertyDescriptor;var $n=Object.getOwnPropertyNames;var _n=Object.getPrototypeOf,Mn=Object.prototype.hasOwnProperty;var Ln=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports);var Sn=(o,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $n(t))!Mn.call(o,i)&&i!==n&&Ft(o,i,{get:()=>t[i],enumerable:!(a=kn(t,i))||a.enumerable});return o};var Tn=(o,t,n)=>(n=o!=null?yn(_n(o)):{},Sn(t||!o||!o.__esModule?Ft(n,"default",{value:o,enumerable:!0}):n,o));var Jt=Ln((Vt,Yt)=>{"use strict";var Kt=(function(){var o=function(y,D){var T=236,f=17,g=y,_=n[D],c=null,u=0,C=null,v=[],b={},j=function(M,S){u=g*4+17,c=(function(x){for(var E=new Array(x),A=0;A<x;A+=1){E[A]=new Array(x);for(var B=0;B<x;B+=1)E[A][B]=null}return E})(u),q(0,0),q(u-7,0),q(0,u-7),ee(),Z(),he(M,S),g>=7&&ie(M),C==null&&(C=yt(g,_,v)),fe(C,S)},q=function(M,S){for(var x=-1;x<=7;x+=1)if(!(M+x<=-1||u<=M+x))for(var E=-1;E<=7;E+=1)S+E<=-1||u<=S+E||(0<=x&&x<=6&&(E==0||E==6)||0<=E&&E<=6&&(x==0||x==6)||2<=x&&x<=4&&2<=E&&E<=4?c[M+x][S+E]=!0:c[M+x][S+E]=!1)},I=function(){for(var M=0,S=0,x=0;x<8;x+=1){j(!0,x);var E=i.getLostPoint(b);(x==0||M>E)&&(M=E,S=x)}return S},Z=function(){for(var M=8;M<u-8;M+=1)c[M][6]==null&&(c[M][6]=M%2==0);for(var S=8;S<u-8;S+=1)c[6][S]==null&&(c[6][S]=S%2==0)},ee=function(){for(var M=i.getPatternPosition(g),S=0;S<M.length;S+=1)for(var x=0;x<M.length;x+=1){var E=M[S],A=M[x];if(c[E][A]==null)for(var B=-2;B<=2;B+=1)for(var G=-2;G<=2;G+=1)B==-2||B==2||G==-2||G==2||B==0&&G==0?c[E+B][A+G]=!0:c[E+B][A+G]=!1}},ie=function(M){for(var S=i.getBCHTypeNumber(g),x=0;x<18;x+=1){var E=!M&&(S>>x&1)==1;c[Math.floor(x/3)][x%3+u-8-3]=E}for(var x=0;x<18;x+=1){var E=!M&&(S>>x&1)==1;c[x%3+u-8-3][Math.floor(x/3)]=E}},he=function(M,S){for(var x=_<<3|S,E=i.getBCHTypeInfo(x),A=0;A<15;A+=1){var B=!M&&(E>>A&1)==1;A<6?c[A][8]=B:A<8?c[A+1][8]=B:c[u-15+A][8]=B}for(var A=0;A<15;A+=1){var B=!M&&(E>>A&1)==1;A<8?c[8][u-A-1]=B:A<9?c[8][15-A-1+1]=B:c[8][15-A-1]=B}c[u-8][8]=!M},fe=function(M,S){for(var x=-1,E=u-1,A=7,B=0,G=i.getMaskFunction(S),U=u-1;U>0;U-=2)for(U==6&&(U-=1);;){for(var te=0;te<2;te+=1)if(c[E][U-te]==null){var de=!1;B<M.length&&(de=(M[B]>>>A&1)==1);var W=G(E,U-te);W&&(de=!de),c[E][U-te]=de,A-=1,A==-1&&(B+=1,A=7)}if(E+=x,E<0||u<=E){E-=x,x=-x;break}}},Te=function(M,S){for(var x=0,E=0,A=0,B=new Array(S.length),G=new Array(S.length),U=0;U<S.length;U+=1){var te=S[U].dataCount,de=S[U].totalCount-te;E=Math.max(E,te),A=Math.max(A,de),B[U]=new Array(te);for(var W=0;W<B[U].length;W+=1)B[U][W]=255&M.getBuffer()[W+x];x+=te;var me=i.getErrorCorrectPolynomial(de),ge=r(B[U],me.getLength()-1),qt=ge.mod(me);G[U]=new Array(me.getLength()-1);for(var W=0;W<G[U].length;W+=1){var Ut=W+qt.getLength()-G[U].length;G[U][W]=Ut>=0?qt.getAt(Ut):0}}for(var Gt=0,W=0;W<S.length;W+=1)Gt+=S[W].totalCount;for(var kt=new Array(Gt),st=0,W=0;W<E;W+=1)for(var U=0;U<S.length;U+=1)W<B[U].length&&(kt[st]=B[U][W],st+=1);for(var W=0;W<A;W+=1)for(var U=0;U<S.length;U+=1)W<G[U].length&&(kt[st]=G[U][W],st+=1);return kt},yt=function(M,S,x){for(var E=l.getRSBlocks(M,S),A=d(),B=0;B<x.length;B+=1){var G=x[B];A.put(G.getMode(),4),A.put(G.getLength(),i.getLengthInBits(G.getMode(),M)),G.write(A)}for(var U=0,B=0;B<E.length;B+=1)U+=E[B].dataCount;if(A.getLengthInBits()>U*8)throw"code length overflow. ("+A.getLengthInBits()+">"+U*8+")";for(A.getLengthInBits()+4<=U*8&&A.put(0,4);A.getLengthInBits()%8!=0;)A.putBit(!1);for(;!(A.getLengthInBits()>=U*8||(A.put(T,8),A.getLengthInBits()>=U*8));)A.put(f,8);return Te(A,E)};b.addData=function(M,S){S=S||"Byte";var x=null;switch(S){case"Numeric":x=h(M);break;case"Alphanumeric":x=m(M);break;case"Byte":x=p(M);break;case"Kanji":x=$(M);break;default:throw"mode:"+S}v.push(x),C=null},b.isDark=function(M,S){if(M<0||u<=M||S<0||u<=S)throw M+","+S;return c[M][S]},b.getModuleCount=function(){return u},b.make=function(){if(g<1){for(var M=1;M<40;M++){for(var S=l.getRSBlocks(M,_),x=d(),E=0;E<v.length;E++){var A=v[E];x.put(A.getMode(),4),x.put(A.getLength(),i.getLengthInBits(A.getMode(),M)),A.write(x)}for(var B=0,E=0;E<S.length;E++)B+=S[E].dataCount;if(x.getLengthInBits()<=B*8)break}g=M}j(!1,I())},b.createTableTag=function(M,S){M=M||2,S=typeof S>"u"?M*4:S;var x="";x+='<table style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: "+S+"px;",x+='">',x+="<tbody>";for(var E=0;E<b.getModuleCount();E+=1){x+="<tr>";for(var A=0;A<b.getModuleCount();A+=1)x+='<td style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: 0px;",x+=" width: "+M+"px;",x+=" height: "+M+"px;",x+=" background-color: ",x+=b.isDark(E,A)?"#000000":"#ffffff",x+=";",x+='"/>';x+="</tr>"}return x+="</tbody>",x+="</table>",x},b.createSvgTag=function(M,S,x,E){var A={};typeof arguments[0]=="object"&&(A=arguments[0],M=A.cellSize,S=A.margin,x=A.alt,E=A.title),M=M||2,S=typeof S>"u"?M*4:S,x=typeof x=="string"?{text:x}:x||{},x.text=x.text||null,Line truncated
|
||||
`}return x%2&&M>0?ge.substring(0,ge.length-x-1)+Array(x+1).join("▀"):ge.substring(0,ge.length-1)};return b.createASCII=function(M,S){if(M=M||1,M<2)return se(S);M-=1,S=typeof S>"u"?M*2:S;var x=b.getModuleCount()*M+S*2,E=S,A=x-S,B,G,U,te,de=Array(M+1).join("██"),W=Array(M+1).join(" "),me="",ge="";for(B=0;B<x;B+=1){for(U=Math.floor((B-E)/M),ge="",G=0;G<x;G+=1)te=1,E<=G&&G<A&&E<=B&&B<A&&b.isDark(U,Math.floor((G-E)/M))&&(te=0),ge+=te?de:W;for(U=0;U<M;U+=1)me+=ge+`
|
||||
`}return me.substring(0,me.length-1)},b.renderTo2dContext=function(M,S){S=S||2;for(var x=b.getModuleCount(),E=0;E<x;E++)for(var A=0;A<x;A++)M.fillStyle=b.isDark(E,A)?"black":"white",M.fillRect(E*S,A*S,S,S)},b};o.stringToBytesFuncs={default:function(y){for(var D=[],T=0;T<y.length;T+=1){var f=y.charCodeAt(T);D.push(f&255)}return D}},o.stringToBytes=o.stringToBytesFuncs.default,o.createStringToBytes=function(y,D){var T=(function(){for(var g=Y(y),_=function(){var Z=g.read();if(Z==-1)throw"eof";return Z},c=0,u={};;){var C=g.read();if(C==-1)break;var v=_(),b=_(),j=_(),q=String.fromCharCode(C<<8|v),I=b<<8|j;u[q]=I,c+=1}if(c!=D)throw c+" != "+D;return u})(),f=63;return function(g){for(var _=[],c=0;c<g.length;c+=1){var u=g.charCodeAt(c);if(u<128)_.push(u);else{var C=T[g.charAt(c)];typeof C=="number"?(C&255)==C?_.push(C):(_.push(C>>>8),_.push(C&255)):_.push(f)}}return _}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},i=(function(){var y=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],D=1335,T=7973,f=21522,g={},_=function(c){for(var u=0;c!=0;)u+=1,c>>>=1;return u};return g.getBCHTypeInfo=function(c){for(var u=c<<10;_(u)-_(D)>=0;)u^=D<<_(u)-_(D);return(c<<10|u)^f},g.getBCHTypeNumber=function(c){for(var u=c<<12;_(u)-_(T)>=0;)u^=T<<_(u)-_(T);return c<<12|u},g.getPatternPosition=function(c){return y[c-1]},g.getMaskFunction=function(c){switch(c){case a.PATTERN000:return function(u,C){return(u+C)%2==0};case a.PATTERN001:return function(u,C){return u%2==0};case a.PATTERN010:return function(u,C){return C%3==0};case a.PATTERN011:return function(u,C){return(u+C)%3==0};case a.PATTERN100:return function(u,C){return(Math.floor(u/2)+Math.floor(C/3))%2==0};case a.PATTERN101:return function(u,C){return u*C%2+u*C%3==0};case a.PATTERN110:return function(u,C){return(u*C%2+u*C%3)%2==0};case a.PATTERN111:return function(u,C){return(u*C%3+(u+C)%2)%2==0};default:throw"bad maskPattern:"+c}},g.getErrorCorrectPolynomial=function(c){for(var u=r([1],0),C=0;C<c;C+=1)u=u.multiply(r([1,s.gexp(C)],0));return u},g.getLengthInBits=function(c,u){if(1<=u&&u<10)switch(c){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+c}else if(u<27)switch(c){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+c}else if(u<41)switch(c){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+c}else throw"type:"+u},g.getLostPoint=function(c){for(var u=c.getModuleCount(),C=0,v=0;v<u;v+=1)for(var b=0;b<u;b+=1){for(var j=0,q=c.isDark(v,b),I=-1;I<=1;I+=1)if(!(v+I<0||u<=v+I))for(var Z=-1;Z<=1;Z+=1)b+Z<0||u<=b+Z||I==0&&Z==0||q==c.isDark(v+I,b+Z)&&(j+=1);j>5&&(C+=3+j-5)}for(var v=0;v<u-1;v+=1)for(var b=0;b<u-1;b+=1){var ee=0;c.isDark(v,b)&&(ee+=1),c.isDark(v+1,b)&&(ee+=1),c.isDark(v,b+1)&&(ee+=1),c.isDark(v+1,b+1)&&(ee+=1),(ee==0||ee==4)&&(C+=3)}for(var v=0;v<u;v+=1)for(var b=0;b<u-6;b+=1)c.isDark(v,b)&&!c.isDark(v,b+1)&&c.isDark(v,b+2)&&c.isDark(v,b+3)&&c.isDark(v,b+4)&&!c.isDark(v,b+5)&&c.isDark(v,b+6)&&(C+=40);for(var b=0;b<u;b+=1)for(var v=0;v<u-6;v+=1)c.isDark(v,b)&&!c.isDark(v+1,b)&&c.isDark(v+2,b)&&c.isDark(v+3,b)&&c.isDark(v+4,b)&&!c.isDark(v+5,b)&&c.isDark(v+6,b)&&(C+=40);for(var ie=0,b=0;b<u;b+=1)for(var v=0;v<u;v+=1)c.isDark(v,b)&&(ie+=1);var he=Math.abs(100*ie/u/u-50)/5;return C+=he*10,C},g})(),s=(function(){for(var y=new Array(256),D=new Array(256),T=0;T<8;T+=1)y[T]=1<<T;for(var T=8;T<256;T+=1)y[T]=y[T-4]^y[T-5]^y[T-6]^y[T-8];for(var T=0;T<255;T+=1)D[y[T]]=T;var f={};return f.glog=function(g){if(g<1)throw"glog("+g+")";return D[g]},f.gexp=function(g){for(;g<0;)g+=255;for(;g>=256;)g-=255;return y[g]},f})();function r(y,D){if(typeof y.length>"u")throw y.length+"/"+D;var T=(function(){for(var g=0;g<y.length&&y[g]==0;)g+=1;for(var _=new Array(y.length-g+D),c=0;c<y.length-g;c+=1)_[c]=y[c+g];return _})(),f={};return f.getAt=function(g){return T[g]},f.getLength=function(){return T.length},f.multiply=function(g){for(var _=new Array(f.getLength()+g.getLength()-1),c=0;c<f.getLength();c+=1)for(var u=0;u<g.getLength();u+=1)_[c+u]^=s.gexp(s.glog(f.getAt(c))+s.glog(g.getAt(u)));return r(_,0)},f.mod=function(g){if(f.g
Line truncated
|
||||
`),hostName:s,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(r),port:String(n.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:s};return n.dns[0]&&(l.dns1=n.dns[0]),n.dns[1]&&(l.dns2=n.dns[1]),l}function On(o){let t="";for(let n=0;n<o.length;n+=32768)t+=String.fromCharCode(...o.subarray(n,n+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function qn(o){let t=globalThis;if(typeof t.CompressionStream>"u")return null;try{let n=new t.Blob([o]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(n).arrayBuffer()),i=new Uint8Array(4+a.length);return new DataView(i.buffer).setUint32(0,o.length,!1),i.set(a,4),i}catch{return null}}async function Zt(o,t,n=!0){let a=new TextEncoder().encode(JSON.stringify(jn(o,t))),i=n?await qn(a):null;return`vpn://${On(i??a)}`}function V(o){if(!o||o<0)return"0 B";let t=["B","KB","MB","GB","TB"],n=0,a=o;for(;a>=1024&&n<t.length-1;)a/=1024,n++;return`${a>=100||n===0?Math.round(a):a.toFixed(1)} ${t[n]}`}function $e(o){let t=o*8;return t<1e3?`${Math.round(t)} bit/s`:t<1e6?`${(t/1e3).toFixed(t<1e4?1:0)} kbit/s`:t<1e9?`${(t/1e6).toFixed(t<1e7?1:0)} Mbit/s`:`${(t/1e9).toFixed(1)} Gbit/s`}function ce(o,t=Date.now()/1e3){if(!o)return"never";let n=Math.max(0,Math.round(t-o));return n<60?"just now":n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:n<86400*30?`${Math.floor(n/86400)} d ago`:new Date(o*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function Xt(o){if(!o||o<0)return"—";let t=Math.floor(o/86400),n=Math.floor(o%86400/3600),a=Math.floor(o%3600/60);return t?`${t}d ${n}h`:n?`${n}h ${a}m`:`${a}m`}function St(o){let t=new Date(o*1e3),n=new Date,a=t.toDateString()===n.toDateString(),i=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return a?i:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})} ${i}`}function _e(o){if(!o)return"";let[t,n,a]=o.split("-").map(Number);return new Date(t,n-1,a).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function ze(o,t=Date.now()){if(!o)return null;let[n,a,i]=o.split("-").map(Number),s=new Date(n,a-1,i,23,59,59).getTime();return Math.ceil((s-t)/864e5)}var je={lan:"Home network",internet:"Internet",both:"Home network + Internet"},en={lan:"LAN",internet:"Internet",both:"LAN + Internet"},tn=["computer","phone","tablet","router","other"],Me={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Tt={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function Le(o){let t=o.trim().split(/\s+/).filter(Boolean);if(!t.length)return"?";let n=t[0][0]??"",a=t.length>1?t[t.length-1][0]??"":t[0][1]??"";return(n+a).toUpperCase()}var Ne=null;function le(o,t){let n=a=>{Ne??(Ne=document.body.appendChild(e("div",{class:"dl-tip dl-tip-float dl-root"}))),Ne.replaceChildren(...t().map(i=>typeof i=="string"?document.createTextNode(i):i)),Ne.style.display="",Ne.style.left=`${a.clientX}px`,Ne.style.top=`${a.clientY-10}px`};o.addEventListener("mouseenter",n),o.addEventListener("mousemove",n),o.addEventListener("mouseleave",()=>Ne&&(Ne.style.display="none"))}function nn(o,t=120,n=26){let a=Math.max(1,...o),i=e("div",{class:"dl-spark"});i.style.width=`${t}px`,i.style.height=`${n}px`;let s=Date.now();return o.forEach((r,l)=>{let d=e("i");d.style.height=`${Math.max(6,r/a*100)}%`,r||d.classList.add("zero");let h=o.length-1-l,m=new Date(s-h*864e5);le(d,()=>[e("div",{class:"dl-tip-title"},h===0?"Today":h===1?"Yesterday":m.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})),e("div",{class:"dl-muted"},V(r))]),i.appendChild(d)}),i}var Un={connect:"connections",disconnect:"connections",roam:"connections",device_added:"devices",device_removed:"devices",devices_removed:"devices",person_added:"people",person_removed:"people",person_changed:"people",paused:"people",resumed:"people",paused_all:"people",resumed_all:"people",server_down:"problems",server_up:"problems",portal_blocked:"problems"},Oe=["connections","devices","people","problems"],qe={connections:"Connections",devices:"Devices",people:"People",problems:"Problems"},an={connections:"Connects, disconnects and IP changes",devices:"Devices added and removed",people:"People added, changed, paused",problems:"Tunnel down, blocked portal sign-ins"},rt=o=>Un[o]??"problems";function Gn(o){let t=new Map(o.people.map(a=>[a.id,a.name])),n=new Map(o.people.flatMap(a=>a.devices.map(i=>[i.id,i.name])));return{people:t,devices:n}}function Fn(o){let t=o==null?"":String(o);return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function be(o,t,n,a=""){let i=Gn(o),s=t.
Line truncated
|
||||
`);ve(l,h,"text/csv")}var Wn=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]];function Ee(o,t,n,a,i){let s=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...Oe.map(l=>e("option",{value:l,selected:l===i?"selected":null},qe[l]))]),r=e("select",{class:"cbi-input-select"},Wn.map(([l,d])=>e("option",{value:l},d)));ne(o,[e("p",{class:"dl-muted"},`${t} This cannot be undone; export first if you want a copy.`),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Category"),s]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),r])],[e("button",{class:"cbi-button cbi-button-neutral",click:J},"Cancel")," ",N("Clear",async()=>{let l=await O(()=>P.logsClear({...n,category:s.value,older_days:r.value}));l&&(J(),X(l.removed?`${l.removed} event${l.removed===1?"":"s"} removed`:"Nothing matched","success",3e3),a())},"negative")])}function Ue(o,t,n,a){let i=o==="device"?`Clears ${n}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:o==="person"?`Clears ${n}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";ne(o==="all"?"Reset all traffic history?":`Reset traffic history for ${n}?`,[e("p",{class:"dl-muted"},i)],[e("button",{class:"cbi-button cbi-button-neutral",click:J},"Cancel")," ",N("Reset",async()=>{await O(()=>P.usageClear(o,t),"Traffic history reset")&&(J(),a())},"negative")])}var lt=null;function Kn(o){return o?new Date(o*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function on(o,t,n=!0){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},o),e("button",{type:"button",class:`dl-kvrow-v copy${n?" dl-mono":""}`,title:"Copy",click:()=>re(t,`${o} copied`)},[e("span",{},t),w("copy")])])}function dt(o,t){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},o),e("span",{class:"dl-kvrow-v"},t)])}function sn(o,t){if(/^\s*\[.+\]\s*$/.test(o))return e("span",{class:"dl-conf-sec"},o);let n=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(o);if(!n)return document.createTextNode(o);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(o);return e("span",{},[e("span",{class:"dl-conf-k"},n[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):n[2]])}function Vn(o){let t=!1,n=e("pre",{class:"dl-conf"}),a=()=>dom.content(n,o.conf.split(`
|
||||
`).flatMap((r,l)=>l?[`
|
||||
`,sn(r,t)]:[sn(r,t)])),i=e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),t=!t,dom.content(i,[w(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[w("key"),"Show key"]);a();let s=new Blob([o.conf]).size;return e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-filecard"},[e("span",{class:"dl-filecard-ic"},".conf"),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono dl-ellipsis"},o.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${s} bytes · import it in the app`)]),N([w("download")," Download"],()=>ve(o.filename,o.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[w("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),i,e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),re(o.conf,"Configuration copied")}},[w("copy"),"Copy"])]),n])])}async function Et(o){if(!o.has_private_key)return e("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let t=await Zt(o,`${o.server} · ${o.person} · ${o.name}`),n={qr:()=>e("div",{class:"dl-qr-pane"},[Pe(Be(o.conf),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-linkbox"},[e("span",{class:"dl-mono"},t),N("Copy",()=>re(t,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Vn(o)},a=e("div",{class:"dl-connect-body"}),i=e("div",{class:"dl-seg"}),s=r=>{i.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.id===r)),dom.content(a,n[r]())};for(let[r,l]of[["qr","QR code"],["key","Key"],["file","File"]])i.appendChild(e("button",{type:"button","data-id":r,click:()=>s(r)},l));return s("qr"),e("div",{class:"dl-stack gap12"},[i,a])}function Yn(o,t,n,a){lt?.close();let i=e("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[e("div",{class:"dl-drawer-head"},[o,e("button",{type:"button",class:"dl-drawer-x","aria-label":"Close",click:()=>l()},w("x"))]),e("div",{class:"dl-drawer-body"},t),n?e("div",{class:"dl-drawer-foot"},n):""]),s=e("div",{class:"dl-drawer-overlay dl-root",click:h=>{h.target===s&&l()}},i),r=h=>{h.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&l()};function l(){document.removeEventListener("keydown",r),s.classList.remove("open"),setTimeout(()=>s.remove(),220),lt===d&&(lt=null),a()}let d={close:l,panel:i};return document.addEventListener("keydown",r),document.body.appendChild(s),requestAnimationFrame(()=>s.classList.add("open")),lt=d,d}var rn={connect:["ok","Connected"],disconnect:["","Went offline"],roam:["","Changed network"],device_added:["accent","Added"],device_removed:["","Removed"]};function Jn(o,t){let n=o.filter(a=>a.device===t&&rn[a.type]).reverse().slice(0,12);return n.length?e("div",{class:"dl-dev-log"},n.map(a=>{let[i,s]=rn[a.type],r=a.type==="connect"?[a.detail?e("span",{class:"dl-mono"},` ${a.detail}`):"",a.where?e("span",{class:"dl-faint"},` · ${a.where}`):""]:a.type==="roam"?[e("span",{class:"dl-mono dl-faint"},` ${a.detail??""}`)]:a.type==="device_added"?[e("span",{class:"dl-faint"},(a.detail??"").includes("(portal)")?" from the portal":" by you")]:[],l=new Date(a.ts*1e3);return e("div",{class:"dl-dev-log-row"},[e("span",{class:`dl-ev-dot ${i}`}),e("span",{class:"dl-row-main"},[e("span",{},s),...r]),e("span",{class:"dl-faint dl-nowrap",title:l.toLocaleString()},ce(a.ts))])})):e("div",{class:"dl-sub"},"No activity yet.")}function Qn(o){return o.disabled?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),"Disabled"]):o.online?e("span",{class:"dl-dstat ok"},[e("i",{class:"dot ok"}),`Online from ${o.endpoint}`]):o.handshake?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),`Last seen ${ce(o.handshake)}`]):e("span",{class:"dl-dstat warn"},[e("i",{class:"dot warn"}),"Waiting for the first connection"])}async function Ce(o,t,n,a){let i=await O(()=>P.deviceConfig(t.id));if(!i)return;let s=t,r=o,l=await Et(i),d=e("div",{class:"dl-drawer-title"}),h=e("div",{}),m=e("div",{}),p=e("div",{class:"dl-live"}),$=e("div",{},e("div",{class:"dl-sub"},"Loading…")),k=[],z=async()=>{let g=await P.events(5e3).catch(()=>null);g&&(k=g.events.filter(_=>_.device===s.id),dom.content($,Jn(g.events,s.id)))},Y=()=>{let g=a?.points.find(c=>c.device===s.id&&c.ip===s.endpoint);dom.content(d,[e("span",{class:`dl-dcard-ic${s.online?" on":""}`},w(s.kind)),e("div",{class:"dl-stack"},[e("div",{class:"dl-title-row"},[e("h3",{},s.name),N([w("edit")],()=>H(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),e("span",{class:"dl-sub"},[`${r.name} · ${Me[s.kind]}`])])]);let _=s.spark.reduce((c,u)=>c+u,0);dom.content(h,e("div",{class:"dl-dstats"},[e("div",{class:"dl-dstats-cell wide"},[e("span",{class:"dl-metric-label"},"Status"),Qn(s)]),e("div",{class:"dl-dstats-cell"},[e("span",{class:"dl-metric-label"},"This month"),e("b",{},V(s.month[0]+s.month[1])),e("span",
Line truncated
|
||||
`),d=e("div",{class:"dl-pgrid"},[i("Junk packets","zap",s?`${s} random packet${s===1?"":"s"} of ${o.jmin}–${o.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),i("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),i("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),i("Signatures","globe",r,["i1","i2","i3","i4","i5"]),i("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),i("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return e("details",{class:"dl-params"},[e("summary",{},[w("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(n.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:h=>{h.preventDefault(),re(l,"Parameters copied")}},"Copy as config")]),d])}var Rt=(o,t)=>{let n=new URLSearchParams;o&&n.set("server",o),t&&t!=="overview"&&n.set("section",t);let a=n.toString();return`${L.url("admin/network/dawnline/server")}${a?`?${a}`:""}`},at=class{constructor(){this.noFooter=!0;this.root=e("div",{class:"dl-root"});this.section="overview";this.srvId="";this.ov={};this.pp={};this.tabsEl=e("div",{});this.headEl=e("div",{});this.secEl=e("div",{});this.bodyEl=e("div",{class:"dl-srvbody"})}async load(){let t=await P.status(31),n=t.servers.length?null:await P.setupDefaults();return[t,n]}render([t,n]){if(this.st=t,!t.servers.length&&n)return this.wizard(n);let a=new URLSearchParams(location.search),i=a.get("section")??"",s=Ma[i]??i;return mn.some(([r])=>r===s)&&(this.section=s),this.srvId=(t.servers.find(r=>r.id===a.get("server"))??t.servers[0]).id,we(t),dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint(),poll.add(async()=>{if(this.section!=="overview")return;let r=await P.status(31).catch(()=>null);if(!r||!r.servers.length)return;this.st=r;let l=this.current();dom.content(this.headEl,this.head(l)),this.paintTabs(),this.ov[l.id]?.update(r)},10),this.root}current(){return this.st.servers.find(t=>t.id===this.srvId)??this.st.servers[0]}async refresh(){let t=await P.status(31).catch(()=>null);t&&(this.st=t,t.servers.length?this.paint():location.href=Rt())}paint(){this.paintTabs(),dom.content(this.headEl,this.head(this.current())),this.paintSections(),this.showSection(this.section)}paintTabs(){let t=this.current();dom.content(this.tabsEl,e("div",{class:"dl-srvtabs",role:"tablist","aria-label":"Servers"},[...this.st.servers.map(n=>e("button",{type:"button",role:"tab",class:`dl-srvtab${n.id===t.id?" on":""}`,"aria-selected":n.id===t.id?"true":"false",click:()=>{n.id!==this.srvId&&(this.srvId=n.id,this.paint())}},[e("i",{class:`dot ${n.up?"ok":"bad"}`}),e("b",{},n.name),e("span",{class:"dl-mono dl-faint"},`:${n.port}`)])),e("button",{type:"button",class:"dl-srvtab add",click:()=>this.addServer()},[w("plus"),"Add server"])]))}paintSections(){dom.content(this.secEl,e("div",{class:"dl-seg dl-srvsections",role:"tablist","aria-label":"Server"},mn.map(([t,n])=>e("button",{type:"button",role:"tab","data-section":t,class:t===this.section?"on":"","aria-selected":t===this.section?"true":"false",click:()=>this.showSection(t)},n))))}go(t,n){let a=this.pp[this.current().id];if(n&&a)a.filter=n,a.el&&a.decorate();else if(n){let i=this.pp[this.current().id]=new He;i.filter=n}this.showSection(t),window.scrollTo({top:0,behavior:"smooth"})}detachKept(){let t=[...Object.values(this.ov).map(n=>n.el),...Object.values(this.pp).map(n=>n.el)];for(let n of t)n&&this.bodyEl.contains(n)&&n.remove()}showSection(t){this.section=t,this.secEl.querySelectorAll("[data-section]").forEach(r=>{let l=r.dataset.section===t;r.classList.toggle("on",l),r.setAttribute("aria-selected",l?"true":"false")});let n=this.st,a=this.current(),s={overview:()=>{let r=this.ov[a.id];return r?(r.update(n),r.el):(this.ov[a.id]=new ft(a.id,(l,d)=>this.go(l,d))).mount(n)},people:()=>{var h,m;let r=this.pp[a.id];if(r?.el)return r.poll(),r.el;let l=e("div",{},e("p",{class:"dl-muted"},"Loading people…"));return((h=this.pp)[m=a.id]??(h[m]=new He)).embed(n,a.id).then(p=>{l.isConnected?dom.content(l,p):l.replaceChildren(p)}),l},connection:()=>this.connection(a),access:()=>this.access(a),disguise:()=>this.disguise(a),tunnel:()=>this.tunnel(a)}[t]();this.detachKept(),dom.content(this.bodyEl,s)}head(t){let n=this.st,a=(l,d)=>e("span",{class:"dl-addrbar-seg"},[w(l),...d]),i=`${t.endpoint||"—"}:${t.port}`,s=!t.enabled||n.settings.paused_all,r=e("div",{class:"dl-actions"},[N([w("search")," Search ",e("kbd",{},"⌘K")],()=>Ct(),"neutral",{class:"cbi-button cbi-button-neutral dl-searchbtn"}),s?N([w("play")," Turn o
Line truncated
|
||||
`))]):"",u=g.length+(s?.update?1:0)+(r?.update?1:0),C=[i?.version?`OpenWrt ${i.version} · ${i.target}`:"",t.check?u?`${u} update${u===1?"":"s"} ready`:"everything is current":"not checked yet",t.check?`checked ${St(t.check.time)}`:""].filter(Boolean).join(" · ");dom.content(this.root,[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"Updates"),e("span",{class:"dl-faint"},C)]),N([w("refresh")," Check now"],()=>this.run("check"),"neutral",d)]),k,H,_,c])}async runAwg(t,n,a){await ae(a?`Install AmneziaWG ${a}?`:"Install AmneziaWG?","Every AmneziaWG tunnel on the router restarts for a few seconds, HomeTunnel too. Devices stay configured.","Install")&&this.start(`amneziawg:${t}${n?":ru":""}`)}async runPkgs(t,n,a=t){await ae(`Update ${n}?`,`${a.join(", ")} from the OpenWrt feeds. Services that use them restart for a moment.`,"Update")&&this.start(`pkgs:${t.join(",")}`)}async run(t){t!=="check"&&!await ae(`Update ${t==="app"?"Dawnline":t}?`,"A backup is made first. The page reloads when it finishes.","Update")||this.start(t)}async start(t){if(await O(()=>P.updatesRun(t))){this.running=!0;let n=await P.updatesStatus().catch(()=>null);n&&this.paint(n)}}};function Ot(o){return`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}-${String(o.getDate()).padStart(2,"0")}`}function Aa(o,t,n,a=30){let i=o?new Date(`${o}T12:00:00`):new Date;return t==="day"?i.setDate(i.getDate()+n):t==="week"?i.setDate(i.getDate()+7*n):t==="month"?i.setMonth(i.getMonth()+n):t==="year"?i.setFullYear(i.getFullYear()+n):i.setDate(i.getDate()+a*n),Ot(i)}var Pa={internet:"Browse the internet through your router. No access to devices at home.",lan:"Reach devices at home. Internet stays on their own connection.",both:"Home devices and the internet, all through your router."},wt=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.refreshSeq=0;this.refreshShown=0}async load(){this.id=new URLSearchParams(location.search).get("id")??"";let[t,n,a]=await Promise.all([P.status(30),P.events(5e3).catch(()=>({events:[]})),P.personUsage(this.id,30).catch(()=>null)]);return this.series=a?.person??[],this.devSeries=a?.devices??{},[t,n.events]}render([t,n]){this.st=t,this.events=n,we(t);let a=t.people.find(l=>l.id===this.id);if(!a)return e("div",{class:"dl-empty"},[e("h3",{},"Person not found"),e("p",{},"They may have been removed."),e("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=a;for(let l of["head","devices","traffic","places","activity","limits"])this.parts[l]=e("div",{});this.parts.devices.className="dl-person-devices";let i=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:Ze(a.server)},t.servers.find(l=>l.id===a.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:Ze(a.server)},"People"),e("span",{},"/"),e("span",{},a.name)]),this.parts.head,e("div",{class:"dl-grid-person"},[e("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),e("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let s=new URLSearchParams(location.search),r=s.get("device")&&a.devices.find(l=>l.id===s.get("device"));return r?setTimeout(()=>Ce(this.p,r,()=>this.refresh(),this.st.geo),50):s.get("add")&&setTimeout(()=>Re(this.p,()=>this.refresh()),50),poll.add(()=>this.refresh(!0),15),i}async refresh(t=!1){let n=++this.refreshSeq,[a,i,s]=await Promise.all([P.status(30).catch(()=>null),P.events(5e3).catch(()=>null),P.personUsage(this.id,30).catch(()=>null)]);if(!a||n<this.refreshShown)return;this.refreshShown=n,this.st=a,i&&(this.events=i.events),s&&(this.series=s.person,this.devSeries=s.devices);let r=a.people.find(l=>l.id===this.id);if(!r){t||(location.href=Ze(this.p?.server));return}this.p=r,this.paint(),this.map?.update(this.mapData())}async patch(t,n){var s;let a=await O(()=>P.personUpdate(this.p.id,t),n);if(!a)return;let i=this.st.people.findIndex(r=>r.id===this.p.id);(s=a.person).rate??(s.rate=this.p.rate),i>=0&&(this.st.people[i]=a.person),this.p=a.person,this.paint()}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}mapCard(){let t=e("div",{class:"dl-panel-head pad"},[e("h3",{},"Locations"),e("span",{class:"dl-spacer"}),this.st.geo.enabled?ut("30d",n=>this.map?.setRange(n),!1):"",N("Hide",()=>{this.mapOpen=!1,this.map?.destroy(),this.map=null,this.paintPlaces()},"neutral")]);return this.st.geo.enabled?(this.map=new Fe({openPerson:()=>{},openDevice:(n,a)=>{let i=this.p.devices.find(s=>s.id===a);i&&Ce(this.p,i,()=>this.refresh(),this.st.geo)}},"30d",280),requestAnimationFrame(()=>this.map.mount(this.mapData())),e("div",{class:"dl-panel flush"},[t,this.map.el])):e("div",{class:"dl-panel flush"},[t,e("div",{class:"dl-map-off"},["Locations are off. ",e("a",{href:L.url("admin/network/dawnline/settings")},"Turn them on in Settings"),"."])])}paint(){let t=this.p,n=this.st,a=t.online?"online now":
Line truncated
|
||||
`)}d.push(z),p+=k-1}let m=N([w("more")],()=>ke(m,[{label:"Export CSV",icon:w("download"),run:()=>be(this.st,l,"csv",t.id)},{label:"Export JSON",icon:w("download"),run:()=>be(this.st,l,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:w("trash"),danger:!0,run:()=>Ee(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>this.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});dom.content(this.parts.activity,e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},l.length>10?`latest 10 of ${l.length}`:""),e("span",{class:"dl-spacer"}),m]),d.length?d:e("div",{class:"dl-row dl-muted"},"Nothing yet.")]))}deviceStatus(t){return t.disabled?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),"Disabled"]):t.online?e("span",{class:"dl-dstat ok"},[e("i",{class:"dot ok"}),`Online · ${ce(t.handshake,this.st.now).replace(" ago","")}`]):t.handshake?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),`Last seen ${ce(t.handshake,this.st.now)}`]):e("span",{class:"dl-dstat warn",title:"Waiting for the first connection"},[e("i",{class:"dot warn"}),"Not set up yet"])}addrs(t){if(!t.online||!t.endpoint)return"";let n=this.st.geo?.points.find(s=>s.device===t.id&&s.ip===t.endpoint),a=n?.city?`Client IP · ${n.city}${n.org?` · ${n.org}`:""}`:"Client IP",i=e("button",{type:"button",class:"dl-addr wan","aria-label":`Copy ${t.endpoint}`,click:()=>re(t.endpoint,"Client IP copied")},[w("globe"),e("span",{},t.endpoint)]);return le(i,()=>[e("div",{class:"dl-tip-title"},a),e("div",{class:"dl-muted"},"Click to copy")]),e("div",{class:"dl-addrs"},i)}deviceBars(t){let n=(this.devSeries[t]??[]).slice(-30),a=n.map(r=>r.rx+r.tx),i=Math.max(1,...a),s=r=>new Date(`${r}T12:00:00`).toLocaleDateString("en-GB",{day:"numeric",month:"short"});return e("div",{class:"dl-dbars"},n.map((r,l)=>{let d=e("i",{class:`${a[l]?"":"zero"}${l===n.length-1?" hi":""}`});return d.style.height=`${Math.max(8,a[l]/i*100)}%`,le(d,()=>[e("div",{class:"dl-tip-title"},l===n.length-1?`Today · ${s(r.day)}`:s(r.day)),e("div",{},V(a[l]))]),d}))}paintDevices(){let t=this.p,n=()=>this.refresh(),a=t.devices.map(s=>{let r=()=>Ce(t,s,n,this.st.geo);return e("article",{class:`dl-dcard${s.online?" online":""}${s.disabled?" off":""}`},[e("div",{class:"dl-dcard-head"},[e("span",{class:"dl-dcard-ic"},w(s.kind)),e("button",{type:"button",class:"dl-dcard-title",click:r},[e("b",{},s.name),this.deviceStatus(s),s.config_stale?e("span",{class:"dl-pill warn dl-stale"},"Update config"):""]),N([w("more")],r,"neutral",{title:`${s.name}: connect, rename, keys, remove`,class:"cbi-button cbi-button-neutral dl-icon-only"})]),s.handshake?e("div",{class:"dl-dcard-trend"},[e("div",{class:"dl-stack"},[e("b",{},V(s.month[0]+s.month[1])),e("span",{class:"dl-sub"},"this month")]),this.deviceBars(s.id)]):s.disabled?e("div",{class:"dl-sub"},`${Me[s.kind]} · created ${ce(s.created,this.st.now)} ${s.created_by==="portal"?"in the portal":"by you"}.`):e("div",{class:"dl-chips-row"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>this.showDeviceQr(s)},[w("qr"),"Show QR"]),e("button",{type:"button",class:"dl-chipbtn",click:()=>this.downloadConfig(s)},[w("download"),"Config"])]),this.addrs(s)])}),i=Math.max(0,t.device_limit-t.devices.length);i&&a.push(e("button",{type:"button",class:"dl-dslot add",click:()=>Re(t,n)},[e("span",{class:"dl-dslot-ic"},w("plus")),e("b",{},"Add device")])),dom.content(this.parts.devices,e("section",{class:"dl-devsec"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Devices"),e("span",{class:"dl-sub"},`${t.online} online`),e("span",{class:"dl-spacer"}),i?"":N([w("plus")," Add device"],()=>Re(t,n),"neutral",{title:"Over the limit — admins can still add"})]),e("div",{class:"dl-dgrid"},a)]))}paintLimits(){let t=this.p,n=e("div",{class:"dl-seg wide",role:"radiogroup","aria-label":"Access"},["internet","lan","both"].map(c=>e("button",{type:"button",role:"radio",class:t.access===c?"on":"","aria-checked":t.access===c?"true":"false",click:()=>t.access!==c&&this.patch({access:c},`Access: ${je[c]}`)},[w(c==="internet"?"globe":c==="lan"?"home":"shield"),c==="internet"?"Internet":c==="lan"?"Home":"Both"]))),a=ze(t.expires),i=e("input",{type:"date",class:"dl-date-hidden",value:t.expires,tabindex:"-1","aria-hidden":"true"});i.addEventListener("change",()=>i.value&&this.patch({expires:i.value},`Access until ${_e(i.value)}`));let s=(c,u,C)=>{let v=Aa(t.expires&&(a??-1)>=0?t.expires:"",c,u);return this.patch({expires:v},`Access until ${_e(v)}`),C},r=[["week",1,"+1 week"],["month",1,"+1 month"],["month",3,"+3 months"],["year",1,"+1 year"]].map(([c,u,C])=>e("button",{type:"button",class:"dl-chipbtn",click:()=>s(c,u,C)},C)),l=e("span",{class:"dl-datechip"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>{try{i.showPicker()}catch{i.focus()}}},[w("calendar"),t.expires?_e(t.expires):"Date"]),i]),d={pause:"pause access",notify:"keep acc
Line truncated
|
||||
var va=Object.create;var ds=Object.defineProperty;var ba=Object.getOwnPropertyDescriptor;var xa=Object.getOwnPropertyNames;var wa=Object.getPrototypeOf,ya=Object.prototype.hasOwnProperty;var ka=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var _a=(t,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xa(e))!ya.call(t,r)&&r!==o&&ds(t,r,{get:()=>e[r],enumerable:!(s=ba(e,r))||s.enumerable});return t};var Ca=(t,e,o)=>(o=t!=null?va(wa(t)):{},_a(e||!t||!t.__esModule?ds(o,"default",{value:t,enumerable:!0}):o,t));var _s=ka((ys,ks)=>{"use strict";var ws=(function(){var t=function(P,R){var w=236,k=17,y=P,O=o[R],b=null,f=0,T=null,C=[],A={},K=function(z,$){f=y*4+17,b=(function(E){for(var I=new Array(E),D=0;D<E;D+=1){I[D]=new Array(E);for(var W=0;W<E;W+=1)I[D][W]=null}return I})(f),Y(0,0),Y(f-7,0),Y(0,f-7),Z(),j(),me(z,$),y>=7&&te(z),T==null&&(T=ne(y,O,C)),ke(T,$)},Y=function(z,$){for(var E=-1;E<=7;E+=1)if(!(z+E<=-1||f<=z+E))for(var I=-1;I<=7;I+=1)$+I<=-1||f<=$+I||(0<=E&&E<=6&&(I==0||I==6)||0<=I&&I<=6&&(E==0||E==6)||2<=E&&E<=4&&2<=I&&I<=4?b[z+E][$+I]=!0:b[z+E][$+I]=!1)},Q=function(){for(var z=0,$=0,E=0;E<8;E+=1){K(!0,E);var I=r.getLostPoint(A);(E==0||z>I)&&(z=I,$=E)}return $},j=function(){for(var z=8;z<f-8;z+=1)b[z][6]==null&&(b[z][6]=z%2==0);for(var $=8;$<f-8;$+=1)b[6][$]==null&&(b[6][$]=$%2==0)},Z=function(){for(var z=r.getPatternPosition(y),$=0;$<z.length;$+=1)for(var E=0;E<z.length;E+=1){var I=z[$],D=z[E];if(b[I][D]==null)for(var W=-2;W<=2;W+=1)for(var ee=-2;ee<=2;ee+=1)W==-2||W==2||ee==-2||ee==2||W==0&&ee==0?b[I+W][D+ee]=!0:b[I+W][D+ee]=!1}},te=function(z){for(var $=r.getBCHTypeNumber(y),E=0;E<18;E+=1){var I=!z&&($>>E&1)==1;b[Math.floor(E/3)][E%3+f-8-3]=I}for(var E=0;E<18;E+=1){var I=!z&&($>>E&1)==1;b[E%3+f-8-3][Math.floor(E/3)]=I}},me=function(z,$){for(var E=O<<3|$,I=r.getBCHTypeInfo(E),D=0;D<15;D+=1){var W=!z&&(I>>D&1)==1;D<6?b[D][8]=W:D<8?b[D+1][8]=W:b[f-15+D][8]=W}for(var D=0;D<15;D+=1){var W=!z&&(I>>D&1)==1;D<8?b[8][f-D-1]=W:D<9?b[8][15-D-1+1]=W:b[8][15-D-1]=W}b[f-8][8]=!z},ke=function(z,$){for(var E=-1,I=f-1,D=7,W=0,ee=r.getMaskFunction($),X=f-1;X>0;X-=2)for(X==6&&(X-=1);;){for(var ve=0;ve<2;ve+=1)if(b[I][X-ve]==null){var Le=!1;W<z.length&&(Le=(z[W]>>>D&1)==1);var re=ee(I,X-ve);re&&(Le=!Le),b[I][X-ve]=Le,D-=1,D==-1&&(W+=1,D=7)}if(I+=E,I<0||f<=I){I-=E,E=-E;break}}},U=function(z,$){for(var E=0,I=0,D=0,W=new Array($.length),ee=new Array($.length),X=0;X<$.length;X+=1){var ve=$[X].dataCount,Le=$[X].totalCount-ve;I=Math.max(I,ve),D=Math.max(D,Le),W[X]=new Array(ve);for(var re=0;re<W[X].length;re+=1)W[X][re]=255&z.getBuffer()[re+E];E+=ve;var ze=r.getErrorCorrectPolynomial(Le),Re=a(W[X],ze.getLength()-1),is=Re.mod(ze);ee[X]=new Array(ze.getLength()-1);for(var re=0;re<ee[X].length;re+=1){var as=re+is.getLength()-ee[X].length;ee[X][re]=as>=0?is.getAt(as):0}}for(var ls=0,re=0;re<$.length;re+=1)ls+=$[re].totalCount;for(var ao=new Array(ls),hn=0,re=0;re<I;re+=1)for(var X=0;X<$.length;X+=1)re<W[X].length&&(ao[hn]=W[X][re],hn+=1);for(var re=0;re<D;re+=1)for(var X=0;X<$.length;X+=1)re<ee[X].length&&(ao[hn]=ee[X][re],hn+=1);return ao},ne=function(z,$,E){for(var I=l.getRSBlocks(z,$),D=d(),W=0;W<E.length;W+=1){var ee=E[W];D.put(ee.getMode(),4),D.put(ee.getLength(),r.getLengthInBits(ee.getMode(),z)),ee.write(D)}for(var X=0,W=0;W<I.length;W+=1)X+=I[W].dataCount;if(D.getLengthInBits()>X*8)throw"code length overflow. ("+D.getLengthInBits()+">"+X*8+")";for(D.getLengthInBits()+4<=X*8&&D.put(0,4);D.getLengthInBits()%8!=0;)D.putBit(!1);for(;!(D.getLengthInBits()>=X*8||(D.put(w,8),D.getLengthInBits()>=X*8));)D.put(k,8);return U(D,I)};A.addData=function(z,$){$=$||"Byte";var E=null;switch($){case"Numeric":E=c(z);break;case"Alphanumeric":E=p(z);break;case"Byte":E=u(z);break;case"Kanji":E=g(z);break;default:throw"mode:"+$}C.push(E),T=null},A.isDark=function(z,$){if(z<0||f<=z||$<0||f<=$)throw z+","+$;return b[z][$]},A.getModuleCount=function(){return f},A.make=function(){if(y<1){for(var z=1;z<40;z++){for(var $=l.getRSBlocks(z,O),E=d(),I=0;I<C.length;I++){var D=C[I];E.put(D.getMode(),4),E.put(D.getLength(),r.getLengthInBits(D.getMode(),z)),D.write(E)}for(var W=0,I=0;I<$.length;I++)W+=$[I].dataCount;if(E.getLengthInBits()<=W*8)break}y=z}K(!1,Q())},A.createTableTag=function(z,$){z=z||2,$=typeof $>"u"?z*4:$;var E="";E+='<table style="',E+=" border-width: 0px; border-style: none;",E+=" border-collapse: collapse;",E+=" padding: 0px; margin: "+$+"px;",E+='">',E+="<tbody>";for(var I=0;I<A.getModuleCount();I+=1){E+="<tr>";for(var D=0;D<A.getModuleCount();D+=1)E+='<td style="',E+=" border-width: 0px; border-style: none;",E+=" border-collapse: collapse;",E+=" padding: 0px; margin: 0px;",E+=" width: "+z+"px;",E+=" height: "+z+"px;",E+=" background-color: ",E+=A.isDark(I,D)?"#000000":"#ffffff",E+=";",E+='"/>';E+="</tr>"}return E+="</tbody>",E+="</table>",E},A.createSvgTag=function(z,$,E,I){var D={};typeof arguments[0]=="object"&&(D=arguments[0],z=D.cellSize,$=D.margin,E=D.alt,I=D.title),z=z||2,$=typeof $>"u"?z*4:$,E=typeof E==Line truncated
|
||||
`}return E%2&&z>0?Re.substring(0,Re.length-E-1)+Array(E+1).join("▀"):Re.substring(0,Re.length-1)};return A.createASCII=function(z,$){if(z=z||1,z<2)return fe($);z-=1,$=typeof $>"u"?z*2:$;var E=A.getModuleCount()*z+$*2,I=$,D=E-$,W,ee,X,ve,Le=Array(z+1).join("██"),re=Array(z+1).join(" "),ze="",Re="";for(W=0;W<E;W+=1){for(X=Math.floor((W-I)/z),Re="",ee=0;ee<E;ee+=1)ve=1,I<=ee&&ee<D&&I<=W&&W<D&&A.isDark(X,Math.floor((ee-I)/z))&&(ve=0),Re+=ve?Le:re;for(X=0;X<z;X+=1)ze+=Re+`
|
||||
`}return ze.substring(0,ze.length-1)},A.renderTo2dContext=function(z,$){$=$||2;for(var E=A.getModuleCount(),I=0;I<E;I++)for(var D=0;D<E;D++)z.fillStyle=A.isDark(I,D)?"black":"white",z.fillRect(I*$,D*$,$,$)},A};t.stringToBytesFuncs={default:function(P){for(var R=[],w=0;w<P.length;w+=1){var k=P.charCodeAt(w);R.push(k&255)}return R}},t.stringToBytes=t.stringToBytesFuncs.default,t.createStringToBytes=function(P,R){var w=(function(){for(var y=h(P),O=function(){var j=y.read();if(j==-1)throw"eof";return j},b=0,f={};;){var T=y.read();if(T==-1)break;var C=O(),A=O(),K=O(),Y=String.fromCharCode(T<<8|C),Q=A<<8|K;f[Y]=Q,b+=1}if(b!=R)throw b+" != "+R;return f})(),k=63;return function(y){for(var O=[],b=0;b<y.length;b+=1){var f=y.charCodeAt(b);if(f<128)O.push(f);else{var T=w[y.charAt(b)];typeof T=="number"?(T&255)==T?O.push(T):(O.push(T>>>8),O.push(T&255)):O.push(k)}}return O}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var P=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],R=1335,w=7973,k=21522,y={},O=function(b){for(var f=0;b!=0;)f+=1,b>>>=1;return f};return y.getBCHTypeInfo=function(b){for(var f=b<<10;O(f)-O(R)>=0;)f^=R<<O(f)-O(R);return(b<<10|f)^k},y.getBCHTypeNumber=function(b){for(var f=b<<12;O(f)-O(w)>=0;)f^=w<<O(f)-O(w);return b<<12|f},y.getPatternPosition=function(b){return P[b-1]},y.getMaskFunction=function(b){switch(b){case s.PATTERN000:return function(f,T){return(f+T)%2==0};case s.PATTERN001:return function(f,T){return f%2==0};case s.PATTERN010:return function(f,T){return T%3==0};case s.PATTERN011:return function(f,T){return(f+T)%3==0};case s.PATTERN100:return function(f,T){return(Math.floor(f/2)+Math.floor(T/3))%2==0};case s.PATTERN101:return function(f,T){return f*T%2+f*T%3==0};case s.PATTERN110:return function(f,T){return(f*T%2+f*T%3)%2==0};case s.PATTERN111:return function(f,T){return(f*T%3+(f+T)%2)%2==0};default:throw"bad maskPattern:"+b}},y.getErrorCorrectPolynomial=function(b){for(var f=a([1],0),T=0;T<b;T+=1)f=f.multiply(a([1,i.gexp(T)],0));return f},y.getLengthInBits=function(b,f){if(1<=f&&f<10)switch(b){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+b}else if(f<27)switch(b){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+b}else if(f<41)switch(b){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+b}else throw"type:"+f},y.getLostPoint=function(b){for(var f=b.getModuleCount(),T=0,C=0;C<f;C+=1)for(var A=0;A<f;A+=1){for(var K=0,Y=b.isDark(C,A),Q=-1;Q<=1;Q+=1)if(!(C+Q<0||f<=C+Q))for(var j=-1;j<=1;j+=1)A+j<0||f<=A+j||Q==0&&j==0||Y==b.isDark(C+Q,A+j)&&(K+=1);K>5&&(T+=3+K-5)}for(var C=0;C<f-1;C+=1)for(var A=0;A<f-1;A+=1){var Z=0;b.isDark(C,A)&&(Z+=1),b.isDark(C+1,A)&&(Z+=1),b.isDark(C,A+1)&&(Z+=1),b.isDark(C+1,A+1)&&(Z+=1),(Z==0||Z==4)&&(T+=3)}for(var C=0;C<f;C+=1)for(var A=0;A<f-6;A+=1)b.isDark(C,A)&&!b.isDark(C,A+1)&&b.isDark(C,A+2)&&b.isDark(C,A+3)&&b.isDark(C,A+4)&&!b.isDark(C,A+5)&&b.isDark(C,A+6)&&(T+=40);for(var A=0;A<f;A+=1)for(var C=0;C<f-6;C+=1)b.isDark(C,A)&&!b.isDark(C+1,A)&&b.isDark(C+2,A)&&b.isDark(C+3,A)&&b.isDark(C+4,A)&&!b.isDark(C+5,A)&&b.isDark(C+6,A)&&(T+=40);for(var te=0,A=0;A<f;A+=1)for(var C=0;C<f;C+=1)b.isDark(C,A)&&(te+=1);var me=Math.abs(100*te/f/f-50)/5;return T+=me*10,T},y})(),i=(function(){for(var P=new Array(256),R=new Array(256),w=0;w<8;w+=1)P[w]=1<<w;for(var w=8;w<256;w+=1)P[w]=P[w-4]^P[w-5]^P[w-6]^P[w-8];for(var w=0;w<255;w+=1)R[P[w]]=w;var k={};return k.glog=function(y){if(y<1)throw"glog("+y+")";return R[y]},k.gexp=function(y){for(;y<0;)y+=255;for(;y>=256;)y-=255;return P[y]},k})();function a(P,R){if(typeof P.length>"u")throw P.length+"/"+R;var w=(function(){for(var y=0;y<P.length&&P[y]==0;)y+=1;for(var O=new Array(P.length-y+R),b=0;b<P.length-y;b+=1)O[b]=P[b+y];return O})(),k={};return k.getAt=function(y){return w[y]},k.getLength=function(){return w.length},k.multiply=function(y){for(var O=new Array(k.getLength()+y.getLength()-1),b=0;b<k.getLength();b+=1)for(var f=0;f<y.getLength();f+=1)O[b+f]^=i.gexp(i.glog(k.getAt(b))+i.glog(y.getAt(f)));return a(O,0)},k.mod=function(y){if(k.getLengt
Line truncated
|
||||
`)}function ol(t){let e=new Map(t.people.map(s=>[s.id,s.name])),o=new Map(t.people.flatMap(s=>s.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Xe(t,e,o,s="",r=[]){let i=ol(t),a=[...e.map(u=>({ts:u.ts,category:Zt(u.type),type:u.type,person:u.person?i.people.get(u.person)??u.pname??u.person:"",device:u.device?i.devices.get(u.device)??u.dname??u.device:"",detail:u.detail??"",where:u.where??"",by:Ve(u)??""})),...r.map(u=>({ts:u.ts,category:"system",type:`${u.src}.${u.level}`,person:"",device:"",detail:`${u.who?`${u.who} `:""}${u.msg}${u.detail?`
|
||||
${u.detail}`:""}`,where:Qt(u.src),by:""}))].sort((u,g)=>u.ts-g.ts).map(({ts:u,...g})=>({time:new Date(u*1e3).toISOString(),...g})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${s?`-${s}`:""}-${l}.${o}`;if(o==="json"){Ae(d,JSON.stringify(a,null,2),"application/json");return}let c=["time","category","type","person","device","detail","where","by"],p={time:_("Time"),category:_("Category"),type:_("Type"),person:_("Person"),device:_("Device"),detail:_("Detail"),where:_("Where"),by:_("By")};Ae(d,nr(c,a,p),"text/csv")}var sl=["","7","30","90"],rl=t=>t?G(Number(t),"Older than %s day","Older than %s days"):_("Everything"),or=t=>t?G(t,"%s event removed","%s events removed"):_("Nothing matched");function dt(t,e,o,s,r,i=!1){let a=n("select",{class:"cbi-input-select"},[n("option",{value:""},_("All categories")),...Rt.map(d=>n("option",{value:d,selected:d===r?"selected":null},Ke(d))),i?n("option",{value:"system",selected:r==="system"?"selected":null},_("System")):""]),l=n("select",{class:"cbi-input-select"},sl.map(d=>n("option",{value:d},rl(d))));ae(t,[n("p",{class:"dl-muted"},`${e} ${_("This cannot be undone; export first if you want a copy.")}`),n("label",{class:"dl-fld"},[n("span",{class:"dl-fld-label"},_("Category")),a]),n("label",{class:"dl-fld"},[n("span",{class:"dl-fld-label"},_("Which events")),l])],[de()," ",H(_("Clear"),async()=>{let d=0;if(a.value!=="system")try{d+=(await N.logsClear({...o,category:a.value,older_days:l.value})).removed}catch(c){F(_e(c),"error",1e4);return}if(i&&(a.value==="system"||a.value===""))try{d+=(await N.serviceLogClear(l.value)).removed}catch(c){le();let p=m(_("The service log was not cleared: %s"),_e(c));F(a.value==="system"?p:`${m(_("Activity: %s."),or(d).toLowerCase())} ${p}`,"error",1e4),s();return}le(),F(or(d),"success",3e3),s()},"negative")])}function It(t,e,o,s){let r=t==="device"?m(_("Clears %s's daily and monthly traffic history. Their person's totals and data limit are not changed."),o):t==="person"?m(_("Clears %s's traffic history and that of their devices. Their data limit starts again from zero."),o):_("Clears traffic history for everyone. Data limits start again from zero.");ae(t==="all"?_("Reset all traffic history?"):m(_("Reset traffic history for %s?"),o),[n("p",{class:"dl-muted"},r)],[de()," ",H(_("Reset"),async()=>{await q(()=>N.usageClear(t,e),_("Traffic history reset"))&&(le(),s())},"negative")])}var il={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"",s4:"",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},al={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function ll(t){let e={};for(let[o,s]of Object.entries(al))t[o]!=null&&t[o]!==""&&(e[s]=String(t[o]));return e}function dl(t,e){let o=t.amnezia,s=o.obfuscation??{},r=d=>s[d]!=null&&s[d]!==""?String(s[d]):il[d],i=o.host.replace(/^\[(.*)\]$/,"$1"),a={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...ll(s),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:t.conf.replace(/\r?\n/g,`\r
|
||||
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(a),port:String(o.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0],l.dns2=o.dns[1]||o.dns[0]),l}function cl(t){let e="";for(let o=0;o<t.length;o+=32768)e+=String.fromCharCode(...t.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pl(t){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([t]).stream().pipeThrough(new e.CompressionStream("deflate")),s=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+s.length);return new DataView(r.buffer).setUint32(0,t.length,!1),r.set(s,4),r}catch{return null}}async function Po(t,e,o=!0){let s=new TextEncoder().encode(JSON.stringify(dl(t,e))),r=o?await pl(s):null;return`vpn://${cl(r??s)}`}function rr(){return[{id:"off",title:_("Off"),ic:"zap",stealth:0,speed:4,text:_("Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block."),apps:_("Any WireGuard app"),short:_("Any WireGuard app")},{id:"balanced",title:_("Balanced"),ic:"shield",stealth:3,speed:4,needs:"v2",text:_("AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk."),apps:_("AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps"),short:_("AmneziaWG 2.0+ apps")},{id:"max",title:_("Maximum"),ic:"lock",stealth:4,speed:3,needs:"v3",text:_("AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS."),apps:_("Apps with AmneziaWG 3.1 (current AmneziaVPN)"),short:_("AmneziaWG 3.1 apps")}]}var Xt=t=>rr().find(e=>e.id===t),$n=t=>t.v3?"max":t.v2?"balanced":"off",en=t=>t==="standard"?_("Standard (old)"):t==="strong"?_("Strong (old)"):null;function ul(t,e){return e?t==="v2"?_("Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on)."):_("Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."):t==="v2"?_("Needs AmneziaWG on the router."):_("Needs AmneziaWG 3.1 on the router: install it first.")}function sr(t,e){return n("span",{class:"dl-dots",title:m(_("%s: %s of 4"),e,t)},[n("span",{class:"dl-dots-label"},e),n("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>n("i",{class:o<t?"on":""})))])}function Dn(t,e,o,s,r=!0){let i=n("div",{class:"dl-methods",role:"radiogroup","aria-label":_("Disguise method")}),a=()=>dom.content(i,rr().map(l=>{let d=!l.needs||t[l.needs],c=l.id===e;return n("button",{type:"button",role:"radio","aria-checked":c?"true":"false","aria-disabled":d?null:"true",class:`dl-method${c?" on":""}${d?"":" off"}`,click:()=>{!d||c||(e=l.id,a(),o(l.id))}},[n("div",{class:"dl-method-head"},[n("span",{class:"dl-method-ic"},v(l.ic)),n("b",{},l.title),l.id===s?n("span",{class:"dl-pill ok"},_("Current")):""]),n("p",{},l.text),n("div",{class:"dl-method-meters"},[sr(l.stealth,_("Stealth")),sr(l.speed,_("Speed"))]),n("div",{class:"dl-method-foot"},d?[v(l.id==="off"?"wireguard":"amneziawg"),n("span",{},l.apps)]:[v("alert"),n("span",{},ul(l.needs,r))])])}));return a(),i}function ir(t,e){return n("div",{class:"dl-corehead"},[n("h3",{},t),e?n("span",{class:"dl-sub"},e):""])}var ar=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function ml(t,e){let o=p=>p==="header_protection_key"?e:t[p]!=null&&t[p]!=="",s=ar.filter(([p])=>o(p));if(!s.length)return null;let r=(p,u)=>n("span",{class:"dl-pv"},[n("i",{},u),n("b",{},p==="header_protection_key"?_("set","key"):t[p])]),i=(p,u,g,M)=>{let x=ar.filter(([h])=>M.includes(h)&&o(h));return x.length?n("div",{class:"dl-pgroup"},[n("div",{class:"dl-pgroup-head"},[v(u),n("b",{},p)]),n("p",{},g),n("div",{class:"dl-pvals"},x.map(([h,S])=>r(h,S)))]):""},a=Number(t.jc||0),l=(t.i1??"").includes("0x8580")?_("A first packet shaped like a DNS answer."):_("Extra packets sent before the handshake."),d=s.filter(([p])=>p!=="header_protection_key").map(([p,u])=>`${u} = ${t[p]}`).join(`
|
||||
`),c=n("div",{class:"dl-pgrid"},[i(_("Junk packets"),"zap",a?m(N_(a,"%s random packet of %s–%s bytes before each handshake.","%s random packets of %s–%s bytes before each handshake."),V(a),t.jmin,t.jmax):_("No junk packets."),["jc","jmin","jmax"]),i(_("Padding"),"archive",_("Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard."),["s1","s2","s3","s4"]),i(_("Packet types"),"key",_("The values that replace WireGuard’s recognisable message types."),["h1","h2","h3","h4"]),i(_("Signatures"),"globe",l,["i1","i2","i3","i4","i5"]),i(_("Protection"),"lock",_("AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets."),["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),i(_("Timing"),"clock",_("Handshake and key timers vary within these ranges instead of WireGuard’s fixed values."),["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return n("details",{class:"dl-params"},[n("summary",{},[v("chevron"),n("span",{},_("Current parameters")),n("span",{class:"dl-pcount"},String(s.length)),n("span",{class:"dl-spacer"}),n("button",{type:"button",class:"dl-linkbtn",click:p=>{p.preventDefault(),xe(d,e?_("Parameters copied. The header protection key is in each device’s file."):_("Parameters copied"))}},_("Copy as config"))]),c])}function lr(t,e){if(/^\s*\[.+\]\s*$/.test(t))return n("span",{class:"dl-conf-sec"},t);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(t);if(!o)return document.createTextNode(t);let s=/^(\s*)(PrivateKey|PresharedKey)\b/.test(t);return n("span",{},[n("span",{class:"dl-conf-k"},o[1])," ",s&&!e?n("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function hl(t){let e=!1,o=n("pre",{class:"dl-conf"}),s=()=>dom.content(o,t.conf.split(`
|
||||
`).flatMap((a,l)=>l?[`
|
||||
`,lr(a,e)]:[lr(a,e)])),r=n("button",{type:"button",class:"dl-chipbtn",click:a=>{a.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?_("Hide key"):_("Show key")]),s()}},[v("key"),_("Show key")]);s();let i=new Blob([t.conf]).size;return n("div",{class:"dl-stack gap8"},[n("div",{class:"dl-filecard"},[n("span",{class:"dl-filecard-ic"},".conf"),n("span",{class:"dl-stack"},[n("span",{class:"dl-mono dl-ellipsis"},t.filename),n("span",{class:"dl-sub"},`AmneziaWG · ${G(i,"%s byte","%s bytes")}`)]),H([v("download")," ",_("Download")],()=>Ae(t.filename,t.conf,"application/octet-stream"),"positive")]),n("details",{class:"dl-params"},[n("summary",{},[v("chevron"),n("span",{},_("Configuration")),n("span",{class:"dl-spacer"}),r,n("button",{type:"button",class:"dl-chipbtn",click:a=>{a.preventDefault(),xe(t.conf,_("Configuration copied"))}},[v("copy"),_("Copy")])]),o])])}function $o(t){let e=t.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([s,r])=>r==null||r===""||r===(o[s]??"0"))}async function fl(t,e="file"){if(!t.has_private_key)return n("div",{class:"dl-hint"},_("This device generated its own keys in the browser, so its full configuration only exists on that device."));let o=await Po(t,t.server),s={qr:()=>n("div",{class:"dl-qr-pane"},[_n(t.conf),n("span",{class:"dl-sub"},$o(t)?_("Scan with AmneziaVPN or any WireGuard app on the device."):_("Scan with AmneziaVPN or AmneziaWG on the device."))]),key:()=>n("div",{class:"dl-stack gap8"},[n("div",{class:"dl-linkbox"},[n("span",{class:"dl-mono"},o),H(_("Copy"),()=>xe(o,_("Key copied")))]),n("span",{class:"dl-sub"},m(_("AmneziaVPN → %s. Keep it private."),["+",_("Insert","AmneziaVPN app"),_("Continue","AmneziaVPN app")].join(" → ")))]),file:()=>hl(t)},r=n("div",{class:"dl-connect-body"}),i=n("div",{class:"dl-seg"}),a=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,s[l]())};for(let[l,d]of[["file",_("File")],["key",_("Key")],["qr",_("QR code")]])i.appendChild(n("button",{type:"button","data-id":l,click:()=>a(l)},d));return a(e),n("div",{class:"dl-stack gap12"},[i,r])}async function gl(t,e,o,s){let r=Xt(o),a=t.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await pe(s?_("Generate new disguise values?"):m(_("Switch to %s?"),r.title),[G(a,"%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you).","%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)."),o==="max"?_("They need an app with AmneziaWG 3.1."):o==="balanced"?_("They need an app with AmneziaWG 2.0 or newer."):"",t.st.servers.length===1&&a?_("To keep the old disguise for some people, add a second server and move them there."):""].filter(Boolean).join(" "),s?_("Generate and apply"):_("Switch and apply"),!0)&&await q(()=>N.serverObfuscation(e.id,o),s?_("New values applied"):m(_("%s applied"),r.title))&&(F(_("Devices are marked “Update config” until they import again."),"info",6e3),await t.refresh())}function vl(t,e){let o=t.st,s=ue(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=ue(e.mtu?String(e.mtu):"",{placeholder:_("Auto"),inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=ue(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=Xt(e.preset)?e.preset:void 0,l=a??$n(o.awg),d=H("",()=>gl(t,e,l,l===a),"neutral"),c=()=>dom.content(d,l===a?[v("reset")," ",_("Generate new values")]:[m(_("Switch to %s"),Xt(l).title)]);c();let p=o.awg_state?.tools!==!1,u=[],g=Ce(_("UDP port"),s,()=>Jt(Number(s.value),u,[_("Opened on the WAN firewall automatically."),Number(s.value)===4500?_("4500 is IPsec’s port: most networks let it through."):""].filter(Boolean).join(" ")));N.serverPorts(e.id).then(h=>{u=h.udp_taken??[],g.refresh()}).catch(()=>{});let M=Ce("MTU",r,()=>$s(r.value,e.mtus)),x=Ce(_("Keep-alive"),i,()=>Ds(i.value));return Vt("",[ir("AmneziaWG",e.ifname),ye("globe",_("Listening"),_("Where devices reach this core from the internet"),[g]),ye("file",_("In every device configuration"),_("Changing these marks devices “Update config” until they import again"),[M,x]),ye("shield",_("Disguise"),_("So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"),[en(e.preset)?yt("warn",oe(_("%s is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to %s or %s: devices import their configuration again."),n("b",{},en(e.preset)),n("b",{},_("Balanced")),n("b",{},_("Maximum")))):"",Dn(o.awg,l,h=>{l=h,c()},a,p),p&&!o.awg.v3?yt("info",oe(_("This router runs an older AmneziaWG. %s becomes available with kmod-amneziawg and amneziawg-tools 3.1."),n("b",{},_("Maximum")))):"",ml(e.obf??{},e.hpk)??"",n("div",{class:"dl-row-end"},[n("span",{class:"dl-sub"},_("Applies at once: every AmneziaWG device imports its configuration again.")),d])]),n
Line truncated
|
||||
`),_("Log copied")))]),p,u]),[g],"wide"),x([n("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?_("Checking…"):_("Working…"))]);let S=o??null,B=o?.id,P,R=0,w=T=>{B!==T.id&&(B=T.id,e.onJob?.(T))};if(o)e.onJob?.(o);else try{let T=await N.updatesStatus().catch(()=>null);P=T?.job?.id,R=T?.now??0;let C=await N.updatesRun(t);C.job&&C.job.state==="running"&&C.job.id!==P&&(S=C.job,w(C.job))}catch(T){return M=[_e(T)],p.textContent=M[0],dom.content(u,n("div",{class:"dl-comp-status warn"},[v("alert"),n("span",{},_e(T))])),x([h(!0)]),F(_e(T),"error"),null}let k=null,y=0;for(;;){if(await Vo(1e3),k=await N.updatesStatus().catch(()=>null),!k){if(++y>60)break;continue}y=0;let T=k.job;if(!T||!oi(T,B,P,R)){if(Date.now()-i>15e3)break;continue}if(w(T),S=T,T.log.length){M=T.log;let C=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=M.join(`
|
||||
`),C&&(p.scrollTop=p.scrollHeight)}if(l.textContent=ti(T,e.version??""),!l.isConnected&&l.textContent&&a.after(l),c.textContent=ei((T.finished??k.now)-T.started),T.state==="running"){d.hidden=!T.phase,d.textContent=T.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!S||S.state==="running")return d.className="dl-pill warn",d.textContent=_("No answer"),dom.content(u,n("div",{class:"dl-comp-status warn"},[v("alert"),n("span",{},_("The router stopped answering. The job may still finish: reopen Components in a minute."))])),x([h()]),e.onDone?.(k),S;if(S.state==="failed")return d.className="dl-pill bad",d.textContent=_("Failed"),dom.content(u,n("div",{class:"dl-comp-status bad"},[v("x"),n("span",{},[n("b",{},(S.error??_("Operation failed")).replace(/\.$/,"")),r?"":`. ${_("Nothing else was changed.")}`])])),x([H(_("Copy log"),()=>xe(M.join(`
|
||||
`),_("Log copied"))),h(!0)]),F(`${Un(s)??_("Update","noun")}: ${S.error??_("failed")}`,"error"),e.onDone?.(k),S;if(d.className="dl-pill ok",d.textContent=_("Finished"),r&&k){let T=ni(k,s);if(dom.content(u,n("div",{class:`dl-comp-status ${T.tone}`},[v(T.tone==="ok"?"check":T.tone==="warn"?"alert":"download"),n("span",{},T.text)])),F(T.text,T.tone==="warn"?"warning":"success"),e.onDone?.(k),T.update&&e.onUpdate){let C=k;x([h(),H(m(_("Update to %s"),T.update),()=>e.onUpdate(C),"positive")])}else x([h()]),T.tone==="ok"&&setTimeout(()=>u.isConnected&&le(),1200);return S}let O=/^app:(lang:|nolang$)/.exec(S.component??"");if(O){let T=()=>{ui.menu?.flushCache(),location.reload()};return dom.content(u,n("div",{class:"dl-comp-status ok"},[v("check"),n("span",{},[n("b",{},O[1]==="nolang"?_("The translation is removed."):_("The translation is installed."))," ",_("Reloading the page…")])])),x([h(),H(_("Reload now"),T,"positive")]),await Vo(4e3),u.isConnected&&T(),S}if(s==="app"&&S.to){let T=S.to,C=n("span",{},_("Waiting for the router to restart its services…"));dom.content(u,n("div",{class:"dl-comp-status ok"},[v("check"),n("span",{},[n("b",{},m(_("Dawnline %s is installed."),T))," ",C])]));let A=()=>{ui.menu?.flushCache(),location.reload()};x([h(),H(_("Reload now"),A,"positive")]),F(m(_("Dawnline updated to %s"),T),"success",6e3);for(let K=1;K<=30;K++)if(C.textContent=m(_("Waiting for the router to restart its services (%s of 30)…"),K),await Vo(1500),(await N.updatesStatus().catch(()=>null))?.version===T)return C.textContent=_("Services are back. Reloading…"),setTimeout(A,800),S;return C.textContent=_("Services restarted. Reload the page to use the new version."),S}let b=[...S.result?.pkgs?.updated??[],...S.result?.pkgs?.installed??[]],f=s==="pkgs"?b.length?m(_("Updated %s"),b.join(", ")):_("Updated system packages"):s==="amneziawg"?S.to?m(_("AmneziaWG %s is installed"),S.to):_("AmneziaWG is installed"):_("Operation completed");return dom.content(u,n("div",{class:"dl-comp-status ok"},[v("check"),n("span",{},f)])),x([h()]),F(f,"success"),e.onDone?.(k),S}function Kl(t){return{https:[_("Install HTTPS for the portal?"),_("Installing HTTPS for the portal")],acme:[_("Install ACME certificates?"),_("Installing ACME certificates")],home:[_("Install the home-like link?"),_("Installing the home-like link")],awg:[_("Install AmneziaWG?"),_("Installing AmneziaWG")]}[t]}async function si(t,e,o,s){let[r,i]=Kl(e);return!await pe(r,o,_("Install"))||(await dn(t,{title:i}))?.state!=="done"?!1:(setTimeout(()=>s?.(),4e3),!0)}function Gn(t){return si("amneziawg:auto","awg",_("Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds."),t)}async function cn(t,e,o){return t==="awg"?Gn(o):e.length?si(`pkgs:${e.join(",")}`,t,m(_("%s from the OpenWrt feeds. Dawnline sets the rest up when they arrive."),e.join(", ")),o):!0}async function ri(t,e){if(t==="awg")return Gn(e);let o=await q(()=>N.updatesStatus());return o?cn(t,o.needs?.[t]??[],e):!1}var Vl=()=>[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn",_("VPN & tunnels")],["other",_("Other")]],Yl={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Yo(t){let e=n("b",{},oe(_("add its interface %s to their source interfaces yourself"),n("span",{class:"dl-mono"},t)));return[...oe(_("Off: internet traffic goes straight to the WAN, the fastest way. DNS still goes through this router. Proxies and filters here handle the tunnel only if you %s."),e)," ",n("span",{class:"dl-warn"},_("If the router’s DNS hands out proxy addresses, those sites won’t open without it."))]}function Jo(){return wt(_("Slower: every packet crosses the router twice. On a dual-core router expect up to a third less speed, and lost packets at full load."))}function ii(t,e,o){let s=t.id,r=e,i=n("div",{class:"dl-stack gap16"},n("section",{class:"dl-setsec"},n("div",{class:"dl-setsec-body"},n("p",{class:"dl-muted"},_("Loading interfaces…"))))),a,l=!0,d="",c=!0,p=!0,u="all",g=!1,M=Zr(r,s,o),x=new Set,h="",S=()=>JSON.stringify([p,l,l?"":d,c,[...x].sort()]),B=()=>a.detected.lan||a.saved.lan||"",P=()=>(l?a.detected.wan||a.saved.wan:d)||"",R=()=>new Map(a.devices.map(j=>[j.name,j])),w=()=>{let j=R();return[...c&&B()?[B()]:[],...[...x].filter(te=>te!==B())].filter(te=>te!==P()).map(te=>j.get(te)??{name:te,nets:[],missing:!0})},k=(j,Z)=>{a=j,Z&&(l=j.config.auto_wan,d=j.config.wan_device||j.detected.wan||j.saved.wan||"",c=j.config.auto_lan,p=j.config.lan_like,u=j.config.mesh??(j.config.device_mesh?"all":"off"),x=new Set(j.config.lan_devices),h=S()),Y()},y=async j=>{let Z=await N.interfaces(s).catch(te=>(F(te.message,"error"),null));Z&&k(Z,j)};function O(j){let Z=c&&j.name===B(),te=!!j.own||!!j.master||j.name===P()||Z;return Z||x.has(j.name)||!te&&(j.nets.length>0||!!j.missing)}function b(j){let Z=c&&j.name===B(),te=j.name===P(),me=!Z&&x.has(j.name),U=!(!!j.own||!!j.maste
Line truncated
|
||||
`).map(e=>zt(e)).join(`
|
||||
`);function qn(t,e,o,s){let r=t.by==="admin",i=zt(t.msg),a=n("div",{class:`dl-row dl-slog-row ${r?"dl-ev-by-admin":`dl-ev-by-system ${nd[t.level]??""}`}${t.detail?" has-detail":""}`},[r?n("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},v("admin")):n("span",{class:"dl-ev-tile sys",title:sd(t.level)},v(od[t.src]??"zap")),n("span",{class:"dl-row-main"},r?[...rd(t),t.note?n("span",{class:"dl-muted"},` · ${Xs(t.note)}`):"",t.detail?n("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",t.detail&&e?n("pre",{class:"dl-slog-detail"},ai(t.detail)):""]:[t.src==="awg"&&t.who&&t.who!=="AmneziaWG"?n("span",{class:"dl-ev-kind"},`${_("Server")} `):"",n("b",{class:"dl-sys-src",title:Qt(t.src)},t.who?t.src==="awg"?t.who:zt(t.who):Qt(t.src)),/^[:,]/.test(i)?"":" ",n("span",{class:"dl-muted"},i),t.detail?n("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",t.detail&&e?n("pre",{class:"dl-slog-detail"},ai(t.detail)):""]),n("span",{class:"dl-faint dl-nowrap",title:new Date(t.ts*1e3).toLocaleString(ie())},s)]);return t.detail&&a.addEventListener("click",l=>{l.target.closest("pre")||o()}),a}function li(t){let e=new Date(t*1e3),o=new Date,s=new Date;if(s.setDate(o.getDate()-1),e.toDateString()===o.toDateString())return _("Today");if(e.toDateString()===s.toDateString())return _("Yesterday");let r=e.toLocaleDateString(ie(),{weekday:"long",day:"numeric",month:"long"});return r.charAt(0).toLocaleUpperCase(ie())+r.slice(1)}var Ut=t=>Pt(t).toLocaleDateString(ie(),{day:"numeric",month:"short"}),pn=200,Wt=40;function di(t,e){let o=Math.max(1,...t.map(a=>Math.max(a[1],a[2]))),s=a=>t.map((l,d)=>`${e[d]*pn},${Wt-2-l[a]/o*(Wt-6)}`),r=s(2),i=s(1);return{area:`M${r.join(" L")} L${e[e.length-1]*pn},${Wt} L${e[0]*pn},${Wt}Z`,down:`M${r.join(" L")}`,up:`M${i.join(" L")}`}}var Kn=(t,e,o,s)=>n("div",{class:"dl-speed-col"},[n("span",{class:"dl-sub"},[n("span",{class:o},e),` ${t}`]),s]),ci=([t,e])=>[n("span",{},oe(_("Today %s"),n("b",{},se(t+e)))),n("span",{},[n("span",{class:"dl-dn"},"↓"),` ${se(e)} `,n("span",{class:"dl-up"},"↑"),` ${se(t)}`])];function pi(t,e,o,s=!1){let r=t.slice(-15),i=r[r.length-1],a=i&&e-i[0]<180,l=a?i[2]:0,d=a?i[1]:0,c;if(r.length>1&&!s){let u=di(r,r.map((g,M)=>M/(r.length-1)));c=kt(`<svg viewBox="0 0 ${pn} ${Wt}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true"><path d="${u.area}" class="area"/><path d="${u.down}" class="line"/><path d="${u.up}" class="line up"/></svg>`),we(c,()=>{let g=r[r.length-1];return[n("div",{class:"dl-tip-title"},new Date(g[0]*1e3).toLocaleTimeString(ie(),{hour:"2-digit",minute:"2-digit"})),n("div",{},`↓ ${We(g[2])} · ↑ ${We(g[1])}`)]})}else c=n("div",{class:"dl-speed-wait"},[n("i"),s?"":n("span",{},_("Collecting… 1 point a minute"))]);let p=u=>s?n("span",{class:"dl-speed-val off"},"—"):n("span",{class:"dl-speed-val"},We(u));return n("div",{class:"dl-bento-tile"},[n("div",{class:"dl-bento-head"},[n("span",{class:"dl-metric-label"},_("Speed now")),s?"":n("span",{class:"dl-sub"},_("last 15 min"))]),n("div",{class:"dl-speed-cols"},[Kn(_("Download","speed"),"↓","dl-dn",p(l)),Kn(_("Upload","speed"),"↑","dl-up",p(d))]),c,n("div",{class:"dl-speed-today"},ci(o))])}var Vn=class{constructor(){this.span=n("span",{class:"dl-sub"},_("last 2 min"));this.down=n("span",{class:"dl-speed-val"});this.up=n("span",{class:"dl-speed-val"});this.chart=kt(`<svg viewBox="0 0 ${pn} ${Wt}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true"><path class="area"/><path class="line"/><path class="line up"/></svg>`);this.wait=n("div",{class:"dl-speed-wait"});this.shown=this.wait;this.today=n("div",{class:"dl-speed-today"});this.el=n("div",{class:"dl-bento-tile"},[n("div",{class:"dl-bento-head"},[n("span",{class:"dl-metric-label"},_("Speed now")),this.span]),n("div",{class:"dl-speed-cols"},[Kn(_("Download","speed"),"↓","dl-dn",this.down),Kn(_("Upload","speed"),"↑","dl-up",this.up)]),this.wait,this.today])}update(e,o,s){let r=s||!!e.error;this.span.style.display=s?"none":"";for(let[l,d]of[[this.down,e.tx],[this.up,e.rx]])l.className=`dl-speed-val${r?" off":""}`,l.textContent=r?"—":We(d);let i=!r&&e.pts.length>1;if(i){let l=di(e.pts,e.xs),[d,c,p]=this.chart.querySelectorAll("path");d.setAttribute("d",l.area),c.setAttribute("d",l.down),p.setAttribute("d",l.up)}else dom.content(this.wait,[n("i"),s||e.early&&!e.error?"":n("span",{},e.error?m(_("Couldn't read the live speed: %s"),e.error):_("Collecting… 1 point a second"))]);let a=i?this.chart:this.wait;a!==this.shown&&(this.shown.replaceWith(a),this.shown=a),dom.content(this.today,ci(o))}};function Yn(t,e){let o=t.slice(-30),s=o.map(d=>d.rx+d.tx),r=Math.max(1,...s),i=s.reduce((d,c)=>d+c,0),a=s.reduce((d,c,p)=>c>s[d]?p:d,0),l=n("div",{class:"dl-bento-bars"},o.map((d,c)=>{let p=s[c],u=n("i",{class:c===o.length-1?"hi":"",style:`height:${Math.max(4,p/r*100)}%`}),g=n("span",{},[u]);return we(g,()=>[n("div",{class:"dl-tip-title"},c===o.length-1?`${_("Today")} · ${Ut(d.day)}`:Ut(d.day)),n("div",{},se(pLine truncated
|
||||
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(e.push(n("pre",{},i.join(`
|
||||
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){a(),i=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(a(),e.push(n("h5",{},o(c[2])))):p?(r.length&&a(),s||(s=n("ul",{}),e.push(s)),s.appendChild(n("li",{},o(p[1])))):d.trim()?(s&&(s=null),r.push(d.trim())):a()}return i&&e.push(n("pre",{},i.join(`
|
||||
`))),a(),e}function Si(t){let e=[],o=!1;for(let s of t.replace(/\r/g,"").split(`
|
||||
`)){let r=/^#{1,6}\s+(.*)$/.exec(s);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(s)&&(o=!1);o||e.push(s)}return e.join(`
|
||||
`).replace(/\n{3,}/g,`
|
||||
|
||||
`).trim()}async function mn(t,e,o,s){let r=n("div",{class:"dl-notes"},n("p",{class:"dl-muted dl-loading"},_("Loading release notes…"))),i=n("div",{class:"dl-op-head"}),a="";ae(o,[i,r],[H([v("copy")," ",_("Copy")],()=>xe(a,_("Release notes copied")))," ",de(_("Close"))],"wide");try{let l=await N.updatesNotes(t,e,s??"");a=Si(l.body||"");let d=Ei(l.url);dom.content(i,[l.published?n("span",{class:"dl-pill"},Ie(l.published)):"",l.prerelease?n("span",{class:"dl-pill warn"},_("Pre-release")):"",n("span",{class:"dl-spacer"}),d?n("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},[_("On GitHub")," ",v("open")]):""]),dom.content(r,a.trim()?Ti(a):n("p",{class:"dl-muted"},_("This release has no notes.")))}catch(l){dom.content(r,n("p",{class:"dl-muted"},_e(l)))}}function hd(t){let e={"6h":_("checks every 6 h"),"12h":_("checks every 12 h"),"1d":_("checks daily"),"7d":_("checks weekly")};return e[t]??e["1d"]}var ns=t=>t?Ie(t):"";function fd(t){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(t)?.[1];return e||(t.length<=90?t:`${t.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function $i(t,e){let o=t.st,s=o.policy,r=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,a=g=>()=>mn("app",g,m(_("What’s new in Dawnline %s"),g.replace(/^v/,""))),l=e?.tag&&(e.update||e.status==="latest")?gd(t,e.tag,e.update?o.version:""):null,d=e?.tag??i,c=s.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[s.interval]??24)*3600:0,p=(g,M)=>n("div",{class:"dl-stack gap4"},[n("span",{class:"dl-metric-label"},g),n("span",{class:"dl-comp-side-v"},M)]),u=[{label:_("What’s new"),ic:"file",run:a(i)},{label:_("Open on GitHub"),ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:m(_("Reinstall %s"),o.version),ic:"reset",warn:!0,run:()=>t.op("app:reinstall",_("Reinstalling Dawnline"),o.version)},r?{label:m(_("Roll back to %s"),r.version),ic:"archive",warn:!0,run:async()=>{await pe(m(_("Roll back to Dawnline %s?"),r.version),m(_("The copy kept on the router replaces %s. A backup of the settings is made first."),o.version),_("Roll back"))&&t.op("app:rollback",_("Rolling back Dawnline"),o.version)}}:null];return n("section",{class:"dl-panel flush dl-comp-hero"},[n("div",{class:"dl-comp-hero-main"},[n("div",{class:"dl-comp-hero-head"},[n("span",{class:"dl-group-ic"},v("sunrise")),n("b",{class:"dl-comp-name"},"Dawnline"),t.state("app",e,e?.latest??""),n("span",{class:"dl-spacer"}),t.round(()=>t.op("check:app",_("Checking Dawnline"),o.version),u,!0)]),n("div",{class:"dl-comp-verrow"},[n("div",{class:"dl-stack"},[n("div",{class:"dl-comp-big"},[o.version,e?.update?n("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?n("small",{class:"dl-faint"},m(_("release %s"),e.latest)):""]),n("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?m(_("released %s"),ns(e.published)):"":e?.status==="dev"?_("ahead of the latest release"):e?[_("latest release"),e.published?m(_("released %s"),ns(e.published)):""].filter(Boolean).join(" · "):_("not checked yet"))])]),l?.items.length?n("div",{class:"dl-stack gap4"},[n("ul",{class:"dl-comp-bullets"},l.items.map(g=>n("li",{},g))),l.total>l.items.length?n("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:a(d)},G(l.total-l.items.length,"+%s more in What’s new","+%s more in What’s new")):""]):"",e?.error?n("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?n("div",{class:"dl-comp-btns"},[H(_("Update now"),()=>t.op("app",_("Updating Dawnline"),o.version),"positive",{disabled:t.busy}),H(_("What’s new"),a(i))]):"",bd(t),vd(t)]),n("div",{class:"dl-comp-hero-side"},[p(_("Source"),[v("globe"),n("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p(_("Auto-update"),[s.auto?Se("ok",_("On")):Se("",_("Off")),n("span",{class:"dl-muted"},s.auto?s.mode==="immediate"?_("as soon as found"):m(s.interval==="7d"?_("weekly at %s"):_("daily at %s"),s.time):s.check?hd(s.interval):_("checks off"))]),p(_("Last check"),o.check?[ce(o.check.time,o.now),c>o.now?n("span",{class:"dl-faint"},`· ${m(_("next in %s"),st(c-o.now))}`):""]:[_("Never")]),p(_("Rollback"),r?[n("span",{class:"dl-mono"},r.version),n("span",{class:"dl-faint"},_("kept on flash"))]:[n("span",{class:"dl-muted"},s.keep?_("Kept after the next update"):_("Off"))])])])}function gd(t,e,o){if(t.notes.has(e))return t.notes.get(e)??null;t.notes.set(e,null);let s=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,a)=>a??"").trim();return(async()=>{let i=((await N.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
|
||||
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await N.updatesChanges(o,e).catch(()=>null))?.items??[]);let a={items:i.slice(0,3).map(l=>fd(s(l))),total:i.length};t.notes.set(e,a),a.items.length&&t.root.isConnected&&t.paint()})(),null}function Xn(t){return t==="ru"?_("Russian translation"):t}function vd(t){let e=(t.st.translations??[]).includes("ru"),o=be(e,Xn("ru"),r=>{t.op(r?"app:lang:ru":"app:nolang",r?_("Adding the Russian translation"):_("Removing the Russian translation"),t.st.version)});o.disabled=t.busy;let s=n("details",{class:"dl-params dl-comp-fold",open:t.langOpen?"open":null},[n("summary",{},[v("chevron"),n("span",{},_("Translation")),n("span",{class:"dl-sub"},e?_("Russian"):_("English only"))]),n("div",{class:"dl-params-body"},[n("div",{class:"dl-list"},[n("div",{class:"dl-row"},[n("span",{class:"dl-row-main dl-stack"},[n("b",{},Xn("ru")),n("span",{class:"dl-sub"},_("LuCI pages for Dawnline"))]),n("span",{class:"dl-comp-bact"},o)])])])]);return s.addEventListener("toggle",()=>t.langOpen=s.open),s}function bd(t){let e=n("div",{class:"dl-params-body"}),o=n("details",{class:"dl-params dl-comp-vers",open:t.versOpen?"open":null},[n("summary",{},[v("chevron"),n("span",{},_("Versions")),n("span",{class:"dl-sub"},_("install any release"))]),e]);return o.addEventListener("toggle",()=>{t.versOpen=o.open,t.versOpen&&eo(t,e)}),t.versOpen&&eo(t,e),o}async function eo(t,e){let o=ue("",{placeholder:_("Tag, e.g. 0.3.1"),class:"cbi-input-text dl-mono","aria-label":_("Release tag")}),s=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return F(_("Enter a release tag like 0.3.1"),"warning");Pi(t,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),s(o.value))});let r=n("div",{class:"dl-comp-tag"},[o,H(_("Install"),()=>s(o.value),"neutral",{disabled:t.busy})]),i=t.versPage,a=p=>{t.versPage=Math.max(1,t.versPage+p),eo(t,e)},l=p=>n("div",{class:"dl-comp-pager"},[n("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>a(-1)},_("← Newer")),n("span",{class:"dl-faint"},m(_("Page %s"),i)),n("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>a(1)},_("Older →"))]),d=t.versCache.get(i);if(!d){dom.content(e,[r,n("p",{class:"dl-muted dl-loading"},_("Loading versions…"))]);try{d=(await N.updatesReleases(i)).releases}catch(p){if(i!==t.versPage||!e.isConnected)return;dom.content(e,[r,n("div",{class:"dl-row-actions"},[n("span",{class:"dl-muted"},m(_("Failed to load versions: %s"),_e(p))),H(_("Try again"),()=>eo(t,e))]),l(!1)]);return}if(t.versCache.set(i,d),i!==t.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[r,n("p",{class:"dl-muted"},i>1?_("No more versions."):_("No versions found.")),l(!1)]);let c=t.st.version;dom.content(e,[r,...d.map(p=>{let u=p.tag.replace(/^v/,"");return n("div",{class:"dl-comp-ver"},[n("span",{class:"dl-mono"},u),n("span",{class:"dl-sub"},ns(p.published)),p.prerelease?Se("warn",_("Pre-release")):"",n("span",{class:"dl-comp-ic"},Pe("file",_("What’s new"),()=>mn("app",p.tag,m(_("What’s new in Dawnline %s"),u)))),u===c?Se("ok",_("Installed")):H(_("Install"),()=>Pi(t,p.tag),"neutral",{disabled:t.busy})])}),l(d.length>=5)])}async function Pi(t,e){let o=e.replace(/^v/,"");o.localeCompare(t.st.version,void 0,{numeric:!0})<0&&!await pe(m(_("Install Dawnline %s?"),o),m(_("It is older than %s. A backup of the settings is made first; restore it from Settings if something looks wrong."),t.st.version),_("Install"))||t.op(`app@${e}`,m(_("Installing Dawnline %s"),o),t.st.version)}function Di(t,e){let o=t.st,s=o.kept?.amneziawg,r=e?.sources??{},i=Object.keys(r),a=e?.current??null,l=a?r[a]:void 0,d=!!e?.ru,c=o.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];a&&p&&u.push({label:_("Reinstall this build"),warn:!0,ic:"reset",run:()=>t.op(`amneziawg:${a}${d?":ru":""}`,_("Reinstalling AmneziaWG"),p)}),s&&u.push({label:m(_("Roll back to %s"),s.version),ic:"archive",warn:!0,run:async()=>{await pe(m(_("Roll back AmneziaWG to %s?"),s.version),_("The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds."),_("Roll back"))&&t.op("amneziawg:rollback",_("Rolling back AmneziaWG"),p??void 0)}});let g=[e?.release?{label:_("What’s new"),ic:"file",run:()=>mn("amneziawg",e.release,m(_("What’s new in the %s build"),l?.label??"AmneziaWG"),a??"slava")}:null,{label:_("Open on GitHub"),ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((b,f,T)=>b!==null||f>0&&T[f-1]!==null),M=o.tunnels??[],x=M.length?M.length===1?m(_("Switching restarts the tunnel for a few seconds: %s. Devices keep their configurations."),M[0]):m(N_(M.length,"Switching restarts %s tunnel for a few seconds: %s. Devices keep their configurations.","Switching restarts %s tunnels for a few seconds: %s. Devices keep their configurations."),V(M.length),M.join(", ")):_("Switching takes a few
Line truncated
|
||||
`)}r.push(p),l+=c-1}let a=H([v("more")],()=>Te(a,[{label:_("Export CSV"),icon:v("download"),run:()=>Xe(o,s,"csv",e.id)},{label:_("Export JSON"),icon:v("download"),run:()=>Xe(o,s,"json",e.id)},null,{label:m(_("Clear %s's activity"),e.name),icon:v("trash"),danger:!0,run:()=>dt(m(_("Clear %s's activity"),e.name),m(_("Removes events about %s and their devices."),e.name),{person:e.id},()=>t.refresh())}]),"neutral",{title:_("Export or clear"),class:"cbi-button cbi-button-neutral dl-icon-only"});return n("div",{class:"dl-panel flush"},[n("div",{class:"dl-panel-head pad"},[n("h3",{},_("Activity")),n("span",{class:"dl-sub"},s.length>10?m(_("latest 10 of %s"),V(s.length)):""),n("span",{class:"dl-spacer"}),a]),r.length?r:n("div",{class:"dl-row dl-muted"},_("Nothing yet."))])}var no=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,s,r]=await Promise.all([N.status(30),e?N.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?N.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:s?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(a=>a.id===this.id);if(!o)return n("div",{class:"dl-empty"},[n("h3",{},_("Person not found")),n("p",{},_("They may have been removed.")),n("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},_("Back to Servers"))]);this.p=o;for(let a of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[a]=n("div",{});this.parts.devices.className="dl-person-devices";let s=n("div",{},[this.parts.crumbs,this.parts.head,n("div",{class:"dl-grid-person"},[n("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),n("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(a=>a.id===r.get("device"));return i?setTimeout(()=>Ye(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>pt(this.p,this.deviceOpts()),50),this.poller=nt({fetch:a=>{let l=a||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>s.isConnected,apply:(a,l)=>this.apply(a,l)}),s}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let s=this.st.people.find(r=>r.id===this.id);if(!s){o||(location.href=jt(this.p?.server));return}this.p=s,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let s=await q(()=>N.personUpdate(this.p.id,e),o);if(!s)return!1;this.poller?.claim();let r=this.st.people.findIndex(a=>a.id===this.p.id);return(i=s.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=s.person),this.p=s.person,this.paint(),!0}get today(){return Ge(this.series.length?this.series:this.st.series)}get core(){return Ot(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,server:this.st.servers.find(e=>e.id===this.p.server),events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return n("nav",{class:"dl-crumbs","aria-label":_("Breadcrumb")},[n("a",{href:jt(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??_("Servers")),n("span",{},"/"),n("a",{href:jt(e.server)},_("People")),n("span",{},"/"),n("span",{},e.name)])}paint(e=!1){Ne(this.parts.crumbs,this.crumbs(),e),Ne(this.parts.head,Ui(this),e),Ne(this.parts.traffic,Wi(this),e),Ne(this.parts.devices,Gi(this),e),Ne(this.parts.limits,Zi(this),e),this.paintPlaces(e),Ne(this.parts.activity,Xi(this),e)}paintPlaces(e=!1){let o=Qi(this);o&&Ne(this.parts.places,o,e&&!this.mapOpen)}};var Sd={ok:"check",warn:"alert",error:"x",skip:"pause"},oo=class{constructor(e,o,s,r){this.el=n("div",{});this.wdEl=n("div",{});this.checksEl=n("div",{class:"dl-panel"});this.recentEl=n("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=n("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=s,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,n("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,s)}async run(e){let o=e?await Jn(e):await N.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[n("div",{class:"dl-panel-head"},[n("h3",{},_("Checks"))]),n("p",{class:"dl-muted dl-loading"},_("Running checks…"))]);return}let o=e.filter(a=>a.status==="error").length,s=e.filter(a=>a.status==="
Line truncated
|
||||
`);function fa(){let t=document.createElement("style");return t.dataset.dawnline="1",t.textContent=Vd,t}function Lt(t){return()=>{let e=new t;return Object.assign({load:()=>e.load(),render:async s=>{let r=await e.render(s),i=document.createElement("div");return i.className="dl-root",i.append(fa(),r),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var ux=Lt(un),mx=Lt(Ct),hx=Lt(un),fx=Lt(Qn),gx=Lt(no),vx=Lt(io),bx=Lt(to);function ga(t){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${t?`?tab=${t}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var xx=ga(""),wx=ga("log");return baseclass.extend({ activity: wx, diagnostics: vx, health: xx, overview: ux, people: mx, person: gx, server: hx, settings: fx, updates: bx });
|
||||
@@ -0,0 +1,5 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require dawnline.app as app';
|
||||
|
||||
return view.extend(app.diagnostics());
|
||||
@@ -1,5 +1,11 @@
|
||||
#!/bin/sh
|
||||
# Load devices into a Dawnline tunnel whenever netifd (re)creates it.
|
||||
[ "$ACTION" = ifup ] || exit 0
|
||||
# Dawnline tunnels: log starts and stops to the service log, and load devices
|
||||
# whenever netifd (re)creates one.
|
||||
case "$ACTION" in ifup|ifdown|ifup-failed) ;; *) exit 0 ;; esac
|
||||
[ -n "$(uci -q get "network.$INTERFACE._dawnline")" ] || exit 0
|
||||
/usr/bin/dawnline sync >/dev/null 2>&1 &
|
||||
# In order (a quick down/up must not log up first).
|
||||
/usr/bin/dawnline iface-event "$ACTION" "$INTERFACE" >/dev/null 2>&1
|
||||
# A disabled Dawnline leaves the tunnels empty: nothing would enforce end
|
||||
# dates, limits or hours once the devices were loaded.
|
||||
[ "$ACTION" = ifup ] && /etc/init.d/dawnline enabled && /usr/bin/dawnline sync >/dev/null 2>&1 &
|
||||
exit 0
|
||||
@@ -21,9 +21,15 @@ start_portal() {
|
||||
hport="$(/usr/bin/dawnline portal-http-port 2>/dev/null)"
|
||||
[ -n "$hport" ] && http="-p 0.0.0.0:$hport -p [::]:$hport"
|
||||
|
||||
# Portal processes at once: each loads the whole model (a burst of 16 could
|
||||
# empty a 128 MB router), so four, and two on a router with little memory;
|
||||
# the rest of 64 connections wait their turn.
|
||||
local procs=4 mem
|
||||
mem="$(awk '/^MemTotal:/ { print int($2 / 1024) }' /proc/meminfo 2>/dev/null)"
|
||||
[ -n "$mem" ] && [ "$mem" -le 160 ] && procs=2
|
||||
procd_open_instance portal
|
||||
procd_set_param command /usr/sbin/uhttpd -f -h "$PORTAL_ROOT" -x /cgi-bin -E /cgi-bin/portal \
|
||||
-D -n 16 -N 64 -t 20 -T 30 -k 10 -A 1 \
|
||||
-D -n "$procs" -N 64 -t 20 -T 30 -k 10 -A 1 \
|
||||
-s "0.0.0.0:$port" -s "[::]:$port" -C "$cert" -K "$key" $http
|
||||
procd_set_param file "$cert"
|
||||
procd_set_param respawn 3600 5 0
|
||||
@@ -36,7 +42,8 @@ start_resolver() {
|
||||
procd_open_instance dns
|
||||
procd_set_param command /usr/libexec/dawnline/resolver
|
||||
procd_set_param file /var/etc/dawnline-dns.conf
|
||||
procd_set_param respawn 3600 5 0
|
||||
# A new config kills it (dawnline.resolver): back within a second, not five.
|
||||
procd_set_param respawn 3600 1 0
|
||||
procd_close_instance
|
||||
}
|
||||
|
||||
@@ -55,6 +62,14 @@ start_service() {
|
||||
start_resolver
|
||||
}
|
||||
|
||||
# Noted for the service log: the next agent start is a restart, not a crash or a boot.
|
||||
stop_service() {
|
||||
mkdir -p /var/run/dawnline
|
||||
date +%s > /var/run/dawnline/agent.stopped
|
||||
# Copies procd doesn't know about (started by hand, or left by an older version) go too.
|
||||
pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent' | xargs -r kill 2>/dev/null
|
||||
}
|
||||
|
||||
reload_service() {
|
||||
/usr/bin/dawnline apply >/dev/null 2>&1
|
||||
start
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
#!/bin/sh
|
||||
# Dawnline first-run / upgrade housekeeping.
|
||||
|
||||
# Locations are off by default since 0.5.2 (lookups send addresses to a third
|
||||
# party); a router that had them on by the old default keeps them on.
|
||||
if [ -f /etc/config/dawnline ] && [ -z "$(uci -q get dawnline.settings.geo_enabled)" ]; then
|
||||
uci -q set dawnline.settings.geo_enabled=1
|
||||
uci -q commit dawnline
|
||||
fi
|
||||
|
||||
[ -f /etc/config/dawnline ] || cat > /etc/config/dawnline <<'CFG'
|
||||
config settings 'settings'
|
||||
option portal_enabled '0'
|
||||
@@ -17,17 +24,45 @@ uci -q commit dawnline
|
||||
rm -f /etc/dawnline/alerts.json
|
||||
# Backups moved into Settings.
|
||||
rm -f /www/luci-static/resources/view/dawnline/backups.js
|
||||
# "Pause everyone" is gone: turning a server off does the same, so a
|
||||
# router left paused keeps its servers off instead of letting everyone in.
|
||||
if [ "$(uci -q get dawnline.settings.paused_all)" = 1 ]; then
|
||||
for s in $(uci -q show dawnline | sed -n 's/^dawnline\.\([^.=]*\)=server$/\1/p'); do uci -q set "dawnline.$s.enabled=0"; done
|
||||
fi
|
||||
uci -q delete dawnline.settings.paused_all
|
||||
uci -q commit dawnline
|
||||
# Portal assets moved out of the web root (served only with a valid code).
|
||||
rm -rf /usr/share/dawnline/portal/www/assets
|
||||
|
||||
# "Find home devices" (0.3.0) is gone: its option and dnsmasq records too.
|
||||
for s in $(uci -q show dawnline | sed -n 's/^dawnline\.\([^.]*\)\.bonjour=.*/\1/p'); do uci -q delete "dawnline.$s.bonjour"; done
|
||||
uci -q commit dawnline
|
||||
if ls /tmp/dnsmasq*.d/dawnline-bonjour.conf >/dev/null 2>&1; then
|
||||
rm -f /tmp/dnsmasq*.d/dawnline-bonjour.conf /var/run/dawnline/bonjour.json
|
||||
/etc/init.d/dnsmasq restart 2>/dev/null
|
||||
fi
|
||||
|
||||
# LuCI caches: menu index, and module URLs (?v= follows the opkg status time).
|
||||
rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null
|
||||
touch /usr/lib/opkg/status 2>/dev/null
|
||||
|
||||
# Cron restarts the agent when it stops ticking (Health → Watchdog).
|
||||
mkdir -p /etc/crontabs
|
||||
grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root || {
|
||||
echo '*/5 * * * * /usr/libexec/dawnline/heartbeat' >> /etc/crontabs/root
|
||||
/etc/init.d/cron restart 2>/dev/null
|
||||
}
|
||||
|
||||
/etc/init.d/rpcd reload
|
||||
# A reload keeps LuCI logins but sometimes misses the plugin; restart only then.
|
||||
sleep 2
|
||||
ubus list luci.dawnline >/dev/null 2>&1 || { /etc/init.d/rpcd restart; sleep 2; }
|
||||
/etc/init.d/dawnline enable
|
||||
/etc/init.d/dawnline restart
|
||||
# A fresh install starts the service; an upgrade restarts it only where the
|
||||
# admin had it on (a disabled Dawnline stays that way).
|
||||
if [ "$PKG_UPGRADE" = 1 ]; then
|
||||
/etc/init.d/dawnline enabled && /etc/init.d/dawnline restart
|
||||
else
|
||||
/etc/init.d/dawnline enable
|
||||
/etc/init.d/dawnline restart
|
||||
fi
|
||||
exit 0
|
||||
@@ -0,0 +1 @@
|
||||
/etc/dawnline/
|
||||
@@ -6,10 +6,38 @@ import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as view from 'dawnline.view';
|
||||
import * as ops from 'dawnline.ops';
|
||||
import { VERSION } from 'dawnline.util';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as backup from 'dawnline.backup';
|
||||
import * as pc from 'dawnline.portalcert';
|
||||
import * as watchdog from 'dawnline.watchdog';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as devices from 'dawnline.devices';
|
||||
import { L_ } from 'dawnline.i18n';
|
||||
import {
|
||||
VERSION, slog, slog_read, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
|
||||
} from 'dawnline.util';
|
||||
|
||||
const args = ARGV;
|
||||
/** Options that take no value. */
|
||||
const FLAGS = [ 'json', 'yes', 'conf' ];
|
||||
|
||||
// Options (--name value, or a bare --flag) can go anywhere; what is left are the words.
|
||||
const opts = {};
|
||||
const args = [];
|
||||
for (let i = 0; i < length(ARGV); i++) {
|
||||
let a = ARGV[i];
|
||||
if (a == '-n')
|
||||
a = '--n';
|
||||
if (substr(a, 0, 2) == '--') {
|
||||
let name = substr(a, 2);
|
||||
if (index(FLAGS, name) >= 0)
|
||||
opts[name] = true;
|
||||
else
|
||||
opts[name] = ARGV[++i] ?? '';
|
||||
}
|
||||
else
|
||||
push(args, a);
|
||||
}
|
||||
const cmd = args[0] ?? 'help';
|
||||
|
||||
function out(v) {
|
||||
@@ -17,10 +45,41 @@ function out(v) {
|
||||
}
|
||||
|
||||
function opt(name, dflt) {
|
||||
for (let i = 1; i < length(args); i++)
|
||||
if (args[i] == `--${name}`)
|
||||
return args[i + 1];
|
||||
return dflt;
|
||||
return opts[name] ?? dflt;
|
||||
}
|
||||
|
||||
/** Fixed-width columns: a header, then one line per row. */
|
||||
function table(cols, rows) {
|
||||
let w = map(cols, (c) => length(c));
|
||||
for (let r in rows)
|
||||
for (let i, v in r)
|
||||
w[i] = max(w[i], length(`${v}`));
|
||||
let line = (r) => rtrim(join(' ', map(r, (v, i) => sprintf(`%-${w[i]}s`, `${v}`))));
|
||||
out(line(cols));
|
||||
for (let r in rows)
|
||||
out(line(r));
|
||||
}
|
||||
|
||||
/** `--since 30m|2h|3d|YYYY-MM-DD` as a time, or null. */
|
||||
function since_time(s) {
|
||||
if (!s)
|
||||
return null;
|
||||
let m = match(s, /^([0-9]+)([mhd])$/);
|
||||
if (m)
|
||||
return time() - +m[1] * { m: 60, h: 3600, d: 86400 }[m[2]];
|
||||
m = match(s, /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/);
|
||||
if (m)
|
||||
return timelocal({ year: +m[1], mon: +m[2], mday: +m[3], hour: 0, min: 0, sec: 0 });
|
||||
die('--since takes 30m, 2h, 3d or a date like 2026-10-18.');
|
||||
}
|
||||
|
||||
/** "5m", "3h", "2d": how long ago, for the lists. */
|
||||
function ago(secs) {
|
||||
return secs < 3600 ? `${int(secs / 60)}m` : secs < 86400 ? `${int(secs / 3600)}h` : `${int(secs / 86400)}d`;
|
||||
}
|
||||
|
||||
function the_person(m, slug) {
|
||||
return m.people[slug ?? ''] ?? die(slug ? `Unknown person: ${slug}.` : 'Which person? Give their id (dawnline person ls).');
|
||||
}
|
||||
|
||||
function help() {
|
||||
@@ -29,26 +88,70 @@ function help() {
|
||||
Usage: dawnline <command>
|
||||
|
||||
apply Reconcile router configuration and runtime state
|
||||
sync Push devices and access rules to the tunnel
|
||||
sync Push devices and access rules to the tunnels
|
||||
status People and devices with live state (JSON)
|
||||
health Run health checks (JSON)
|
||||
person ls [--json] Everyone: id, name, access, state, devices, last seen
|
||||
person add <name> [--slug s] [--access lan|internet|both] [--devices n]
|
||||
[--expires YYYY-MM-DD] [--quota GB]
|
||||
person link <slug> Print the personal portal link
|
||||
person rm <slug> Remove a person and their devices
|
||||
device add <slug> <name> [--kind phone|computer|tablet|router]
|
||||
device conf <id> Print a device configuration
|
||||
[--expires YYYY-MM-DD] [--quota GB] [--server id]
|
||||
person link <id> Print the personal portal link
|
||||
person rm <id> [--yes] Remove a person and their devices (--yes when they have any)
|
||||
device ls [person] [--json]
|
||||
device add <person> <name> [--kind phone|computer|tablet|router] [--conf]
|
||||
device conf <id> Print a device configuration (.conf)
|
||||
device rm <id> Remove a device
|
||||
backup Create a backup in /etc/dawnline/backups
|
||||
portal-cert Print the certificate and key the portal uses
|
||||
portal-http-port Print the plain-HTTP port when an IP is among the portal addresses
|
||||
log [-n N] [--since 2h|3d|date] [--level error|down|repair|up|info] [--src awg|dawnline|portal] [--json]
|
||||
Service log: tunnel and service starts, stops, repairs (newest first)
|
||||
teardown Remove everything Dawnline created on the router
|
||||
version`);
|
||||
version
|
||||
|
||||
Exit codes: 0 done, 1 refused or failed, 2 unknown command. health exits 1 when a check fails.`);
|
||||
}
|
||||
|
||||
function commit(c) {
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
/*
|
||||
* netifd retries a tunnel that fails to start every few seconds (a kernel
|
||||
* module that won't load, AmneziaWG removed): one line per interface every
|
||||
* 10 minutes, with how many attempts failed meanwhile. A start clears it.
|
||||
*/
|
||||
const FAILS = `${RUN_DIR}/ifup-failed.json`;
|
||||
const FAIL_EVERY = 600;
|
||||
|
||||
function ifup_failed(ifname, who) {
|
||||
let now = time();
|
||||
// Attempts since the last line (a quiet spell starts a new count), and over how long.
|
||||
let r = with_lock('ifup-failed', () => {
|
||||
let all = read_json(FAILS, {});
|
||||
let f = all[ifname];
|
||||
if (!f || now - f.last > FAIL_EVERY)
|
||||
f = all[ifname] = { logged: 0, count: 0, since: now };
|
||||
f.count++;
|
||||
f.last = now;
|
||||
let out = null;
|
||||
if (now - f.logged >= FAIL_EVERY) {
|
||||
out = { n: f.count, mins: int((now - f.since) / 60) };
|
||||
f.logged = f.since = now;
|
||||
f.count = 0;
|
||||
}
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(FAILS, all, 0o600);
|
||||
return out;
|
||||
});
|
||||
if (r)
|
||||
slog('awg', 'error', r.n > 1 ? sprintf(L_("couldn't start · %d failed attempts in %d min"), r.n, r.mins) : L_("couldn't start"),
|
||||
watchdog.iface_errors(ifname), who);
|
||||
}
|
||||
|
||||
function ifup_ok(ifname) {
|
||||
with_lock('ifup-failed', () => {
|
||||
let all = read_json(FAILS, {});
|
||||
if (all[ifname]) {
|
||||
delete all[ifname];
|
||||
write_json(FAILS, all, 0o600);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -57,54 +160,108 @@ try {
|
||||
else if (cmd == 'sync')
|
||||
out(apply.sync());
|
||||
else if (cmd == 'status') {
|
||||
let m = core.load(), u = core.load_usage(), d = live.dump(), st = view.states(m, u);
|
||||
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
|
||||
out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })));
|
||||
}
|
||||
else if (cmd == 'health')
|
||||
out(ops.health());
|
||||
else if (cmd == 'health') {
|
||||
let checks = health.health();
|
||||
out(checks);
|
||||
if (length(filter(checks, (c) => c.status == 'error')))
|
||||
exit(1);
|
||||
}
|
||||
else if (cmd == 'person' && args[1] == 'ls') {
|
||||
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
|
||||
let people = sort(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })), (a, b) => a.name < b.name ? -1 : 1);
|
||||
if (opts.json)
|
||||
out(people);
|
||||
else
|
||||
table([ 'ID', 'NAME', 'SERVER', 'ACCESS', 'STATE', 'DEVICES', 'LAST SEEN' ], map(people, (p) => [
|
||||
p.id, p.name, p.server, p.access, p.state, `${length(p.devices)}${p.online ? ` (${p.online} online)` : ''}`,
|
||||
p.online ? 'now' : p.last_seen ? ago(time() - p.last_seen) + ' ago' : 'never',
|
||||
]));
|
||||
}
|
||||
else if (cmd == 'person' && args[1] == 'add') {
|
||||
let c = core.open_cursor(), m = core.load(c);
|
||||
let id = core.create_person(c, m, {
|
||||
name: args[2], slug: opt('slug'), access: opt('access', 'internet'),
|
||||
let id = store.transact((c, m) => core.create_person(c, m, {
|
||||
name: args[2], slug: opt('slug'), access: opt('access', 'internet'), server: opt('server'),
|
||||
device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'),
|
||||
});
|
||||
commit(c);
|
||||
}));
|
||||
let m2 = core.load();
|
||||
out(core.portal_url(m2, m2.people[id]) ?? id);
|
||||
live.add_event({ type: 'person_added', person: id, detail: m2.people[id].name, by: 'admin' });
|
||||
out(`Added ${m2.people[id].name} (${id})`);
|
||||
out(core.portal_url(m2, m2.people[id]) ?? 'No personal link: the portal is off.');
|
||||
}
|
||||
else if (cmd == 'person' && args[1] == 'link') {
|
||||
let m = core.load();
|
||||
let p = m.people[args[2]] ?? die('Unknown person.');
|
||||
out(core.portal_url(m, p) ?? 'Set settings.portal_host first.');
|
||||
let p = the_person(m, args[2]);
|
||||
out(core.portal_url(m, p) ?? 'No personal link: the portal is off.');
|
||||
}
|
||||
else if (cmd == 'person' && args[1] == 'rm') {
|
||||
let c = core.open_cursor(), m = core.load(c);
|
||||
core.delete_person(c, m, args[2]);
|
||||
commit(c);
|
||||
apply.sync();
|
||||
let m = core.load();
|
||||
let p = the_person(m, args[2]);
|
||||
let n = length(p.devices);
|
||||
if (n && !opts.yes)
|
||||
die(`${p.name} has ${n} device${n == 1 ? '' : 's'}: add --yes to remove them too.`);
|
||||
store.transact((c, m) => core.delete_person(c, m, p.id));
|
||||
live.add_event({ type: 'person_removed', person: p.id, detail: p.name, pname: p.name, by: 'admin' });
|
||||
let s = apply.sync();
|
||||
out(`Removed ${p.name}${n ? ` and ${n} device${n == 1 ? '' : 's'}` : ''}.`);
|
||||
if (s.warning)
|
||||
warn(`dawnline: ${s.warning}\n`);
|
||||
}
|
||||
else if (cmd == 'device' && args[1] == 'ls') {
|
||||
let m = core.load(), d = live.dump(m);
|
||||
let who = args[2] ? the_person(m, args[2]) : null;
|
||||
let rows = [];
|
||||
for (let id, dev in m.devices) {
|
||||
let p = m.people[dev.person];
|
||||
if (!p || (who && p.id != who.id))
|
||||
continue;
|
||||
let peer = d.peers[dev.public_key];
|
||||
let online = live.online(d, id, peer);
|
||||
push(rows, { id, person: p.id, name: dev.name, kind: dev.kind, address: dev.address, disabled: dev.disabled,
|
||||
online, handshake: +(peer?.handshake ?? 0) });
|
||||
}
|
||||
rows = sort(rows, (a, b) => (a.person < b.person ? -1 : a.person > b.person ? 1 : 0) || (a.name < b.name ? -1 : 1));
|
||||
if (opts.json)
|
||||
out(rows);
|
||||
else
|
||||
table([ 'ID', 'PERSON', 'NAME', 'KIND', 'ADDRESS', 'STATE' ], map(rows, (r) => [
|
||||
r.id, r.person, r.name, r.kind, r.address,
|
||||
r.disabled ? 'off' : r.online ? 'online' : r.handshake ? `seen ${ago(time() - r.handshake)} ago` : 'never connected',
|
||||
]));
|
||||
}
|
||||
else if (cmd == 'device' && args[1] == 'add') {
|
||||
let c = core.open_cursor(), m = core.load(c);
|
||||
let id = core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin' });
|
||||
commit(c);
|
||||
apply.sync();
|
||||
out(id);
|
||||
// Through the same door as LuCI and the portal: event, "issued" marker, capability check.
|
||||
let m = core.load();
|
||||
let p = the_person(m, args[2]);
|
||||
if (!args[3])
|
||||
die('Which name? dawnline device add <person> <name>.');
|
||||
let r = devices.add(p.id, args[3], opt('kind', 'phone'), { by: 'admin' });
|
||||
if (opts.conf)
|
||||
print(r.config.conf);
|
||||
else
|
||||
out(`${r.id} (dawnline device conf ${r.id} prints its configuration)`);
|
||||
if (r.warning)
|
||||
warn(`dawnline: ${r.warning}\n`);
|
||||
}
|
||||
else if (cmd == 'device' && args[1] == 'conf') {
|
||||
let m = core.load();
|
||||
let d = m.devices[args[2]] ?? die('Unknown device.');
|
||||
print(core.client_config(m, d).conf);
|
||||
let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
|
||||
awg.mark_issued(m, d.id);
|
||||
print(awg.client_config(m, d).conf);
|
||||
}
|
||||
else if (cmd == 'device' && args[1] == 'rm') {
|
||||
let c = core.open_cursor(), m = core.load(c);
|
||||
core.delete_device(c, m, args[2]);
|
||||
commit(c);
|
||||
apply.sync();
|
||||
let m = core.load();
|
||||
let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
|
||||
let r = devices.remove(d.id, { by: 'admin' });
|
||||
out(`Removed ${d.name} (${m.people[d.person]?.name ?? d.person}).`);
|
||||
if (r.warning)
|
||||
warn(`dawnline: ${r.warning}\n`);
|
||||
}
|
||||
else if (cmd == 'backup')
|
||||
out(ops.backup_create(opt('reason')));
|
||||
out(backup.backup_create(opt('reason')));
|
||||
else if (cmd == 'portal-cert') {
|
||||
let c = ops.portal_cert(core.load().settings);
|
||||
let c = pc.portal_cert(core.load().settings);
|
||||
out(`${c.cert} ${c.key}`);
|
||||
}
|
||||
else if (cmd == 'portal-http-port') {
|
||||
@@ -112,12 +269,72 @@ try {
|
||||
if (core.portal_http(m))
|
||||
out(`${core.portal_http_port(m)}`);
|
||||
}
|
||||
else if (cmd == 'log') {
|
||||
let n = +opt('n', 0) || 0;
|
||||
let since = since_time(opt('since'));
|
||||
let level = opt('level'), src = opt('src');
|
||||
if (level && index([ 'info', 'up', 'down', 'repair', 'error' ], level) < 0)
|
||||
die('--level takes error, down, repair, up or info.');
|
||||
if (src && index([ 'awg', 'dawnline', 'portal' ], src) < 0)
|
||||
die('--src takes awg, dawnline or portal.');
|
||||
let log = filter(slog_read(n && !since && !level && !src ? n : null),
|
||||
(e) => (!since || e.ts >= since) && (!level || e.level == level) && (!src || e.src == src));
|
||||
if (n && length(log) > n)
|
||||
log = slice(log, 0, n);
|
||||
if (opts.json) {
|
||||
out(log);
|
||||
exit(0);
|
||||
}
|
||||
for (let e in log) {
|
||||
let t = localtime(e.ts);
|
||||
let text = e.by == 'admin'
|
||||
? join(' ', filter([ 'You', e.msg, e.kind, e.who, e.note ? '· ' + e.note : null ], (x) => x))
|
||||
: (e.who ? e.who + ' ' : '') + e.msg;
|
||||
out(sprintf('%02d-%02d %02d:%02d %-8s %-6s %s', t.mon, t.mday, t.hour, t.min, e.src, e.level, text));
|
||||
if (e.detail)
|
||||
out(' ' + replace(e.detail, '\n', '\n '));
|
||||
}
|
||||
}
|
||||
else if (cmd == 'iface-event') {
|
||||
// From the iface hotplug script: a tunnel started, stopped or failed to start.
|
||||
let ifname = args[2] ?? '';
|
||||
if (!match(ifname, /^[a-z][a-z0-9_]{0,15}$/))
|
||||
die('Bad interface.');
|
||||
// Dawnline leaves a note before it takes a tunnel down itself; anything else is unexpected.
|
||||
let it = args[1] == 'ifdown' ? take_iface_intent(ifname) : null;
|
||||
let who = it?.name ?? ifname;
|
||||
for (let id, srv in core.load().servers)
|
||||
if (srv.ifname == ifname)
|
||||
who = srv.name;
|
||||
if (args[1] == 'ifup') {
|
||||
ifup_ok(ifname);
|
||||
let port = sh_out(`awg show ${q(ifname)} listen-port 2>/dev/null`);
|
||||
slog('awg', 'up', port ? sprintf(L_('started · accepting connections on port %s'), port) : L_('started'), null, who);
|
||||
}
|
||||
else if (args[1] == 'ifdown') {
|
||||
// Stops Dawnline made itself are explained by the admin's own line
|
||||
// (changed, turned off, removed); only an AmneziaWG update gets one here.
|
||||
if (it?.reason == 'update')
|
||||
slog('awg', 'info', L_('restarting for the AmneziaWG update'), null, who);
|
||||
else if (!it)
|
||||
slog('awg', 'down', L_('stopped unexpectedly'), join('\n', filter([
|
||||
L_("Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed."),
|
||||
watchdog.iface_errors(ifname),
|
||||
], (x) => x)), who);
|
||||
}
|
||||
else if (args[1] == 'ifup-failed')
|
||||
ifup_failed(ifname, who);
|
||||
}
|
||||
else if (cmd == 'teardown')
|
||||
apply.teardown();
|
||||
else if (cmd == 'version')
|
||||
out(VERSION);
|
||||
else
|
||||
else if (cmd == 'help' || cmd == '--help' || cmd == '-h')
|
||||
help();
|
||||
else {
|
||||
warn(`dawnline: unknown command "${join(' ', slice(args, 0, 2))}" (dawnline help)\n`);
|
||||
exit(2);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
warn(`dawnline: ${e.message}\n`);
|
||||
|
||||
@@ -1,39 +1,83 @@
|
||||
#!/usr/bin/ucode
|
||||
// Dawnline agent (procd instance). Every minute it:
|
||||
// * folds AmneziaWG counters into usage (tmpfs; flushed to flash hourly)
|
||||
// Dawnline agent (procd instance). Every second its watcher reads the tunnels
|
||||
// and, the moment a device connects, its session expires or it roams, logs
|
||||
// it, folds the counters, locates the new address and moves the revision the
|
||||
// admin UI polls (presence.json, see dawnline.live). The same read tells when
|
||||
// a device's link fails in a named way (link.json, dawnline.link), what it does
|
||||
// right now for the portal's set-up sheet (setup.json) and the live meter's
|
||||
// last two minutes, written out while someone looks (meter.json, dawnline.meter).
|
||||
// Every minute it:
|
||||
// * folds the tunnels' counters into usage (tmpfs; flushed to flash hourly)
|
||||
// * saves the activity log to flash as often as Settings says (or never)
|
||||
// * keeps the "like a home device" path and the Home-only resolver up
|
||||
// * logs connects, disconnects and roaming
|
||||
// * enforces end dates, quotas, schedules and pauses (peers + nft sets)
|
||||
// * watches the tunnel interfaces
|
||||
// * watches the tunnel interfaces and repairs what it can (dawnline.watchdog)
|
||||
'use strict';
|
||||
|
||||
import * as uloop from 'uloop';
|
||||
import { readfile, stat, unlink } from 'fs';
|
||||
import { read_json, write_json, ensure_dir, sh_out, q, DATA_DIR, RUN_DIR } from 'dawnline.util';
|
||||
import { open, readfile, writefile, stat, unlink } from 'fs';
|
||||
import {
|
||||
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, date_end, DATA_DIR, RUN_DIR, VERSION
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as ops from 'dawnline.ops';
|
||||
import * as backup from 'dawnline.backup';
|
||||
import * as pc from 'dawnline.portalcert';
|
||||
import * as geo from 'dawnline.geo';
|
||||
import * as watchdog from 'dawnline.watchdog';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
import * as link from 'dawnline.link';
|
||||
import * as meter from 'dawnline.meter';
|
||||
import { L_ } from 'dawnline.i18n';
|
||||
|
||||
const TICK = 60 * 1000;
|
||||
const WATCH = 1000;
|
||||
const FLUSH_EVERY = 3600;
|
||||
const LOG_FLUSH = { '10min': 600, hourly: 3600 };
|
||||
const RESYNC_EVERY = 600;
|
||||
const CONFIG_FILE = '/etc/config/dawnline';
|
||||
|
||||
// One agent, procd's. A second copy would run forever beside it with the code
|
||||
// it started with: its own events (pauses and resumes from stale states), its
|
||||
// own counters and syncs. It takes no arguments: the commands are `dawnline`'s.
|
||||
if (length(ARGV)) {
|
||||
warn(`The agent takes no arguments (procd runs it). For commands use: dawnline ${join(' ', ARGV)}\n`);
|
||||
exit(2);
|
||||
}
|
||||
ensure_dir(RUN_DIR);
|
||||
// Held as long as the process lives; close-on-exec, so children don't keep it.
|
||||
let instance = open(`${RUN_DIR}/agent.lock`, 'we');
|
||||
if (!instance?.lock('xn')) {
|
||||
warn(`The agent is already running (${RUN_DIR}/agent.lock is held). Use /etc/init.d/dawnline restart.\n`);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
let usage = live.load_usage();
|
||||
let last_states = null;
|
||||
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
|
||||
// swallow connects that happened in between.
|
||||
let presence = read_json(`${RUN_DIR}/presence.json`, {});
|
||||
let presence = read_json(live.PRESENCE, {});
|
||||
// What a link showed comes from the watcher's memory, which starts empty: a
|
||||
// state shows again once it held (link.HOLD), a set-up state with the next
|
||||
// read that tells it. The meter's points start again too, written at the next look.
|
||||
write_json(live.LINK, {}, 0o600);
|
||||
write_json(live.SETUP, {}, 0o600);
|
||||
meter.stop();
|
||||
let last_online = presence.online ?? {};
|
||||
let last_endpoint = presence.endpoint ?? {};
|
||||
let offline_ticks = {};
|
||||
let iface_down = {};
|
||||
let rev = +(presence.rev ?? 0);
|
||||
let person_rev = presence.people ?? {};
|
||||
let last_flush = time();
|
||||
let last_log_flush = time();
|
||||
let last_net = null;
|
||||
// The network as apply() last saw it (apply.NET_SIG; this when it never ran),
|
||||
// and a different one seen on the previous tick.
|
||||
let base_net = null;
|
||||
let pending_net = null;
|
||||
let rate_prev = null;
|
||||
|
||||
/**
|
||||
@@ -92,124 +136,498 @@ function record_rate(m) {
|
||||
write_json(`${RUN_DIR}/rate_people.json`, people, 0o644);
|
||||
}
|
||||
let last_sync = 0;
|
||||
// Per server, how the agent's last sync of its devices went (dawnline.awg.sync_peers).
|
||||
let last_peers = {};
|
||||
let conf_mtime = null;
|
||||
let cert_mtime = null;
|
||||
|
||||
const REASON = {
|
||||
paused: 'paused by admin', paused_all: 'everyone paused', expired: 'end date reached',
|
||||
quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', active: 'active',
|
||||
paused: 'paused by admin', expired: 'end date reached',
|
||||
quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', server_off: 'server turned off',
|
||||
active: 'active',
|
||||
};
|
||||
|
||||
function check_people(m, states, events) {
|
||||
let ts = time();
|
||||
for (let id, p in m.people) {
|
||||
let st = states[id], prev = last_states?.[id];
|
||||
if (prev != null && prev != st)
|
||||
// The admin's own pauses (and turning a server off or on) are logged by
|
||||
// rpcd when they happen; here only what changes on its own (end date,
|
||||
// data limit, allowed hours).
|
||||
let by_admin = (x) => x == 'paused' || x == 'server_off';
|
||||
if (prev != null && prev != st && !by_admin(prev) && !by_admin(st))
|
||||
push(events, { type: st == 'active' ? 'resumed' : 'paused', person: id, detail: REASON[st] ?? st });
|
||||
// "Remove their devices" when the end date passes.
|
||||
if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices)) {
|
||||
let c = core.open_cursor();
|
||||
let mm = core.load(c);
|
||||
for (let d in mm.people[id]?.devices ?? [])
|
||||
core.delete_device(c, mm, d);
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
// "Remove their devices" when the end date passes: irreversible, so never
|
||||
// on a clock that has not been set yet (a router before NTP is in 1970).
|
||||
if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices) && localtime(ts).year >= 2025) {
|
||||
store.transact((c, mm) => {
|
||||
for (let d in mm.people[id]?.devices ?? [])
|
||||
core.delete_device(c, mm, d);
|
||||
});
|
||||
push(events, { type: 'devices_removed', person: id, detail: 'end date reached' });
|
||||
last_sync = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let last_home = 0;
|
||||
/** Connections from home: the DHCP name of the address, as it is now. */
|
||||
function named(e) {
|
||||
let h = net.event_hosts(e, net.lan_names());
|
||||
if (h)
|
||||
e.hosts = h;
|
||||
return e;
|
||||
}
|
||||
|
||||
/** Locate new client addresses for the admin map (a couple per minute). */
|
||||
function check_geo(m) {
|
||||
if (!m.settings.geo_enabled)
|
||||
/* ---------- the watcher ---------- */
|
||||
|
||||
// Per device: its latest real handshake, kept when apply re-adds the peer
|
||||
// (its counters and handshake restart from zero, or it is briefly missing),
|
||||
// and the public key it was seen with: new keys (Reconnect, New keys) end
|
||||
// the old session, whatever its handshake said.
|
||||
let last_hs = {}, last_key = {};
|
||||
// The model, read again only when the config file changes (the watcher runs
|
||||
// every second), the tunnels it reads (live.tunnel_ifnames: a regex per
|
||||
// server, compiled each time it runs, so not every second), each device's
|
||||
// online window (live.online_windows: its keep-alive's, from the model) and
|
||||
// the largest keepalive its server's disguise makes (link.keepalive_sizes).
|
||||
let wm = null, wm_sig = null, wm_ifnames = [], wm_windows = {}, wm_ka = {};
|
||||
// netifd deletes and adds a tunnel's link each time it sets it up (a new
|
||||
// ifindex): the devices come back only with the sync its hotplug starts, and
|
||||
// then with no handshake until each one makes a new one. For this long after
|
||||
// the link changed, a device missing from it keeps what was known of it,
|
||||
// rather than a burst of disconnects and connects for everyone online.
|
||||
const RESTART_GRACE = 45;
|
||||
// Per tunnel: the link last seen (null while it is down), and until when its grace lasts.
|
||||
let links = {}, grace = {};
|
||||
|
||||
/** A file's mtime and inode ('-' when it is missing): what the cached model depends on. */
|
||||
function file_sig(path) {
|
||||
let st = stat(path);
|
||||
return st ? `${st.mtime}/${st.inode}` : '-';
|
||||
}
|
||||
|
||||
function watch_model() {
|
||||
// uci commits replace the file: a new inode even within the same second.
|
||||
// Which servers are kept down (core.BLOCKED, written by apply) is in the
|
||||
// model too: their interface names may be someone else's tunnels.
|
||||
let sig = `${file_sig(CONFIG_FILE)} ${file_sig(core.BLOCKED)}`;
|
||||
if (wm == null || sig != wm_sig) {
|
||||
wm = core.load();
|
||||
wm_sig = sig;
|
||||
wm_ifnames = live.tunnel_ifnames(wm);
|
||||
wm_windows = live.online_windows(wm);
|
||||
wm_ka = link.keepalive_sizes(wm);
|
||||
}
|
||||
return wm;
|
||||
}
|
||||
|
||||
// Per device: how its link behaves (dawnline.link: a few recent events and
|
||||
// what is shown), and whether what is shown (link.json) or the set-up states
|
||||
// (setup.json) changed since they were written.
|
||||
let link_hist = {}, link_dirty = false, setup_dirty = false;
|
||||
|
||||
/**
|
||||
* A device's read into its link history: its set-up state follows at once
|
||||
* (link.setup, a few compares unless something happened); it is classified
|
||||
* again when something happened or link.CHECK_EVERY passed (its spans age).
|
||||
* Returns the change in what is shown (link.settle: { from, to }), or null.
|
||||
*/
|
||||
function watch_link(id, dev, peer, now, on) {
|
||||
let h = link_hist[id] ??= link.fresh(now);
|
||||
let moved = false;
|
||||
if (peer)
|
||||
moved = link.observe(h, peer, now, wm_ka[id] ?? link.KEEPALIVE);
|
||||
else
|
||||
link.gone(h);
|
||||
if (link.setup(h, now, on, moved))
|
||||
setup_dirty = true;
|
||||
if (!moved && now - h.checked < link.CHECK_EVERY)
|
||||
return null;
|
||||
h.checked = now;
|
||||
link.prune(h, now);
|
||||
h.raw = link.classify(h, now, on);
|
||||
let change = link.settle(h, h.raw, now, on);
|
||||
if (change)
|
||||
link_dirty = true;
|
||||
return change;
|
||||
}
|
||||
|
||||
// The live meter: the last sample and the last two minutes of points
|
||||
// ([ ts, JSON ], newest last, meter.keep), kept whether anyone looks or not so
|
||||
// that a look gets them at once; whether meter.json is out for a look now.
|
||||
let meter_prev = null, meter_ring = [], meter_out = false;
|
||||
|
||||
/**
|
||||
* A meter point a second from this read, kept; meter.json written while
|
||||
* someone looks (meter.wanted): all the points the first second of a look,
|
||||
* then with each new one. Once nobody does, the file goes; the points stay.
|
||||
*/
|
||||
function watch_meter(m, d, now) {
|
||||
let s = meter.sample(m, d, now);
|
||||
let p = meter_prev ? meter.point(meter_prev, s) : null;
|
||||
meter_prev = s;
|
||||
if (p)
|
||||
meter.keep(meter_ring, p);
|
||||
if (!meter.wanted(now)) {
|
||||
if (meter_out)
|
||||
meter.stop();
|
||||
meter_out = false;
|
||||
return;
|
||||
let cache = geo.load();
|
||||
}
|
||||
if (p || !meter_out)
|
||||
meter.save(meter_ring);
|
||||
meter_out = true;
|
||||
}
|
||||
|
||||
/** Move the revisions (all, and these people's) and save who is online. */
|
||||
function save_presence(people) {
|
||||
rev++;
|
||||
for (let pid in people)
|
||||
person_rev[pid] = rev;
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
|
||||
}
|
||||
|
||||
/* ---------- locations ---------- */
|
||||
|
||||
// A lookup run: this many addresses at most, within this many seconds; a run
|
||||
// still going after GEO_KILL seconds (past every timeout) is given up.
|
||||
const GEO_PER_RUN = 3;
|
||||
const GEO_BUDGET = 12;
|
||||
const GEO_KILL = 60;
|
||||
|
||||
let last_home = 0;
|
||||
// Addresses the watcher saw connect or roam that wait for a run.
|
||||
let geo_pending = {};
|
||||
// The run in a child process (uloop.task) and when it started; null when none.
|
||||
let geo_task = null, geo_since = 0;
|
||||
|
||||
/** Every client address still shown on the map (the cache never pushes these out). */
|
||||
function geo_shown() {
|
||||
let ips = [];
|
||||
for (let id, rec in usage.devices)
|
||||
for (let ip in keys(rec.ips ?? {}))
|
||||
push(ips, ip);
|
||||
let changed = geo.resolve(m.settings, cache, ips, 2);
|
||||
if (time() - last_home > 3600) {
|
||||
last_home = time();
|
||||
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
|
||||
changed = geo.resolve_home(m.settings, cache, wan) || changed;
|
||||
return uniq(ips);
|
||||
}
|
||||
|
||||
/*
|
||||
* A run's results: into the cache (the agent is its only writer), onto the
|
||||
* connections in the activity log that were logged before their place was
|
||||
* known, and to open pages at once: the revision moves for the people seen
|
||||
* from those addresses.
|
||||
*/
|
||||
function geo_done(found) {
|
||||
let cache = geo.load();
|
||||
if (type(found) != 'object' || !geo.merge(cache, found, geo_shown()))
|
||||
return;
|
||||
geo.save(cache);
|
||||
let where = {};
|
||||
for (let ip, r in found)
|
||||
if (r)
|
||||
where[ip] = geo.label(r);
|
||||
if (!length(keys(where)))
|
||||
return;
|
||||
let m = watch_model(), people = {};
|
||||
for (let id, rec in usage.devices)
|
||||
for (let ip in keys(where))
|
||||
if (rec.ips?.[ip] && m.devices[id])
|
||||
people[m.devices[id].person] = true;
|
||||
live.set_places(where, time() - 3600);
|
||||
save_presence(keys(people));
|
||||
}
|
||||
|
||||
/*
|
||||
* Locate client addresses for the admin map in a child process: a lookup
|
||||
* waits on the network for seconds, and neither the 1-second watcher nor the
|
||||
* tick may wait with it. Addresses that just connected go first, at once
|
||||
* (the watcher calls this on a connect); the tick adds anything still shown
|
||||
* that is missing or stale (`more`). One run at a time, a few addresses each;
|
||||
* what just connected and did not fit waits for the next run.
|
||||
*/
|
||||
function geo_lookup(m, more) {
|
||||
if (!m.settings.geo_enabled) {
|
||||
geo_pending = {};
|
||||
return;
|
||||
}
|
||||
if (changed)
|
||||
if (geo_task && !geo_task.finished()) {
|
||||
if (time() - geo_since < GEO_KILL)
|
||||
return;
|
||||
geo_task.kill();
|
||||
}
|
||||
geo_task = null;
|
||||
let todo = geo.stale(geo.load(), [ ...keys(geo_pending), ...(more ?? []) ]);
|
||||
let want = slice(todo, 0, GEO_PER_RUN);
|
||||
let rest = {};
|
||||
for (let ip in slice(todo, GEO_PER_RUN))
|
||||
if (geo_pending[ip])
|
||||
rest[ip] = true;
|
||||
geo_pending = rest;
|
||||
if (!length(want))
|
||||
return;
|
||||
let provider = m.settings.geo_provider;
|
||||
let t = null;
|
||||
t = uloop.task(() => {
|
||||
// The child shares the instance lock: it must not keep it past the agent (a restart would find it taken).
|
||||
instance.close();
|
||||
return geo.lookup_all(provider, want, GEO_PER_RUN, GEO_BUDGET);
|
||||
}, (found) => {
|
||||
if (geo_task == t)
|
||||
geo_task = null;
|
||||
geo_done(found);
|
||||
if (length(keys(geo_pending)))
|
||||
geo_lookup(watch_model());
|
||||
});
|
||||
geo_task = t;
|
||||
geo_since = time();
|
||||
}
|
||||
|
||||
/** The tick: shown addresses missing or stale get a run; the router's own place about hourly. */
|
||||
function check_geo(m) {
|
||||
geo_lookup(m, geo_shown());
|
||||
if (!m.settings.geo_enabled || time() - last_home <= 3600)
|
||||
return;
|
||||
last_home = time();
|
||||
let cache = geo.load();
|
||||
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
|
||||
if (geo.resolve_home(m.settings, cache, wan))
|
||||
geo.save(cache);
|
||||
}
|
||||
|
||||
function place_of(ip) {
|
||||
let pl = geo.place(geo.load(), ip);
|
||||
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
|
||||
return geo.label(geo.place(geo.load(), ip));
|
||||
}
|
||||
|
||||
function check_devices(m, lv, events) {
|
||||
for (let id, d in lv) {
|
||||
let dev = m.devices[id];
|
||||
/*
|
||||
* One look at the tunnels. Connects (a new handshake from a device that was
|
||||
* away), disconnects (its session expired: no handshake within its online
|
||||
* window, live.online_window; a phone asleep looks the same as one switched
|
||||
* off, so silence alone is not enough) and roaming (a new address) are acted
|
||||
* on at once: the log, the counters and the map, then the revision the UI polls.
|
||||
* Only Dawnline's own tunnels are read, each on its own (one process with a
|
||||
* single server): a tunnel that could not be read says nothing about its
|
||||
* devices, which stay as they were.
|
||||
*/
|
||||
function watch() {
|
||||
let m = watch_model();
|
||||
let d = awg.dump(wm_ifnames);
|
||||
let now = time();
|
||||
for (let ifn, r in d.reads) {
|
||||
if (r == 'error')
|
||||
continue;
|
||||
let ix = d.ifaces[ifn]?.ifindex;
|
||||
if (ifn in links && links[ifn] != ix)
|
||||
grace[ifn] = now + RESTART_GRACE;
|
||||
links[ifn] = ix;
|
||||
}
|
||||
for (let ifn in keys(links))
|
||||
if (!(ifn in d.reads)) {
|
||||
delete links[ifn];
|
||||
delete grace[ifn];
|
||||
}
|
||||
let events = [], people = {}, ips = [], failing = [];
|
||||
for (let id, dev in m.devices) {
|
||||
let ifn = m.servers[m.people[dev.person]?.server]?.ifname;
|
||||
if (d.reads[ifn] == 'error')
|
||||
continue;
|
||||
let peer = d.peers[dev.public_key];
|
||||
let ep = '';
|
||||
// New keys: offline until they shake hands, and a new link history. The
|
||||
// old one's set-up session (its no data, or its data flowing) and its
|
||||
// answers would otherwise be taken for the new configuration's.
|
||||
if (last_key[id] != dev.public_key) {
|
||||
if (last_key[id] != null) {
|
||||
last_hs[id] = 0;
|
||||
let h = link_hist[id];
|
||||
if (h?.state != null) {
|
||||
link_dirty = true;
|
||||
people[dev.person] = true;
|
||||
}
|
||||
if (h?.setup != null)
|
||||
setup_dirty = true;
|
||||
delete link_hist[id];
|
||||
}
|
||||
last_key[id] = dev.public_key;
|
||||
}
|
||||
if (peer) {
|
||||
last_hs[id] = max(last_hs[id] ?? 0, peer.handshake);
|
||||
ep = live.endpoint_ip(peer.endpoint);
|
||||
}
|
||||
// Not in the tunnel (turned off, paused, out of time or data): offline now, and online
|
||||
// again only with a new handshake, not the one remembered from before. Unless its
|
||||
// tunnel was just set up again and the sync has not brought it back yet.
|
||||
else if (!(grace[ifn] > now))
|
||||
last_hs[id] = 0;
|
||||
let on = last_hs[id] > 0 && now - last_hs[id] < (wm_windows[id] ?? live.ONLINE_WINDOW);
|
||||
let was = last_online[id];
|
||||
// A device we have never seen before that is online now counts as a connect.
|
||||
if (was == null && d.online && d.present)
|
||||
was = false;
|
||||
// Debounce: a device has to look offline on two ticks in a row before
|
||||
// a disconnect is logged (handshakes are renewed only every 2-3 min).
|
||||
if (was && !d.online) {
|
||||
offline_ticks[id] = (offline_ticks[id] ?? 0) + 1;
|
||||
if (offline_ticks[id] < 2)
|
||||
continue;
|
||||
// What is shown changed: the person's pages read it again (link.json), also
|
||||
// when it cleared without an event (the device stopped trying, or was paused).
|
||||
let change = watch_link(id, dev, peer, now, on);
|
||||
if (change) {
|
||||
people[dev.person] = true;
|
||||
let le = link.event_for(change, dev, on);
|
||||
if (le)
|
||||
push(failing, le);
|
||||
}
|
||||
else
|
||||
delete offline_ticks[id];
|
||||
if (was != null && was != d.online) {
|
||||
if (d.online)
|
||||
push(events, { type: 'connect', person: dev.person, device: id, detail: d.endpoint, where: place_of(d.endpoint) });
|
||||
else
|
||||
push(events, { type: 'disconnect', person: dev.person, device: id });
|
||||
// One configuration on two devices: its address goes back and forth all
|
||||
// the time, which is no roaming (nor a reason to move the revision).
|
||||
let flapping = link_hist[id].raw == 'shared' || link_hist[id].state == 'shared';
|
||||
if (on && !was) {
|
||||
push(events, { type: 'connect', person: dev.person, device: id, detail: ep });
|
||||
push(ips, ep);
|
||||
}
|
||||
else if (d.online && last_endpoint[id] && d.endpoint && last_endpoint[id] != d.endpoint)
|
||||
push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${d.endpoint}` });
|
||||
last_online[id] = d.online;
|
||||
if (d.endpoint)
|
||||
last_endpoint[id] = d.endpoint;
|
||||
else if (!on && was)
|
||||
push(events, { type: 'disconnect', person: dev.person, device: id });
|
||||
else if (on && ep && last_endpoint[id] && ep != last_endpoint[id] && !flapping) {
|
||||
push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${ep}` });
|
||||
push(ips, ep);
|
||||
}
|
||||
if (on != !!was || (ep && ep != last_endpoint[id] && !flapping))
|
||||
people[dev.person] = true;
|
||||
last_online[id] = on;
|
||||
if (ep)
|
||||
last_endpoint[id] = ep;
|
||||
}
|
||||
for (let id in keys(last_online))
|
||||
if (!m.devices[id]) {
|
||||
delete last_online[id];
|
||||
delete last_endpoint[id];
|
||||
delete last_hs[id];
|
||||
delete last_key[id];
|
||||
}
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/presence.json`, { online: last_online, endpoint: last_endpoint }, 0o600);
|
||||
for (let id in keys(link_hist))
|
||||
if (!m.devices[id]) {
|
||||
if (link_hist[id].state != null)
|
||||
link_dirty = true;
|
||||
if (link_hist[id].setup != null)
|
||||
setup_dirty = true;
|
||||
delete link_hist[id];
|
||||
}
|
||||
if (link_dirty) {
|
||||
write_json(live.LINK, link.shown(link_hist), 0o600);
|
||||
link_dirty = false;
|
||||
}
|
||||
// The portal's set-up sheet polls for it: no revision moves with it.
|
||||
if (setup_dirty) {
|
||||
write_json(live.SETUP, link.setups(link_hist), 0o600);
|
||||
setup_dirty = false;
|
||||
}
|
||||
// Merged per device for an hour: a link that keeps failing and coming back is one line.
|
||||
for (let e in failing)
|
||||
live.add_event_merged(e, 3600);
|
||||
watch_meter(m, d, now);
|
||||
if (!length(keys(people)))
|
||||
return;
|
||||
save_presence(keys(people));
|
||||
if (!length(events))
|
||||
return;
|
||||
live.collect(m, usage, d);
|
||||
live.save_usage(usage, false);
|
||||
// The event carries the place when the cache already knows it. A new
|
||||
// address is looked up at once, in a child process (geo_lookup): its place
|
||||
// goes onto this event and the revision moves again when it is known.
|
||||
for (let e in events)
|
||||
if (e.type == 'connect')
|
||||
e.where = place_of(e.detail);
|
||||
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
|
||||
save_presence(keys(people));
|
||||
if (m.settings.geo_enabled && length(ips)) {
|
||||
for (let ip in ips)
|
||||
geo_pending[ip] = true;
|
||||
geo_lookup(m);
|
||||
}
|
||||
}
|
||||
|
||||
function check_servers(m, dmp, events) {
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.enabled || !srv.private_key)
|
||||
// What the service log was already told. On flash: the public address often
|
||||
// changes with a reboot (PPPoE), and that is when it matters. Written rarely.
|
||||
const NOTES = `${DATA_DIR}/notes.json`;
|
||||
let notes = read_json(NOTES, {});
|
||||
let last_cert_check = 0;
|
||||
|
||||
function note(k, v) {
|
||||
notes[k] = v;
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(NOTES, notes, 0o600);
|
||||
}
|
||||
|
||||
/*
|
||||
* End dates in the activity log: a heads-up once per end date when its
|
||||
* warning window opens, and "keep access" passing it (which changes no
|
||||
* state, so nothing else would say it). Not on a clock that is not set.
|
||||
*/
|
||||
function check_expiry(m, events) {
|
||||
let ts = time();
|
||||
if (localtime(ts).year < 2025)
|
||||
return;
|
||||
for (let id, p in m.people) {
|
||||
if (!p.expires)
|
||||
continue;
|
||||
let up = dmp.ifaces[srv.ifname] != null;
|
||||
if (!up) {
|
||||
iface_down[id] = (iface_down[id] ?? 0) + 1;
|
||||
if (iface_down[id] == 2) {
|
||||
push(events, { type: 'server_down', server: id, detail: srv.ifname });
|
||||
}
|
||||
let end = date_end(p.expires);
|
||||
if (end == null)
|
||||
continue;
|
||||
let left = end > ts ? int((end - ts) / 86400) + 1 : 0;
|
||||
if (left > 0 && p.expire_warn > 0 && left <= p.expire_warn && notes[`warned:${id}`] != p.expires) {
|
||||
note(`warned:${id}`, p.expires);
|
||||
push(events, { type: 'expiring', person: id, detail: `${left} day${left == 1 ? '' : 's'}` });
|
||||
}
|
||||
else {
|
||||
if ((iface_down[id] ?? 0) >= 2) {
|
||||
push(events, { type: 'server_up', server: id, detail: srv.ifname });
|
||||
}
|
||||
iface_down[id] = 0;
|
||||
if (left == 0 && p.expire_action == 'notify' && notes[`kept:${id}`] != p.expires) {
|
||||
note(`kept:${id}`, p.expires);
|
||||
push(events, { type: 'expired_kept', person: id, detail: p.expires });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** "Jan 1 2027" from the certificate, or null. */
|
||||
function cert_end(path) {
|
||||
let m = match(sh_out(`openssl x509 -enddate -noout -in ${q(path)} 2>/dev/null`) ?? '', /notAfter=([A-Za-z]+) +([0-9]+) [0-9:]+ ([0-9]+)/);
|
||||
return m ? `${m[1]} ${m[2]} ${m[3]}` : null;
|
||||
}
|
||||
|
||||
function check_cert(m) {
|
||||
if (!m.settings.portal_enabled)
|
||||
return;
|
||||
let c = ops.portal_cert(m.settings);
|
||||
let c = pc.portal_cert(m.settings);
|
||||
let mt = stat(c.cert)?.mtime;
|
||||
if (cert_mtime != null && mt != null && mt != cert_mtime)
|
||||
if (cert_mtime != null && mt != null && mt != cert_mtime) {
|
||||
slog('portal', 'up', sprintf(L_('certificate renewed · valid until %s'), cert_end(c.cert) ?? '?'), null, L_('Personal portal'));
|
||||
system('/etc/init.d/dawnline reload >/dev/null 2>&1 &');
|
||||
}
|
||||
cert_mtime = mt;
|
||||
// Running out soon (ACME did not renew it): once per certificate, checked hourly.
|
||||
if (mt == null || c.self_signed || time() - last_cert_check < 3600)
|
||||
return;
|
||||
last_cert_check = time();
|
||||
if (notes.cert_warned != mt && system(`openssl x509 -checkend 604800 -noout -in ${q(c.cert)} >/dev/null 2>&1`) != 0) {
|
||||
let end = cert_end(c.cert);
|
||||
slog('portal', 'error', end ? sprintf(L_('certificate expires %s'), end) : L_('certificate expires within 7 days'),
|
||||
L_('Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.'), L_('Personal portal'));
|
||||
note('cert_warned', mt);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The router's public IPv4 changed. Devices whose configuration holds the
|
||||
* address itself (a server's public address is an IP) cannot connect until
|
||||
* they get a new one; with a hostname only the DNS record must follow.
|
||||
*/
|
||||
function check_wan(m) {
|
||||
let srv = filter(values(m.servers), (x) => x.enabled && x.private_key)[0];
|
||||
let ip = srv ? net.wan_address(srv) : null;
|
||||
if (!ip || ip == notes.wan)
|
||||
return;
|
||||
let was = notes.wan;
|
||||
note('wan', ip);
|
||||
if (!was)
|
||||
return;
|
||||
let stuck = map(filter(values(m.servers), (x) => core.endpoint_host(m, x) == was), (x) => x.name);
|
||||
if (length(stuck))
|
||||
slog('dawnline', 'error', sprintf(L_('public address changed · %s → %s'), was, ip),
|
||||
sprintf(length(stuck) == 1
|
||||
? L_('%s still gives devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.')
|
||||
: L_('%s still give devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.'),
|
||||
join(', ', stuck)), L_('Router'));
|
||||
else
|
||||
slog('dawnline', 'info', sprintf(L_('public address changed · %s → %s'), was, ip), null, L_('Router'));
|
||||
}
|
||||
|
||||
let last_backup_day = null;
|
||||
@@ -223,13 +641,25 @@ function nightly_backup() {
|
||||
let st = read_json(`${DATA_DIR}/backup-state.json`, {});
|
||||
if (sum && sum != st.auto) {
|
||||
try {
|
||||
ops.backup_create('auto');
|
||||
backup.backup_create('auto');
|
||||
write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600);
|
||||
}
|
||||
catch (e) {}
|
||||
catch (e) {
|
||||
// Tried again tomorrow; meanwhile the admin should know (a full flash, mostly).
|
||||
slog('dawnline', 'error', sprintf(L_('nightly backup failed: %s'), e.message), null, L_('Backup'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings → Updates: an automatic check or update when one is due. The
|
||||
* updater does the work in its own process; this only decides when.
|
||||
*/
|
||||
function check_updates(m) {
|
||||
if (upd.due(m.settings.updates, upd.auto_state()) && !upd.busy())
|
||||
system('start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- auto');
|
||||
}
|
||||
|
||||
/**
|
||||
* Traffic history resets requested from LuCI (rpcd cannot touch the
|
||||
* counters this process holds in memory). Applied, then saved to flash.
|
||||
@@ -246,72 +676,210 @@ function check_usage_reset(m) {
|
||||
return true;
|
||||
}
|
||||
|
||||
function tick() {
|
||||
// A restore or import drops the live counters; start over from flash.
|
||||
if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
|
||||
usage = live.load_usage();
|
||||
let m = core.load();
|
||||
let reset = check_usage_reset(m);
|
||||
let pol = live.policy(m.settings.retention);
|
||||
let dmp = live.dump();
|
||||
let lv = live.collect(m, usage, dmp);
|
||||
try {
|
||||
record_rate(m);
|
||||
}
|
||||
catch (e) {}
|
||||
let states = apply.states_for(m, usage);
|
||||
let events = [];
|
||||
|
||||
check_devices(m, lv, events);
|
||||
check_people(m, states, events);
|
||||
check_servers(m, dmp, events);
|
||||
|
||||
let changed = last_states == null || sprintf('%J', states) != sprintf('%J', last_states);
|
||||
if (changed || time() - last_sync > RESYNC_EVERY) {
|
||||
apply.sync(m, usage);
|
||||
/*
|
||||
* Push devices and access rules when people's states changed, the config
|
||||
* file was written (by anyone: rpcd, the portal, the CLI, a restore), the
|
||||
* access table is gone (a flushed ruleset: the firewall alone would let every
|
||||
* device reach everything, so the sync unloads them until it is back), a
|
||||
* running tunnel holds other devices than it should (check_peers), or every
|
||||
* RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
|
||||
*/
|
||||
function sync_runtime(t) {
|
||||
// uci commits replace the file: a new inode even within the same second.
|
||||
let st = stat(CONFIG_FILE);
|
||||
let mt = st ? `${st.mtime}/${st.inode}` : null;
|
||||
let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) ||
|
||||
(conf_mtime != null && mt != conf_mtime);
|
||||
if (changed || time() - last_sync > RESYNC_EVERY || (length(t.m.servers) && !apply.table_present())) {
|
||||
last_peers = apply.sync(t.m, usage).peers ?? {};
|
||||
last_sync = time();
|
||||
}
|
||||
last_states = states;
|
||||
conf_mtime = mt;
|
||||
last_states = t.states;
|
||||
}
|
||||
|
||||
live.add_events(events, pol);
|
||||
|
||||
let persist = reset || time() - last_flush >= FLUSH_EVERY;
|
||||
live.save_usage(usage, persist);
|
||||
if (persist)
|
||||
last_flush = time();
|
||||
if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) {
|
||||
live.persist_events(pol);
|
||||
last_log_flush = time();
|
||||
/*
|
||||
* A running tunnel without all of its devices, or with ones it should not
|
||||
* have (set up again before its hotplug sync ran, an `awg set` by hand): the
|
||||
* sync runs on this tick, not up to RESYNC_EVERY later. By the same choice
|
||||
* of devices the sync makes (and Health compares); only where the agent's
|
||||
* last sync took: a server that refuses its devices has said so in the
|
||||
* service log and keeps the slower pace.
|
||||
*/
|
||||
function check_peers(t) {
|
||||
for (let id, srv in t.m.servers) {
|
||||
let last = last_peers[id] ?? 'ok';
|
||||
if (t.dmp?.reads?.[srv.ifname] != 'read' || (last != 'ok' && last != 'down'))
|
||||
continue;
|
||||
let diff = awg.peer_diff(awg.tunnel_devices(t.m, id, t.states), t.dmp, srv.ifname);
|
||||
if (diff.missing || diff.extra)
|
||||
last_sync = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* The router's network changed under us: re-derive everything. Only a change
|
||||
* seen on two ticks in a row (a bridge recreated or an interface restarting
|
||||
* passes), compared with what the last apply() used.
|
||||
*/
|
||||
function check_network(t) {
|
||||
let sig = apply.net_signature(t.m);
|
||||
let applied = readfile(apply.NET_SIG) ?? base_net;
|
||||
if (applied == null || sig == applied) {
|
||||
base_net ??= sig;
|
||||
pending_net = null;
|
||||
return;
|
||||
}
|
||||
if (pending_net != sig) {
|
||||
pending_net = sig;
|
||||
return;
|
||||
}
|
||||
pending_net = null;
|
||||
slog('dawnline', 'info', L_('network changed - Dawnline set itself up again'), null, L_('Router'));
|
||||
apply.apply();
|
||||
base_net = readfile(apply.NET_SIG) ?? apply.net_signature(core.load());
|
||||
}
|
||||
|
||||
/*
|
||||
* One tick is a list of steps, each on its own: a failing step is logged
|
||||
* (each new message once in the service log, every time in syslog) and the
|
||||
* others still run. Steps that need the model wait for it; the counters and
|
||||
* the logs are saved at the end whatever happened.
|
||||
*/
|
||||
const STEPS = [
|
||||
{ who: 'Dawnline', run: (t) => {
|
||||
t.m = core.load();
|
||||
t.pol = live.policy(t.m.settings.retention);
|
||||
} },
|
||||
{ who: L_('Traffic'), run: (t) => {
|
||||
t.reset = check_usage_reset(t.m);
|
||||
t.dmp = live.dump(t.m);
|
||||
live.collect(t.m, usage, t.dmp);
|
||||
} },
|
||||
{ who: L_('Speed'), quiet: true, run: (t) => record_rate(t.m) },
|
||||
{ who: L_('People'), run: (t) => {
|
||||
t.states = apply.states_for(t.m, usage);
|
||||
check_people(t.m, t.states, t.events);
|
||||
check_expiry(t.m, t.events);
|
||||
} },
|
||||
{ who: L_('Access rules'), run: (t) => {
|
||||
if (!t.states)
|
||||
return;
|
||||
check_peers(t);
|
||||
sync_runtime(t);
|
||||
} },
|
||||
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
|
||||
{ who: L_('Activity'), run: (t) => {
|
||||
live.add_events(t.events, t.pol);
|
||||
// Pauses and resumes on their own: the UI shows them without waiting for its next poll.
|
||||
if (length(t.events))
|
||||
save_presence(uniq(map(filter(t.events, (e) => e.person), (e) => e.person)));
|
||||
} },
|
||||
{ who: L_('Internet like a home device'), run: (t) => apply.sync_loop(t.m, usage) },
|
||||
{ who: L_('Router'), run: check_network },
|
||||
{ who: L_('Watchdog'), run: (t) => watchdog.run(core.load()) },
|
||||
{ who: L_('Personal portal'), run: (t) => check_cert(t.m) },
|
||||
{ who: L_('Router'), quiet: true, run: (t) => check_wan(t.m) },
|
||||
{ who: L_('Backup'), run: (t) => nightly_backup() },
|
||||
{ who: 'updates', quiet: true, run: (t) => check_updates(t.m) },
|
||||
{ who: 'geo', quiet: true, run: (t) => check_geo(t.m) },
|
||||
];
|
||||
|
||||
// Step → the last error it logged (cleared when it works again).
|
||||
let step_err = {};
|
||||
|
||||
function step(i, s, fn) {
|
||||
try {
|
||||
apply.sync_loop(m, usage);
|
||||
// The router's network changed under us: re-derive everything.
|
||||
let sig = apply.net_signature(m);
|
||||
if (last_net != null && sig != last_net) {
|
||||
system(`logger -t dawnline-agent 'network changed, re-applying'`);
|
||||
apply.apply();
|
||||
sig = apply.net_signature(core.load());
|
||||
fn();
|
||||
delete step_err[i];
|
||||
}
|
||||
catch (e) {
|
||||
system(`logger -t dawnline-agent ${q(`${s.who}: ${e.message}`)}`);
|
||||
if (!s.quiet && step_err[i] != e.message)
|
||||
slog('dawnline', 'error', sprintf(L_('failed: %s'), e.message), e.stacktrace?.[0]?.context, s.who);
|
||||
step_err[i] = e.message;
|
||||
}
|
||||
}
|
||||
|
||||
function tick() {
|
||||
ensure_dir(RUN_DIR);
|
||||
writefile(watchdog.BEAT, `${time()}`);
|
||||
// A restore or import put other counters on flash (dawnline.backup leaves
|
||||
// a marker): start over from them, whatever the watcher wrote since.
|
||||
if (stat(live.USAGE_RELOAD)) {
|
||||
unlink(live.USAGE_RELOAD);
|
||||
usage = live.load_usage(true);
|
||||
}
|
||||
else if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
|
||||
usage = live.load_usage();
|
||||
let t = { m: null, pol: null, reset: false, events: [], dmp: null };
|
||||
for (let i, s in STEPS)
|
||||
if (i == 0 || t.m)
|
||||
step(i, s, () => s.run(t));
|
||||
|
||||
let persist = t.reset || time() - last_flush >= FLUSH_EVERY;
|
||||
step('save', { who: L_('Traffic') }, () => {
|
||||
live.save_usage(usage, persist);
|
||||
if (persist) {
|
||||
last_flush = time();
|
||||
geo.flush();
|
||||
}
|
||||
last_net = sig;
|
||||
}
|
||||
catch (e) {
|
||||
system(`logger -t dawnline-agent ${q('like-home: ' + e.message)}`);
|
||||
}
|
||||
check_cert(m);
|
||||
nightly_backup();
|
||||
try {
|
||||
check_geo(m);
|
||||
}
|
||||
catch (e) {
|
||||
system(`logger -t dawnline-agent ${q('geo: ' + e.message)}`);
|
||||
}
|
||||
});
|
||||
step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist));
|
||||
step('events', { who: L_('Activity') }, () => {
|
||||
let pol = t.pol ?? live.policy();
|
||||
if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) {
|
||||
live.persist_events(pol);
|
||||
last_log_flush = time();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function shutdown() {
|
||||
live.save_usage(usage, true);
|
||||
live.persist_events();
|
||||
geo.flush();
|
||||
slog_trim(true);
|
||||
// The live meter's file goes with it: a stopped agent's points are no speed now.
|
||||
meter.stop();
|
||||
// A clean stop: the next start is not a crash.
|
||||
unlink(watchdog.BEAT);
|
||||
}
|
||||
|
||||
// Why this start: the heartbeat file outlives an agent that died (crash, out
|
||||
// of memory, kill -9); the init script notes a stop; the version on flash
|
||||
// changes with an update; a fresh uptime means the router just booted.
|
||||
let crashed = stat(watchdog.BEAT) != null;
|
||||
let stopped = +(readfile(`${RUN_DIR}/agent.stopped`) ?? 0);
|
||||
unlink(`${RUN_DIR}/agent.stopped`);
|
||||
let was = trim(readfile(`${DATA_DIR}/version`) ?? '');
|
||||
if (was != VERSION) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
writefile(`${DATA_DIR}/version`, VERSION);
|
||||
}
|
||||
slog_restore();
|
||||
// postupdate put this (kept) version back because the new one did not come up.
|
||||
let rolled = trim(readfile(`${RUN_DIR}/update-rolled-back`) ?? '');
|
||||
unlink(`${RUN_DIR}/update-rolled-back`);
|
||||
if (rolled)
|
||||
slog('dawnline', 'error', sprintf(L_('update to %s failed its check - rolled back to %s'), rolled, VERSION),
|
||||
L_('The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.'), 'Dawnline');
|
||||
else if (was && was != VERSION)
|
||||
slog('dawnline', 'up', sprintf(L_('updated · %s → %s'), was, VERSION), null, 'Dawnline');
|
||||
else if (crashed)
|
||||
slog('dawnline', 'repair', L_('stopped unexpectedly - started again'),
|
||||
// Why, when syslog knows: procd, the kernel (out of memory, segfault), ucode errors.
|
||||
sh_out('logread -l 400 2>/dev/null | grep -iE "kernel:.*(out of memory|killed process|oom-kill|segfault)|procd:.*dawnline|dawnline/agent" | tail -n 6'), 'Dawnline');
|
||||
else if (stopped && time() - stopped < 300)
|
||||
slog('dawnline', 'info', sprintf(L_('restarted · version %s'), VERSION), null, 'Dawnline');
|
||||
else if (live.uptime() < 600)
|
||||
slog('dawnline', 'info', sprintf(L_('started with the router · version %s'), VERSION), null, 'Dawnline');
|
||||
else
|
||||
slog('dawnline', 'info', sprintf(L_('started · version %s'), VERSION), null, 'Dawnline');
|
||||
// A module Dawnline did not install has no record of its kernel: without one
|
||||
// Health cannot tell a firmware upgrade from a missing module.
|
||||
builds.adopt();
|
||||
|
||||
uloop.init();
|
||||
|
||||
let timer;
|
||||
@@ -320,11 +888,17 @@ timer = uloop.timer(1000, function() {
|
||||
tick();
|
||||
}
|
||||
catch (e) {
|
||||
system(`logger -t dawnline-agent ${q('tick failed: ' + e.message)}`);
|
||||
slog('dawnline', 'error', sprintf(L_('background check failed: %s'), e.message), e.stacktrace?.[0]?.context, 'Dawnline');
|
||||
}
|
||||
timer.set(TICK);
|
||||
});
|
||||
|
||||
let watcher;
|
||||
watcher = uloop.timer(WATCH, function() {
|
||||
step('watch', { who: L_('Connections') }, watch);
|
||||
watcher.set(WATCH);
|
||||
});
|
||||
|
||||
if (type(uloop.signal) == 'function') {
|
||||
uloop.signal('TERM', () => { shutdown(); uloop.end(); });
|
||||
uloop.signal('INT', () => { shutdown(); uloop.end(); });
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/bin/sh
|
||||
# Cron, every 5 minutes: the watchdog lives in the agent, so this looks after
|
||||
# the agent itself: ends any copy that isn't procd's, and kills procd's when it
|
||||
# runs but has stopped ticking (procd starts it again; that part is off with
|
||||
# the watchdog, Health → Watchdog).
|
||||
pid="$(ubus call service list '{"name":"dawnline"}' 2>/dev/null | jsonfilter -q -e '@.dawnline.instances.agent.pid')"
|
||||
|
||||
# Only procd's agent: any other copy (started by hand, or left by an older version that let
|
||||
# it start) runs stale code beside it, with its own events and syncs. Always ended.
|
||||
for p in $(pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent'); do
|
||||
[ "$p" = "$pid" ] || kill -9 "$p" 2>/dev/null
|
||||
done
|
||||
|
||||
[ "$(uci -q get dawnline.settings.watchdog)" = 0 ] && exit 0
|
||||
[ -n "$pid" ] && [ -r "/proc/$pid/stat" ] || exit 0
|
||||
|
||||
now="$(date +%s)"
|
||||
last="$(cat /var/run/dawnline/agent.beat 2>/dev/null)"
|
||||
# Seconds the agent has been running: uptime minus its start time (field 22, in 1/100 s).
|
||||
age="$(awk -v up="$(cut -d. -f1 /proc/uptime)" '{ print up - int($22 / 100) }' "/proc/$pid/stat")"
|
||||
[ "${age:-0}" -gt 300 ] || exit 0
|
||||
[ $((now - ${last:-0})) -gt 300 ] || exit 0
|
||||
|
||||
kill -9 "$pid"
|
||||
# Logged here; the restarted agent should not report a crash as well.
|
||||
rm -f /var/run/dawnline/agent.beat
|
||||
if [ -n "$last" ]; then detail="No check for $((now - last)) s."
|
||||
else detail="It never completed a check."; fi
|
||||
msg="stopped responding — restarted"
|
||||
mkdir -p /var/run/dawnline
|
||||
printf '{"ts":%s,"src":"dawnline","level":"repair","who":"Dawnline","msg":"%s","detail":"%s"}\n' "$now" "$msg" "$detail" >> /var/run/dawnline/service.log
|
||||
logger -t dawnline "Dawnline $msg"
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/bin/sh
|
||||
# Dawnline — after its own package was replaced: restart, check that the new
|
||||
# version answers (the LuCI link and the agent), and put the kept previous
|
||||
# version back when it does not. Started detached by the updater
|
||||
# (usr/libexec/dawnline/updater) with the version being installed.
|
||||
# postupdate <version>
|
||||
# Plain shell on purpose: a release whose ucode does not compile cannot check
|
||||
# or repair itself, and the admin cannot click Roll back in a page that this
|
||||
# same backend serves.
|
||||
RUN=/var/run/dawnline
|
||||
KEEP=/etc/dawnline/keep/app
|
||||
to="${1:-?}"
|
||||
|
||||
sleep 2
|
||||
# LuCI reads a language's catalogs once per web server: a replaced translation
|
||||
# needs a fresh one, before the new version answers and the page reloads.
|
||||
ls /usr/lib/lua/luci/i18n/dawnline.*.lmo >/dev/null 2>&1 && /etc/init.d/uhttpd restart >/dev/null 2>&1
|
||||
/etc/init.d/rpcd reload >/dev/null 2>&1
|
||||
/etc/init.d/dawnline restart >/dev/null 2>&1
|
||||
|
||||
up() {
|
||||
ubus list luci.dawnline >/dev/null 2>&1 || return 1
|
||||
ubus -t 10 call luci.dawnline rev >/dev/null 2>&1 || return 1
|
||||
pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent' >/dev/null 2>&1
|
||||
}
|
||||
|
||||
i=0
|
||||
while [ "$i" -lt 12 ]; do
|
||||
sleep 5
|
||||
i=$((i + 1))
|
||||
up && exit 0
|
||||
done
|
||||
|
||||
logger -t dawnline "update to $to failed its check: luci.dawnline or the agent is not up"
|
||||
set --
|
||||
for f in "$KEEP"/*.ipk "$KEEP"/*.apk; do
|
||||
[ -f "$f" ] && set -- "$@" "$f"
|
||||
done
|
||||
if [ "$#" -eq 0 ]; then
|
||||
logger -t dawnline "no previous version is kept: nothing to roll back to"
|
||||
exit 1
|
||||
fi
|
||||
if command -v apk >/dev/null 2>&1; then
|
||||
apk add --allow-untrusted "$@" >/dev/null 2>&1
|
||||
else
|
||||
opkg install --force-reinstall --force-downgrade "$@" >/dev/null 2>&1
|
||||
fi
|
||||
/etc/init.d/rpcd restart >/dev/null 2>&1
|
||||
/etc/init.d/dawnline restart >/dev/null 2>&1
|
||||
mkdir -p "$RUN"
|
||||
# The restored agent reports it in the service log on its start.
|
||||
echo "$to" > "$RUN/update-rolled-back"
|
||||
logger -t dawnline "rolled back from $to to the kept version"
|
||||
exit 0
|
||||
@@ -1,64 +1,77 @@
|
||||
#!/usr/bin/ucode
|
||||
// Dawnline background update worker, started detached by luci.dawnline.
|
||||
// Dawnline background update worker, started detached by luci.dawnline and
|
||||
// by the agent (automatic runs).
|
||||
//
|
||||
// updater check
|
||||
// updater install app|amneziawg[:slava|grey[:ru]]|pkgs:<name,…>|all
|
||||
// updater check [app|amneziawg|packages]
|
||||
// updater install app | app@<tag> | app:reinstall | app:rollback
|
||||
// updater install amneziawg[:auto|slava|grey[:ru]] | amneziawg:rollback
|
||||
// updater install pkgs:<name,…>
|
||||
// updater auto (Settings → Updates: check, then install)
|
||||
//
|
||||
// Progress: /var/run/dawnline/update-job.json; check results:
|
||||
// /var/run/dawnline/update-check.json. The Updates tab polls both.
|
||||
// One job at a time: the job holds the update lock (dawnline.updates) until
|
||||
// it exits. Progress: /var/run/dawnline/update-job.json; check results:
|
||||
// /var/run/dawnline/update-check.json. The Components tab polls both. The
|
||||
// components themselves are dawnline.upd_app, upd_awg and upd_pkgs.
|
||||
'use strict';
|
||||
|
||||
import * as fs from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { connect } from 'ubus';
|
||||
import { VERSION, REPO } from 'dawnline.util';
|
||||
import { slog, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as app from 'dawnline.upd_app';
|
||||
import * as awg from 'dawnline.upd_awg';
|
||||
import * as pkgs from 'dawnline.upd_pkgs';
|
||||
import * as i18n from 'dawnline.i18n';
|
||||
import { _, L_ } from 'dawnline.i18n';
|
||||
|
||||
const STATE_DIR = '/var/run/dawnline';
|
||||
const JOB_FILE = `${STATE_DIR}/update-job.json`;
|
||||
const CHECK_FILE = `${STATE_DIR}/update-check.json`;
|
||||
const WORK_DIR = '/tmp/dawnline-update';
|
||||
// Builds per OpenWrt release (tag = firmware version); the kernel module must match the firmware.
|
||||
// Which AmneziaWG a build carries (2.0 or 3.1) is read from the package, per firmware.
|
||||
const AWG_SOURCES = {
|
||||
slava: { repo: 'Slava-Shchipunov/awg-openwrt', label: 'Slava-Shchipunov' },
|
||||
grey: { repo: '2Grey/awg-openwrt', label: '2Grey' },
|
||||
};
|
||||
const AWG_PKGS = [ 'kmod-amneziawg', 'amneziawg-tools', 'luci-proto-amneziawg' ];
|
||||
const AWG_RU = 'luci-i18n-amneziawg-ru';
|
||||
// OpenWrt packages Dawnline runs on (the Updates tab groups and names them).
|
||||
// What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the
|
||||
// stock system): the home-like link, and HTTPS plus certificates for the personal portal.
|
||||
const SYS_PKGS = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ];
|
||||
// Packages released together with each of the above, updated as a set so OpenSSL never ends up
|
||||
// half old and half new.
|
||||
const PKG_FAMILY = [
|
||||
[ /^ip-full$/, /^ip-/ ],
|
||||
[ /^(libustream-openssl|openssl-util)$/, /^(libustream-openssl|libopenssl|openssl-util$)/ ],
|
||||
[ /^(acme|luci-app-acme$)/, /^acme/ ],
|
||||
];
|
||||
const USAGE = `Usage:
|
||||
updater check [app|amneziawg|packages]
|
||||
updater install app | app@<tag> | app:reinstall | app:rollback
|
||||
updater install amneziawg[:auto|slava|grey[:ru]] | amneziawg:rollback
|
||||
updater install pkgs:<name,…>
|
||||
updater auto
|
||||
`;
|
||||
|
||||
function family(p) {
|
||||
for (let f in PKG_FAMILY)
|
||||
if (match(p, f[0]))
|
||||
return f[1];
|
||||
return null;
|
||||
// No command, one it doesn't know, or an install of nothing: the usage and exit, before anything is read or
|
||||
// written (no job for Components, no history, nothing in the service log). Asked for help: the same, on stdout.
|
||||
if (index([ '-h', '--help', 'help' ], ARGV[0]) >= 0) {
|
||||
print(USAGE);
|
||||
exit(0);
|
||||
}
|
||||
if (index([ 'check', 'install', 'auto' ], ARGV[0]) < 0 || (ARGV[0] == 'install' && !length(ARGV[1] ?? ''))) {
|
||||
warn(USAGE);
|
||||
exit(2);
|
||||
}
|
||||
|
||||
// The phases and errors of a job LuCI started are in the admin's language (rpc/updates.uc hands it over).
|
||||
i18n.use(getenv('DAWNLINE_LANG'));
|
||||
|
||||
const PID = +split(fs.readfile('/proc/self/stat') ?? '0', ' ')[0];
|
||||
const POL = core.load().settings.updates;
|
||||
const CHECKS = { app: app.check, amneziawg: awg.check, packages: pkgs.check };
|
||||
const INSTALLS = { app: app.install, amneziawg: awg.install, pkgs: pkgs.install };
|
||||
// Names in the service log (English there, like the rest of it); the phases are checking() and updating().
|
||||
const WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: L_('System packages'), packages: L_('System packages') };
|
||||
|
||||
let job = {
|
||||
action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null,
|
||||
phase: '', log: [], error: null, result: null,
|
||||
id: `${time()}-${PID}`, action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null,
|
||||
pid: PID, auto: false, phase: '', from: null, to: null, log: [], error: null, result: null,
|
||||
};
|
||||
// An automatic run only shows up as a job once it installs something.
|
||||
let quiet = ARGV[0] == 'auto';
|
||||
// What to restart once the job is over (never in the middle of it).
|
||||
let after = {};
|
||||
|
||||
function save() {
|
||||
fs.writefile(`${JOB_FILE}.tmp`, sprintf('%J', job));
|
||||
fs.rename(`${JOB_FILE}.tmp`, JOB_FILE);
|
||||
if (!quiet)
|
||||
write_json(upd.JOB_FILE, job, 0o644);
|
||||
}
|
||||
|
||||
function log(msg) {
|
||||
let t = localtime();
|
||||
push(job.log, sprintf('%02d:%02d:%02d %s', t.hour, t.min, t.sec, msg));
|
||||
if (length(job.log) > 300)
|
||||
splice(job.log, 0, length(job.log) - 300);
|
||||
if (length(job.log) > 400)
|
||||
splice(job.log, 0, length(job.log) - 400);
|
||||
save();
|
||||
}
|
||||
|
||||
@@ -67,455 +80,296 @@ function phase(p) {
|
||||
log(p);
|
||||
}
|
||||
|
||||
function q(s) {
|
||||
return "'" + replace(`${s ?? ''}`, "'", "'\\''") + "'";
|
||||
}
|
||||
|
||||
/** A command, its output in the log: { code, out }. */
|
||||
function run(cmd) {
|
||||
let p = fs.popen(cmd + ' 2>&1', 'r');
|
||||
if (!p)
|
||||
return { code: 127, out: '' };
|
||||
let out = p.read('all') ?? '';
|
||||
return { code: p.close(), out };
|
||||
}
|
||||
|
||||
function run_logged(cmd) {
|
||||
let r = run(cmd);
|
||||
for (let line in split(trim(r.out), '\n'))
|
||||
let r = { code: p.close(), out };
|
||||
for (let line in split(trim(out), '\n'))
|
||||
if (length(trim(line)))
|
||||
log(` ${line}`);
|
||||
return r;
|
||||
}
|
||||
|
||||
function repo() {
|
||||
return REPO;
|
||||
const ctx = {
|
||||
pol: POL,
|
||||
work: `/tmp/dawnline-update.${PID}`,
|
||||
log, phase, run, save,
|
||||
// An automatic run (nobody is watching: the previous version is always kept).
|
||||
auto: () => job.auto,
|
||||
versions: (from, to) => {
|
||||
job.from = from;
|
||||
job.to = to;
|
||||
save();
|
||||
},
|
||||
after: (what) => after[what] = true,
|
||||
};
|
||||
|
||||
/** The phase of a component's check (app, amneziawg, packages). */
|
||||
function checking(name) {
|
||||
if (name == 'app')
|
||||
return _('Checking Dawnline');
|
||||
if (name == 'amneziawg')
|
||||
return _('Checking AmneziaWG');
|
||||
return _('Checking system packages');
|
||||
}
|
||||
|
||||
function have_curl() {
|
||||
return fs.access('/usr/bin/curl', 'x');
|
||||
/** The phase of a component's update (app, amneziawg, pkgs). */
|
||||
function updating(name) {
|
||||
if (name == 'app')
|
||||
return _('Updating Dawnline');
|
||||
if (name == 'amneziawg')
|
||||
return _('Updating AmneziaWG');
|
||||
return _('Updating system packages');
|
||||
}
|
||||
|
||||
function download(url, dest) {
|
||||
let r = have_curl()
|
||||
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 2 -o ${q(dest)} ${q(url)}`)
|
||||
: run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(url)}`);
|
||||
return r.code == 0 && (fs.stat(dest)?.size ?? 0) > 0;
|
||||
/* ---------- check results ---------- */
|
||||
|
||||
function checks_file() {
|
||||
return read_json(upd.CHECK_FILE, null)?.components ?? {};
|
||||
}
|
||||
|
||||
/** Latest release tag; the /releases/latest redirect avoids API rate limits. */
|
||||
function latest_tag(rp) {
|
||||
if (have_curl()) {
|
||||
let r = run(`curl -sI --connect-timeout 15 --max-time 30 -o /dev/null -w '%{redirect_url}' ${q('https://github.com/' + rp + '/releases/latest')}`);
|
||||
let m = match(trim(r.out), /\/releases\/tag\/([^\/?#]+)$/);
|
||||
if (m)
|
||||
return m[1];
|
||||
}
|
||||
let r = run(`uclient-fetch -q -T 20 -O - ${q('https://api.github.com/repos/' + rp + '/releases/latest')}`);
|
||||
try {
|
||||
return json(r.out)?.tag_name;
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
/** Components' results into the check file (the others stay as they were). */
|
||||
function save_check(res) {
|
||||
let c = read_json(upd.CHECK_FILE, null) ?? {};
|
||||
c.components ??= {};
|
||||
for (let k, v in res)
|
||||
c.components[k] = { ...v, time: time() };
|
||||
c.time = time();
|
||||
write_json(upd.CHECK_FILE, c, 0o644);
|
||||
}
|
||||
|
||||
function version_cmp(a, b) {
|
||||
let pa = split(replace(`${a}`, /^v/, ''), /[.~+-]/), pb = split(replace(`${b}`, /^v/, ''), /[.~+-]/);
|
||||
for (let i = 0; i < length(pa) || i < length(pb); i++) {
|
||||
let x = pa[i] ?? '0', y = pb[i] ?? '0';
|
||||
if (match(x, /^[0-9]+$/) && match(y, /^[0-9]+$/)) {
|
||||
if (int(x) != int(y))
|
||||
return int(x) < int(y) ? -1 : 1;
|
||||
/**
|
||||
* What a check found, as short names ("Dawnline 0.3.3", "2 system packages"):
|
||||
* kept in the history and shown later, so English whatever the job's language.
|
||||
*/
|
||||
function found_in(res) {
|
||||
let found = [];
|
||||
if (res.app?.update)
|
||||
push(found, `Dawnline ${res.app.latest}`);
|
||||
if (res.amneziawg?.update && res.amneziawg.installed)
|
||||
push(found, `AmneziaWG ${res.amneziawg.latest}`);
|
||||
if (res.packages?.updates)
|
||||
push(found, sprintf(res.packages.updates == 1 ? L_('%d system package') : L_('%d system packages'), res.packages.updates));
|
||||
return found;
|
||||
}
|
||||
|
||||
function run_checks(which) {
|
||||
let res = {};
|
||||
for (let name in which) {
|
||||
phase(checking(name));
|
||||
try {
|
||||
res[name] = CHECKS[name](ctx);
|
||||
}
|
||||
else if (x != y)
|
||||
return x < y ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function is_apk() {
|
||||
return fs.access('/usr/bin/apk', 'x');
|
||||
}
|
||||
|
||||
function pkg_version(name) {
|
||||
let esc = replace(name, /[.+]/g, '\\$&');
|
||||
if (is_apk()) {
|
||||
let m = match(run(`apk list --installed ${q(name)}`).out, regexp(`^${esc}-([^ ]+) `));
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
// Libraries carry their ABI in the name (libustream-openssl20201210).
|
||||
let re = regexp(`^${esc}([0-9]+)? - (.+)$`), found = null;
|
||||
for (let line in split(run('opkg list-installed').out, '\n')) {
|
||||
let m = match(trim(line), re);
|
||||
if (m && (found == null || m[1] == null))
|
||||
found = m;
|
||||
}
|
||||
return found ? trim(found[2]) : null;
|
||||
}
|
||||
|
||||
function pkg_file_version(path) {
|
||||
if (match(path, /\.ipk$/)) {
|
||||
let o = run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out;
|
||||
return match(o, /(^|\n)Version: *([^\n]+)/)?.[2];
|
||||
}
|
||||
return match(run(`apk adbdump ${q(path)}`).out, /\n *version: *([^\n]+)/)?.[1];
|
||||
}
|
||||
|
||||
function workdir() {
|
||||
run(`rm -rf ${WORK_DIR}`);
|
||||
fs.mkdir(WORK_DIR, 0o700);
|
||||
}
|
||||
|
||||
/* ---------- Dawnline itself ---------- */
|
||||
|
||||
function check_app() {
|
||||
let rp = repo();
|
||||
let tag = latest_tag(rp);
|
||||
if (!tag)
|
||||
return { installed: VERSION, latest: null, update: false, note: `No published release in ${rp}` };
|
||||
let latest = replace(tag, /^v/, '');
|
||||
return { installed: VERSION, latest, tag, repo: rp, update: version_cmp(VERSION, latest) < 0 };
|
||||
}
|
||||
|
||||
function install_app() {
|
||||
let c = check_app();
|
||||
if (!c.latest)
|
||||
die(c.note);
|
||||
if (!c.update) {
|
||||
log('Dawnline is up to date');
|
||||
return { installed: VERSION };
|
||||
}
|
||||
// Releases carry luci-app-dawnline-<version>.ipk and .apk plus sha256sums.txt.
|
||||
let asset = `luci-app-dawnline-${c.latest}.${is_apk() ? 'apk' : 'ipk'}`;
|
||||
let base = `https://github.com/${c.repo}/releases/download/${c.tag}`;
|
||||
workdir();
|
||||
phase(`Downloading ${asset}`);
|
||||
let f = `${WORK_DIR}/${asset}`, sums = `${WORK_DIR}/sha256sums.txt`;
|
||||
if (!download(`${base}/${asset}`, f))
|
||||
die(`Download failed: ${asset}`);
|
||||
phase('Verifying package');
|
||||
if (!download(`${base}/sha256sums.txt`, sums))
|
||||
die('The release has no sha256sums.txt');
|
||||
let want = null;
|
||||
for (let line in split(fs.readfile(sums) ?? '', '\n')) {
|
||||
let m = match(trim(line), /^([0-9a-f]{64})[ \t]+\*?(\S+)$/);
|
||||
if (m && m[2] == asset)
|
||||
want = m[1];
|
||||
}
|
||||
let got = match(run(`sha256sum ${q(f)}`).out, /^([0-9a-f]{64})/)?.[1];
|
||||
if (!want || got != want)
|
||||
die(`Checksum mismatch for ${asset}`);
|
||||
phase('Backing up configuration');
|
||||
run('/usr/bin/dawnline backup --reason pre-update');
|
||||
phase('Installing package');
|
||||
if (run_logged(is_apk() ? `apk add --allow-untrusted ${q(f)}` : `opkg install ${q(f)}`).code != 0)
|
||||
die('Installation failed');
|
||||
run('rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null');
|
||||
// Restart after this job has saved its final state.
|
||||
run('( sleep 3; /etc/init.d/rpcd reload; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
|
||||
return { installed: c.latest };
|
||||
}
|
||||
|
||||
/* ---------- AmneziaWG ---------- */
|
||||
|
||||
function awg_release() {
|
||||
let u = connect();
|
||||
let b = u?.call('system', 'board') ?? {};
|
||||
u?.disconnect();
|
||||
let rel = b.release ?? {};
|
||||
let target = split(rel.target ?? '', '/');
|
||||
let arch = rel.arch ?? trim(run("sed -n \"s/^DISTRIB_ARCH='\\(.*\\)'/\\1/p\" /etc/openwrt_release").out);
|
||||
if (!rel.version || length(target) != 2 || !arch)
|
||||
return null;
|
||||
return {
|
||||
tag: `v${rel.version}`,
|
||||
postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`,
|
||||
ext: is_apk() ? 'apk' : 'ipk',
|
||||
};
|
||||
}
|
||||
|
||||
function awg_download(r, name, rp) {
|
||||
let file = `${name}${r.postfix}.${r.ext}`;
|
||||
let dest = `${WORK_DIR}/${replace(rp, '/', '_')}_${file}`;
|
||||
return download(`https://github.com/${rp}/releases/download/${r.tag}/${file}`, dest) ? dest : null;
|
||||
}
|
||||
|
||||
/** When the build for this firmware was published (best effort). */
|
||||
function release_date(rp, tag) {
|
||||
let r = run(`uclient-fetch -q -T 20 -O - ${q(`https://api.github.com/repos/${rp}/releases/tags/${tag}`)}`);
|
||||
try {
|
||||
return json(r.out)?.published_at ?? null;
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** AmneziaWG generation of a tools version: 3.x packages carry 3.1, older ones (1.0.x) 2.0. */
|
||||
function awg_gen(version) {
|
||||
return version == null ? null : match(version, /^3\./) ? '3.1' : '2.0';
|
||||
}
|
||||
|
||||
/** The newest tag of the same OpenWrt series (24.10.x) in a repository, if newer than ours. */
|
||||
function newer_series_tag(rp, tag) {
|
||||
let r = run(`uclient-fetch -q -T 20 -O - ${q(`https://api.github.com/repos/${rp}/releases?per_page=30`)}`);
|
||||
let series = match(tag, /^v([0-9]+\.[0-9]+)\./)?.[1];
|
||||
let best = null;
|
||||
try {
|
||||
for (let x in json(r.out) ?? []) {
|
||||
let t = x.tag_name;
|
||||
if (series && match(t, regexp(`^v${replace(series, '.', '\\.')}\\.`)) && version_cmp(t, tag) > 0 && (!best || version_cmp(t, best) > 0))
|
||||
best = t;
|
||||
catch (e) {
|
||||
log(sprintf(_('Error: %s'), e.message));
|
||||
res[name] = { error: e.message, status: '' };
|
||||
}
|
||||
}
|
||||
catch (e) {}
|
||||
return best;
|
||||
save_check(res);
|
||||
return res;
|
||||
}
|
||||
|
||||
function awg_installed() {
|
||||
let r = {};
|
||||
for (let p in AWG_PKGS)
|
||||
r[p] = pkg_version(p);
|
||||
return r;
|
||||
/** One line in Activity per new finding (the same finding is not repeated). */
|
||||
function note_found(res, st, auto) {
|
||||
let found = found_in(res);
|
||||
let sig = join(', ', found);
|
||||
if (length(found) && sig != st.announced) {
|
||||
if (auto)
|
||||
slog('dawnline', 'info', sprintf(L_('updates available · %s'), sig), null, L_('Components'));
|
||||
upd.history_add({ kind: 'found', items: found, auto });
|
||||
}
|
||||
st.announced = sig;
|
||||
}
|
||||
|
||||
function check_awg() {
|
||||
let installed = awg_installed();
|
||||
let ru = pkg_version(AWG_RU) != null;
|
||||
let cur = installed['amneziawg-tools'];
|
||||
let r = awg_release();
|
||||
if (!r)
|
||||
return { installed: cur, gen: awg_gen(cur), packages: installed, current: null, ru, sources: {}, update: false, note: 'Cannot detect the firmware target' };
|
||||
workdir();
|
||||
let sources = {};
|
||||
for (let id, src in AWG_SOURCES) {
|
||||
let f = awg_download(r, 'amneziawg-tools', src.repo);
|
||||
let v = f ? pkg_file_version(f) : null;
|
||||
let s2 = { label: src.label, repo: src.repo, tag: r.tag, version: v, gen: awg_gen(v), date: f ? release_date(src.repo, r.tag) : null };
|
||||
// A newer firmware may already get 3.1 from this source.
|
||||
if (s2.gen != '3.1') {
|
||||
let nt = newer_series_tag(src.repo, r.tag);
|
||||
if (nt) {
|
||||
let nf = awg_download({ ...r, tag: nt, postfix: replace(r.postfix, r.tag, nt) }, 'amneziawg-tools', src.repo);
|
||||
let nv = nf ? pkg_file_version(nf) : null;
|
||||
if (awg_gen(nv) == '3.1')
|
||||
s2.newer = { tag: nt, gen: '3.1' };
|
||||
}
|
||||
/* ---------- installs ---------- */
|
||||
|
||||
/** A line in the service log for each finished update (Dawnline's own is logged by the new agent). */
|
||||
function log_update(name, r) {
|
||||
if (name == 'amneziawg') {
|
||||
let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg'];
|
||||
slog('awg', 'up', b && a && b != a ? sprintf(job.auto ? L_('updated automatically · %s → %s') : L_('updated · %s → %s'), b, a)
|
||||
: a ? sprintf(L_('installed the %s build · %s'), r?.build ?? '', a) : sprintf(L_('installed the %s build'), r?.build ?? ''), null, 'AmneziaWG');
|
||||
}
|
||||
else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ]))
|
||||
slog('dawnline', 'up', sprintf(job.auto ? L_('updated automatically · %s') : L_('updated · %s'),
|
||||
join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])), null, L_('System packages'));
|
||||
}
|
||||
|
||||
function split_target(w) {
|
||||
let i = index(w, ':'), at = index(w, '@');
|
||||
let cut = i < 0 ? at : at < 0 || i < at ? i : at;
|
||||
if (cut < 0)
|
||||
return [ w, null ];
|
||||
return [ substr(w, 0, cut), substr(w, cut + (substr(w, cut, 1) == ':' ? 1 : 0)) ];
|
||||
}
|
||||
|
||||
function app_status(installed, latest) {
|
||||
if (!latest)
|
||||
return 'latest';
|
||||
let c = upd.version_cmp(installed, latest);
|
||||
return c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
|
||||
}
|
||||
|
||||
function install(what) {
|
||||
job.result ??= {};
|
||||
for (let w in what) {
|
||||
let t = split_target(w), name = t[0], arg = t[1];
|
||||
if (!INSTALLS[name])
|
||||
die(sprintf(_('Unknown component %s'), name));
|
||||
job.current = name;
|
||||
phase(updating(name));
|
||||
let r = INSTALLS[name](ctx, arg);
|
||||
job.result[name] = r;
|
||||
log_update(name, r);
|
||||
// Installed components are current now: no stale "Update available".
|
||||
let c = checks_file();
|
||||
if (name == 'pkgs' && r.check)
|
||||
save_check({ packages: r.check });
|
||||
else if (name == 'app' && r.to && c.app) {
|
||||
let s = app_status(r.to, c.app.latest);
|
||||
save_check({ app: { ...c.app, installed: r.to, update: s == 'outdated', status: s } });
|
||||
}
|
||||
sources[id] = s2;
|
||||
else if (name == 'amneziawg' && r.after)
|
||||
save_check({ amneziawg: { ...(c.amneziawg ?? {}), installed: r.after['amneziawg-tools'], packages: r.after,
|
||||
current: r.build ?? c.amneziawg?.current, update: false, status: 'latest' } });
|
||||
upd.history_add({ kind: 'install', component: w, from: r.from, to: r.to, state: 'done', auto: job.auto,
|
||||
took: time() - job.started });
|
||||
delete job.current;
|
||||
}
|
||||
// The installed build: the source whose package matches, else the main one.
|
||||
let current = null;
|
||||
for (let id, x in sources)
|
||||
if (!current && cur && x.version == cur)
|
||||
current = id;
|
||||
current ??= cur ? 'slava' : null;
|
||||
let mine = current ? sources[current] : null;
|
||||
return { installed: cur, gen: awg_gen(cur), packages: installed, current, ru, release: r.tag, sources,
|
||||
latest: mine?.version ?? null,
|
||||
update: cur == null || (mine?.version != null && version_cmp(cur, mine.version) < 0),
|
||||
note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(r.tag, 1)} yet` : null };
|
||||
}
|
||||
|
||||
function install_awg(arg) {
|
||||
let parts = split(arg ?? '', ':');
|
||||
let id = parts[0] || 'slava';
|
||||
let src = AWG_SOURCES[id];
|
||||
if (!src)
|
||||
die(`Unknown AmneziaWG build ${id}`);
|
||||
let want_ru = parts[1] == 'ru';
|
||||
let r = awg_release();
|
||||
if (!r)
|
||||
die('Cannot detect the firmware target');
|
||||
let before = awg_installed();
|
||||
workdir();
|
||||
let files = [];
|
||||
for (let p in [ ...AWG_PKGS, ...(want_ru ? [ AWG_RU ] : []) ]) {
|
||||
phase(`Downloading ${p} from ${src.repo}`);
|
||||
let f = awg_download(r, p, src.repo);
|
||||
if (!f)
|
||||
die(`No ${p} build for OpenWrt ${substr(r.tag, 1)} in ${src.repo}`);
|
||||
push(files, f);
|
||||
}
|
||||
phase('Refreshing package lists');
|
||||
run_logged(is_apk() ? 'apk update' : 'opkg update');
|
||||
phase(`Installing the ${src.label} build`);
|
||||
let cmd = is_apk()
|
||||
? `apk add --allow-untrusted ${join(' ', map(files, q))}`
|
||||
: `opkg install --force-reinstall --force-downgrade ${join(' ', map(files, q))}`;
|
||||
if (run_logged(cmd).code != 0)
|
||||
die('Package installation failed');
|
||||
if (!want_ru && pkg_version(AWG_RU))
|
||||
run_logged(is_apk() ? `apk del ${AWG_RU}` : `opkg remove ${AWG_RU}`);
|
||||
let after = awg_installed();
|
||||
if (before['kmod-amneziawg'] && before['kmod-amneziawg'] != after['kmod-amneziawg']) {
|
||||
// New kernel module: every AmneziaWG interface must be re-created.
|
||||
let ifaces = [];
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
c.foreach('network', 'interface', (s) => {
|
||||
if (s.proto == 'amneziawg' && s.disabled != '1')
|
||||
push(ifaces, s['.name']);
|
||||
});
|
||||
phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`);
|
||||
for (let i in ifaces)
|
||||
run(`ifdown ${q(i)}`);
|
||||
run('rmmod amneziawg');
|
||||
run_logged('modprobe amneziawg');
|
||||
for (let i in ifaces)
|
||||
run(`ifup ${q(i)}`);
|
||||
}
|
||||
run('rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null');
|
||||
return { build: id, before, after };
|
||||
}
|
||||
|
||||
/* ---------- OpenWrt packages Dawnline uses ---------- */
|
||||
|
||||
// Installed packages with a newer version in the feeds: { name: latest }.
|
||||
function upgradable(refresh) {
|
||||
if (refresh) {
|
||||
phase('Refreshing package lists');
|
||||
run(is_apk() ? 'apk update' : 'opkg update');
|
||||
}
|
||||
let up = {};
|
||||
if (is_apk()) {
|
||||
for (let line in split(run('apk version -l "<"').out, '\n')) {
|
||||
let m = match(line, /^(\S+?)-([0-9][^ ]*)\s+<\s+(\S+)/);
|
||||
if (m)
|
||||
up[m[1]] = m[3];
|
||||
}
|
||||
/** Settings → Updates: check when due, install what is allowed (scheduled or right away). */
|
||||
function auto() {
|
||||
let st = upd.auto_state();
|
||||
let what = upd.due(POL, st);
|
||||
if (!what)
|
||||
return;
|
||||
let now = time();
|
||||
let res;
|
||||
if (what == 'check' || now - (st.check ?? 0) >= 3600) {
|
||||
res = run_checks(upd.TARGETS);
|
||||
st.check = now;
|
||||
note_found(res, st, true);
|
||||
}
|
||||
else
|
||||
for (let line in split(run('opkg list-upgradable').out, '\n')) {
|
||||
let m = match(line, /^(\S+) - (\S+) - (\S+)/);
|
||||
if (m)
|
||||
up[m[1]] = m[3];
|
||||
}
|
||||
return up;
|
||||
res = checks_file();
|
||||
if (what == 'install')
|
||||
upd.mark_day(POL, st, now);
|
||||
upd.auto_save(st);
|
||||
if (!POL.auto || (what != 'install' && POL.mode != 'immediate'))
|
||||
return;
|
||||
let todo = [];
|
||||
// Packages first, Dawnline last: it restarts rpcd and itself.
|
||||
if (index(POL.targets, 'packages') >= 0 && res.packages?.updates) {
|
||||
let names = filter(keys(res.packages.pkgs ?? {}), (p) => res.packages.pkgs[p].latest || length(res.packages.pkgs[p].with ?? []));
|
||||
if (length(names))
|
||||
push(todo, `pkgs:${join(',', names)}`);
|
||||
}
|
||||
let a = res.amneziawg;
|
||||
if (index(POL.targets, 'amneziawg') >= 0 && a?.update && a.installed) {
|
||||
// Only the same build, same generation: anything else needs a person to decide.
|
||||
if (a.current && !a.gen_change)
|
||||
push(todo, `amneziawg:${a.current}${a.ru ? ':ru' : ''}`);
|
||||
else
|
||||
slog('awg', 'info', a.latest ? sprintf(L_('%s needs a manual switch in Components'), a.latest) : L_('a new build needs a manual switch in Components'), null, 'AmneziaWG');
|
||||
}
|
||||
if (index(POL.targets, 'app') >= 0 && res.app?.update)
|
||||
push(todo, 'app');
|
||||
if (!length(todo))
|
||||
return;
|
||||
quiet = false;
|
||||
job.action = 'install';
|
||||
job.component = join(' ', todo);
|
||||
job.auto = true;
|
||||
job.log = [];
|
||||
log(sprintf(_('Automatic update: %s'), join(', ', todo)));
|
||||
install(todo);
|
||||
}
|
||||
|
||||
// The packages to update for these names: each one plus its upgradable family.
|
||||
function with_family(names, up) {
|
||||
let set = {};
|
||||
for (let n in names) {
|
||||
if (up[n])
|
||||
set[n] = true;
|
||||
let f = family(n);
|
||||
if (f)
|
||||
for (let u in keys(up))
|
||||
if (match(u, f))
|
||||
set[u] = true;
|
||||
/**
|
||||
* The restarts the job asked for, in one go, after its final state is saved.
|
||||
* Dawnline's own package is restarted by postupdate, a shell that also checks
|
||||
* the new version and rolls back to the kept one when it does not come up.
|
||||
*/
|
||||
function restarts() {
|
||||
if (after.app) {
|
||||
let to = replace(`${job.to ?? ''}`, /[^A-Za-z0-9.-]/g, '');
|
||||
system(`/usr/libexec/dawnline/postupdate '${to}' </dev/null >/dev/null 2>&1 &`);
|
||||
return;
|
||||
}
|
||||
return sort(keys(set));
|
||||
let cmds = [];
|
||||
if (after.apply)
|
||||
push(cmds, '/usr/bin/dawnline apply');
|
||||
// LuCI's own web server reads a language's catalogs once: a new translation needs a fresh one.
|
||||
if (after.uhttpd || after.luci)
|
||||
push(cmds, '/etc/init.d/uhttpd restart');
|
||||
if (after.apply || after.uhttpd)
|
||||
push(cmds, '/etc/init.d/dawnline restart');
|
||||
if (length(cmds))
|
||||
system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`);
|
||||
}
|
||||
|
||||
function check_pkgs(refresh) {
|
||||
let up = upgradable(refresh ?? true);
|
||||
let res = {}, all = {};
|
||||
for (let p in SYS_PKGS) {
|
||||
let v = pkg_version(p);
|
||||
let set = v ? with_family([ p ], up) : [];
|
||||
res[p] = { installed: v, latest: v && up[p] ? up[p] : null, with: filter(set, (x) => x != p) };
|
||||
for (let x in set)
|
||||
all[x] = true;
|
||||
}
|
||||
return { pkgs: res, updates: length(keys(all)) };
|
||||
}
|
||||
|
||||
// Before install_pkgs: ucode resolves a name at the point it is used.
|
||||
function save_check(res, at) {
|
||||
fs.writefile(CHECK_FILE, sprintf('%J', { time: at ?? time(), components: res }));
|
||||
}
|
||||
|
||||
function install_pkgs(arg) {
|
||||
let names = filter(split(arg ?? '', ','), (x) => x != '');
|
||||
for (let n in names)
|
||||
if (index(SYS_PKGS, n) < 0)
|
||||
die(`${n} is not a package Dawnline manages`);
|
||||
if (!length(names))
|
||||
die('Nothing to install');
|
||||
phase('Refreshing package lists');
|
||||
run_logged(is_apk() ? 'apk update' : 'opkg update');
|
||||
let missing = filter(names, (n) => pkg_version(n) == null);
|
||||
let have = with_family(filter(names, (n) => pkg_version(n) != null), upgradable(false));
|
||||
if (length(have)) {
|
||||
phase(`Updating ${join(', ', have)}`);
|
||||
if (run_logged(is_apk() ? `apk upgrade ${join(' ', map(have, q))}` : `opkg upgrade ${join(' ', map(have, q))}`).code != 0)
|
||||
die('Update failed');
|
||||
}
|
||||
if (length(missing)) {
|
||||
phase(`Installing ${join(', ', missing)}`);
|
||||
if (run_logged(is_apk() ? `apk add ${join(' ', map(missing, q))}` : `opkg install ${join(' ', map(missing, q))}`).code != 0)
|
||||
die('Installation failed');
|
||||
}
|
||||
// Show the new state right away instead of the check from before the update.
|
||||
/** The job the command line asks for, to its final state: done, or failed with the error in the log and the history. */
|
||||
function main() {
|
||||
try {
|
||||
let c = json(fs.readfile(CHECK_FILE) ?? '{}') ?? {};
|
||||
c.components ??= {};
|
||||
c.components.packages = check_pkgs(false);
|
||||
save_check(c.components, c.time);
|
||||
if (job.action == 'check') {
|
||||
let which = job.component ? [ job.component ] : upd.TARGETS;
|
||||
for (let w in which)
|
||||
if (!CHECKS[w])
|
||||
die(sprintf(_('Unknown component %s'), w));
|
||||
job.result = run_checks(which);
|
||||
let st = upd.auto_state();
|
||||
note_found(job.result, st, false);
|
||||
if (length(which) == length(upd.TARGETS))
|
||||
st.check = time();
|
||||
upd.auto_save(st);
|
||||
}
|
||||
else if (job.action == 'install')
|
||||
install([ job.component ]);
|
||||
else if (job.action == 'auto')
|
||||
auto();
|
||||
else
|
||||
die(USAGE);
|
||||
job.state = 'done';
|
||||
phase(_('Finished'));
|
||||
}
|
||||
catch (e) {
|
||||
log(`Could not refresh the package check: ${e.message}`);
|
||||
quiet = false;
|
||||
job.state = 'failed';
|
||||
job.error = e.message;
|
||||
log(sprintf(_('Error: %s'), e.message));
|
||||
let name = job.current ?? split_target(split(job.component ?? '', ' ')[0])[0];
|
||||
if (job.action != 'check') {
|
||||
slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', job.auto ? L_('automatic update failed') : L_('update failed'), e.message, WHO[name] ?? 'Dawnline');
|
||||
upd.history_add({ kind: 'install', component: name, from: job.from, to: job.to, state: 'failed', auto: job.auto, error: e.message,
|
||||
took: time() - job.started });
|
||||
}
|
||||
else
|
||||
upd.history_add({ kind: 'error', component: job.component ?? 'all', state: 'failed', error: e.message });
|
||||
}
|
||||
// The portal's HTTPS runs in uhttpd. Restart after this job saved its state.
|
||||
let touched = [ ...names, ...have ];
|
||||
// A missing piece arrived: set up what waited for it (the portal, the home-like link).
|
||||
if (length(missing) && length(filter(missing, (n) => match(n, /^(openssl-util|libustream|ip-full|kmod-veth)/))))
|
||||
run('( sleep 3; /usr/bin/dawnline apply; /etc/init.d/uhttpd restart; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
|
||||
else if (length(filter(touched, (n) => match(n, /^(libustream|libopenssl)/))))
|
||||
run('( sleep 3; /etc/init.d/uhttpd restart; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
|
||||
return { updated: have, installed: missing };
|
||||
}
|
||||
|
||||
/* ---------- main ---------- */
|
||||
|
||||
const CHECKS = { app: check_app, amneziawg: check_awg, packages: check_pkgs };
|
||||
const INSTALLS = { app: install_app, amneziawg: install_awg, pkgs: install_pkgs };
|
||||
|
||||
|
||||
if (!fs.access(STATE_DIR))
|
||||
fs.mkdir(STATE_DIR, 0o755);
|
||||
ensure_dir(RUN_DIR);
|
||||
// One job at a time (LuCI refuses a second one; an automatic run just skips its turn).
|
||||
let LOCK = null;
|
||||
for (let i = 0; i < 10 && !LOCK; i++) {
|
||||
LOCK = upd.try_lock();
|
||||
if (!LOCK)
|
||||
system('usleep 100000 2>/dev/null || sleep 1');
|
||||
}
|
||||
if (!LOCK)
|
||||
exit(0);
|
||||
fs.mkdir(ctx.work, 0o700);
|
||||
save();
|
||||
main();
|
||||
|
||||
try {
|
||||
if (job.action == 'check') {
|
||||
let res = {};
|
||||
for (let name, fn in CHECKS) {
|
||||
phase(`Checking ${name}`);
|
||||
try {
|
||||
res[name] = fn();
|
||||
}
|
||||
catch (e) {
|
||||
res[name] = { error: e.message };
|
||||
}
|
||||
}
|
||||
save_check(res);
|
||||
job.result = res;
|
||||
}
|
||||
else if (job.action == 'install') {
|
||||
let what = job.component == 'all' ? [ 'amneziawg', 'app' ] : [ job.component ];
|
||||
job.result = {};
|
||||
for (let w in what) {
|
||||
let i = index(w, ':');
|
||||
let name = i < 0 ? w : substr(w, 0, i), arg = i < 0 ? null : substr(w, i + 1);
|
||||
if (!INSTALLS[name])
|
||||
die(`Unknown component ${name}`);
|
||||
phase(`Updating ${name}`);
|
||||
job.result[name] = INSTALLS[name](arg);
|
||||
}
|
||||
}
|
||||
else
|
||||
die('Usage: updater check | install app|amneziawg[:build[:ru]]|pkgs:<names>|all');
|
||||
job.state = 'done';
|
||||
phase('Finished');
|
||||
}
|
||||
catch (e) {
|
||||
job.state = 'failed';
|
||||
job.error = e.message;
|
||||
log(`Error: ${e.message}`);
|
||||
}
|
||||
|
||||
run(`rm -rf ${WORK_DIR}`);
|
||||
system(`rm -rf '${ctx.work}'`);
|
||||
job.finished = time();
|
||||
delete job.current;
|
||||
save();
|
||||
restarts();
|
||||
@@ -1 +1 @@
|
||||
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.pill{display:inline-flex;align-items:center;height:22px;padding:0 9px;border-radius:999px;font-size:12px;font-weight:500;background:var(--soft);color:var(--muted)}.pill.ok{background:var(--ok-wash);color:var(--ok)}.pill.warn{background:var(--warn-wash);color:var(--warn)}.pill.bad{background:var(--bad-wash);color:var(--bad)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);mLine truncated
|
||||
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{color-scheme:dark;--bg: #080808;--raised: #121212;--field: #161616;--knob: #232323;--seg: rgba(237, 237, 237, .05);--seg-shadow: none;--line: rgba(255, 255, 255, .06);--text: #ededed;--text-2: #8c8c8a;--text-3: #4f4f4e;--accent: #4eafff;--accent-ink: #ffffff;--accent-soft: rgba(78, 175, 255, .13);--ok: #30d158;--ok-soft: rgba(48, 209, 88, .14);--warn: #ff8d28;--bad: #ff383c;--bad-soft: rgba(255, 56, 60, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--glass-bg: linear-gradient(rgba(255, 255, 255, .04), rgba(255, 255, 255, .04)), rgba(0, 0, 0, .4);--glass-edge: rgba(255, 255, 255, .05);--glass-sep: rgba(255, 255, 255, .04);--glass-text: #f5f5f5;--glass-sub: #8a8a8a;--glass-bad: var(--bad);--glass-hl: color-mix(in srgb, var(--raised), var(--text) 8%);--glass-hover: color-mix(in srgb, var(--raised), var(--text) 5%);--glass-shadow: 0 0 0 transparent;--line-glass: rgba(255, 255, 255, .07);--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, .75);--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, .6);--bar: rgba(237, 237, 237, .13);--toast: #232323;--toast-fg: #ededed;--qr-bg: #0a0a0a;--gi-a: rgba(255, 255, 255, .58);--gi-b: rgba(255, 255, 255, .14);--gi-rim: rgba(255, 255, 255, .5);--gi-edge: rgba(0, 0, 0, 0);--gi-detail: #ffffff;--t-grey-a: #cfcfcd;--t-grey-b: #5a5a59;--t-blue-a: #a6d9ff;--t-blue-b: #1d84e6;--t-green-a: #a8f29c;--t-green-b: #30d158;--t-red-a: #ffadad;--t-red-b: #ff383c;--t-orange-a: #ffc08f;--t-orange-b: #ff8d28;--font: Geist, -apple-system, system-ui, "Segoe UI", sans-serif;--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;--r-sheet: 36px;--r-card: 28px;--r-row: 20px;--r-field: 16px;--r-tile: 12px;--ease-out: cubic-bezier(.23, 1, .32, 1);--gutter-l: max(16px, env(safe-area-inset-left, 0px));--gutter-r: max(16px, env(safe-area-inset-right, 0px))}@media(prefers-color-scheme:light){:root{color-scheme:light;--bg: #f2f2f1;--raised: #ffffff;--field: #f3f3f2;--knob: #e8e8e7;--seg: #ffffff;--seg-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .05);--line: rgba(0, 0, 0, .07);--text: #0b0b0b;--text-2: #6d6d6b;--text-3: #a6a6a4;--accent: #2b9dff;--accent-soft: rgba(43, 157, 255, .12);--ok: #30d158;--ok-soft: rgba(48, 209, 88, .12);--warn: #ff8d28;--bad: #ff383c;--bad-soft: rgba(255, 56, 60, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--glass-bg: rgba(245, 245, 245, .6);--glass-edge: rgba(0, 0, 0, .04);--glass-sep: rgba(0, 0, 0, .03);--glass-text: #1a1a1a;--glass-sub: #727272;--glass-hl: color-mix(in srgb, var(--raised), var(--text) 11%);--glass-hover: color-mix(in srgb, var(--raised), var(--text) 4%);--glass-shadow: 0 8px 32px rgba(0, 0, 0, .12);--line-glass: rgba(0, 0, 0, .07);--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, .2);--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, .22);--bar: rgba(11, 11, 11, .11);--toast: #0b0b0b;--toast-fg: #f2f2f1;--qr-bg: #ffffff;--gi-a: rgba(250, 250, 249, .72);--gi-b: rgba(206, 206, 204, .5);--gi-rim: rgba(255, 255, 255, .9);--gi-edge: rgba(0, 0, 0, .11);--gi-detail: rgba(28, 28, 28, .72);--t-grey-a: #a9a9a7;--t-grey-b: #3d3d3c;--t-blue-a: #7cc4ff;--t-blue-b: #0a6fd6;--t-green-a: #82e070;--t-green-b: #30d158;--t-red-a: #ff9090;--t-red-b: #ff383c}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable;overflow-anchor:none;touch-action:manipulation}body{margin:0;background:var(--bg);color:var(--text);font:400 15px/22px var(--font);letter-spacing:-.011em;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}body.locked{overflow:hidden}input,textarea,.linkrow .mono,.conf{cursor:text}::selection{background:var(--sel-bg);color:var(--sel-fg)}button{font:inherit;color:inherit;letter-spacing:inherit;background:none;border:0;padding:0;margin:0;cursor:pointer;-webkit-tap-highlight-color:transparent}button:disabled{cursor:default}a{color:inherit;text-decoration:none}:focus{outline:none}.kbd :focus-visible{outline:2px solid color-mix(in srgb,var(--accent) 65%,transparent);outline-offset:2px}[hidden]{display:none!important}.offscreen{position:fixed;left:-9999px;top:0;opacity:0}.mono{font-family:var(--mono);letter-spacing:0}.num{font-variant-numeric:tabular-nums}.ok-t{color:var(--ok)}.warn-t{color:var(--warn)}.bad-t{color:var(--bad)}.here-t{color:var(--accent)}.i{width:18px;height:18px;flex:none}.gi{width:24px;height:24px;flex:none;overflow:visible;--ta: var(Line truncated
|
||||
@@ -1,6 +1,6 @@
|
||||
"use strict";(()=>{var tt=Object.create;var $e=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var at=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty;var st=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ot=(n,e,a,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let v of rt(e))!it.call(n,v)&&v!==a&&$e(n,v,{get:()=>e[v],enumerable:!(o=nt(e,v))||o.enumerable});return n};var lt=(n,e,a)=>(a=n!=null?tt(at(n)):{},ot(e||!n||!n.__esModule?$e(a,"default",{value:n,enumerable:!0}):a,n));var Ue=st((Oe,Ke)=>{"use strict";var Ie=(function(){var n=function(M,k){var w=236,b=17,l=M,m=a[k],i=null,r=0,y=null,f=[],g={},T=function(c,u){r=l*4+17,i=(function(s){for(var d=new Array(s),h=0;h<s;h+=1){d[h]=new Array(s);for(var x=0;x<s;x+=1)d[h][x]=null}return d})(r),E(0,0),E(r-7,0),E(0,r-7),q(),I(),Q(c,u),l>=7&&z(c),y==null&&(y=Xe(l,m,f)),W(y,u)},E=function(c,u){for(var s=-1;s<=7;s+=1)if(!(c+s<=-1||r<=c+s))for(var d=-1;d<=7;d+=1)u+d<=-1||r<=u+d||(0<=s&&s<=6&&(d==0||d==6)||0<=d&&d<=6&&(s==0||s==6)||2<=s&&s<=4&&2<=d&&d<=4?i[c+s][u+d]=!0:i[c+s][u+d]=!1)},P=function(){for(var c=0,u=0,s=0;s<8;s+=1){T(!0,s);var d=v.getLostPoint(g);(s==0||c>d)&&(c=d,u=s)}return u},I=function(){for(var c=8;c<r-8;c+=1)i[c][6]==null&&(i[c][6]=c%2==0);for(var u=8;u<r-8;u+=1)i[6][u]==null&&(i[6][u]=u%2==0)},q=function(){for(var c=v.getPatternPosition(l),u=0;u<c.length;u+=1)for(var s=0;s<c.length;s+=1){var d=c[u],h=c[s];if(i[d][h]==null)for(var x=-2;x<=2;x+=1)for(var C=-2;C<=2;C+=1)x==-2||x==2||C==-2||C==2||x==0&&C==0?i[d+x][h+C]=!0:i[d+x][h+C]=!1}},z=function(c){for(var u=v.getBCHTypeNumber(l),s=0;s<18;s+=1){var d=!c&&(u>>s&1)==1;i[Math.floor(s/3)][s%3+r-8-3]=d}for(var s=0;s<18;s+=1){var d=!c&&(u>>s&1)==1;i[s%3+r-8-3][Math.floor(s/3)]=d}},Q=function(c,u){for(var s=m<<3|u,d=v.getBCHTypeInfo(s),h=0;h<15;h+=1){var x=!c&&(d>>h&1)==1;h<6?i[h][8]=x:h<8?i[h+1][8]=x:i[r-15+h][8]=x}for(var h=0;h<15;h+=1){var x=!c&&(d>>h&1)==1;h<8?i[8][r-h-1]=x:h<9?i[8][15-h-1+1]=x:i[8][15-h-1]=x}i[r-8][8]=!c},W=function(c,u){for(var s=-1,d=r-1,h=7,x=0,C=v.getMaskFunction(u),A=r-1;A>0;A-=2)for(A==6&&(A-=1);;){for(var S=0;S<2;S+=1)if(i[d][A-S]==null){var K=!1;x<c.length&&(K=(c[x]>>>h&1)==1);var L=C(d,A-S);L&&(K=!K),i[d][A-S]=K,h-=1,h==-1&&(x+=1,h=7)}if(d+=s,d<0||r<=d){d-=s,s=-s;break}}},re=function(c,u){for(var s=0,d=0,h=0,x=new Array(u.length),C=new Array(u.length),A=0;A<u.length;A+=1){var S=u[A].dataCount,K=u[A].totalCount-S;d=Math.max(d,S),h=Math.max(h,K),x[A]=new Array(S);for(var L=0;L<x[A].length;L+=1)x[A][L]=255&c.getBuffer()[L+s];s+=S;var Y=v.getErrorCorrectPolynomial(K),j=_(x[A],Y.getLength()-1),Ee=j.mod(Y);C[A]=new Array(Y.getLength()-1);for(var L=0;L<C[A].length;L+=1){var Be=L+Ee.getLength()-C[A].length;C[A][L]=Be>=0?Ee.getAt(Be):0}}for(var De=0,L=0;L<u.length;L+=1)De+=u[L].totalCount;for(var me=new Array(De),ce=0,L=0;L<d;L+=1)for(var A=0;A<u.length;A+=1)L<x[A].length&&(me[ce]=x[A][L],ce+=1);for(var L=0;L<h;L+=1)for(var A=0;A<u.length;A+=1)L<C[A].length&&(me[ce]=C[A][L],ce+=1);return me},Xe=function(c,u,s){for(var d=$.getRSBlocks(c,u),h=B(),x=0;x<s.length;x+=1){var C=s[x];h.put(C.getMode(),4),h.put(C.getLength(),v.getLengthInBits(C.getMode(),c)),C.write(h)}for(var A=0,x=0;x<d.length;x+=1)A+=d[x].dataCount;if(h.getLengthInBits()>A*8)throw"code length overflow. ("+h.getLengthInBits()+">"+A*8+")";for(h.getLengthInBits()+4<=A*8&&h.put(0,4);h.getLengthInBits()%8!=0;)h.putBit(!1);for(;!(h.getLengthInBits()>=A*8||(h.put(w,8),h.getLengthInBits()>=A*8));)h.put(b,8);return re(h,d)};g.addData=function(c,u){u=u||"Byte";var s=null;switch(u){case"Numeric":s=D(c);break;case"Alphanumeric":s=F(c);break;case"Byte":s=J(c);break;case"Kanji":s=U(c);break;default:throw"mode:"+u}f.push(s),y=null},g.isDark=function(c,u){if(c<0||r<=c||u<0||r<=u)throw c+","+u;return i[c][u]},g.getModuleCount=function(){return r},g.make=function(){if(l<1){for(var c=1;c<40;c++){for(var u=$.getRSBlocks(c,m),s=B(),d=0;d<f.length;d++){var h=f[d];s.put(h.getMode(),4),s.put(h.getLength(),v.getLengthInBits(h.getMode(),c)),h.write(s)}for(var x=0,d=0;d<u.length;d++)x+=u[d].dataCount;if(s.getLengthInBits()<=x*8)break}l=c}T(!1,P())},g.createTableTag=function(c,u){c=c||2,u=typeof u=="undefined"?c*4:u;var s="";s+='<table style="',s+=" border-width: 0px; border-style: none;",s+=" border-collapse: collapse;",s+=" padding: 0px; margin: "+u+"px;",s+='">',s+="<tbody>";for(var d=0;d<g.getModuleCount();d+=1){s+="<tr>";for(var h=0;h<g.getModuleCount();h+=1)s+='<td style="',s+=" border-width: 0px; border-style: none;",s+=" border-collapse: collapse;",s+=" padding: 0px; margin: 0px;",s+=" width: "+c+"px;",s+=" height: "+c+"px;",s+=" background-color: ",s+=g.isDark(d,h)?"#000000":"#ffffff",s+=";",s+='"/>';s+="</tr>"}return s+="</tbody>",s+="</table>",s},g.createSvgTag=function(c,u,s,d){var h={};typeof arguments[0]=="object"&&(h=arguments[0],c=h.cellSize,u=h.margin,s=h.alt,d=h.title),c=c||2,u=typeof u=="undefined"?c*4:u,s=typeof s=="string"?{text:s}:s||{},s.text=s.text||nLine truncated
|
||||
`}return s%2&&c>0?j.substring(0,j.length-s-1)+Array(s+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(c,u){if(c=c||1,c<2)return et(u);c-=1,u=typeof u=="undefined"?c*2:u;var s=g.getModuleCount()*c+u*2,d=u,h=s-u,x,C,A,S,K=Array(c+1).join("██"),L=Array(c+1).join(" "),Y="",j="";for(x=0;x<s;x+=1){for(A=Math.floor((x-d)/c),j="",C=0;C<s;C+=1)S=1,d<=C&&C<h&&d<=x&&x<h&&g.isDark(A,Math.floor((C-d)/c))&&(S=0),j+=S?K:L;for(A=0;A<c;A+=1)Y+=j+`
|
||||
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(c,u){u=u||2;for(var s=g.getModuleCount(),d=0;d<s;d++)for(var h=0;h<s;h++)c.fillStyle=g.isDark(d,h)?"black":"white",c.fillRect(d*u,h*u,u,u)},g};n.stringToBytesFuncs={default:function(M){for(var k=[],w=0;w<M.length;w+=1){var b=M.charCodeAt(w);k.push(b&255)}return k}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(M,k){var w=(function(){for(var l=H(M),m=function(){var I=l.read();if(I==-1)throw"eof";return I},i=0,r={};;){var y=l.read();if(y==-1)break;var f=m(),g=m(),T=m(),E=String.fromCharCode(y<<8|f),P=g<<8|T;r[E]=P,i+=1}if(i!=k)throw i+" != "+k;return r})(),b=63;return function(l){for(var m=[],i=0;i<l.length;i+=1){var r=l.charCodeAt(i);if(r<128)m.push(r);else{var y=w[l.charAt(i)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(b)}}return m}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},a={L:1,M:0,Q:3,H:2},o={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},v=(function(){var M=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],k=1335,w=7973,b=21522,l={},m=function(i){for(var r=0;i!=0;)r+=1,i>>>=1;return r};return l.getBCHTypeInfo=function(i){for(var r=i<<10;m(r)-m(k)>=0;)r^=k<<m(r)-m(k);return(i<<10|r)^b},l.getBCHTypeNumber=function(i){for(var r=i<<12;m(r)-m(w)>=0;)r^=w<<m(r)-m(w);return i<<12|r},l.getPatternPosition=function(i){return M[i-1]},l.getMaskFunction=function(i){switch(i){case o.PATTERN000:return function(r,y){return(r+y)%2==0};case o.PATTERN001:return function(r,y){return r%2==0};case o.PATTERN010:return function(r,y){return y%3==0};case o.PATTERN011:return function(r,y){return(r+y)%3==0};case o.PATTERN100:return function(r,y){return(Math.floor(r/2)+Math.floor(y/3))%2==0};case o.PATTERN101:return function(r,y){return r*y%2+r*y%3==0};case o.PATTERN110:return function(r,y){return(r*y%2+r*y%3)%2==0};case o.PATTERN111:return function(r,y){return(r*y%3+(r+y)%2)%2==0};default:throw"bad maskPattern:"+i}},l.getErrorCorrectPolynomial=function(i){for(var r=_([1],0),y=0;y<i;y+=1)r=r.multiply(_([1,p.gexp(y)],0));return r},l.getLengthInBits=function(i,r){if(1<=r&&r<10)switch(i){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+i}else if(r<27)switch(i){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+i}else if(r<41)switch(i){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+i}else throw"type:"+r},l.getLostPoint=function(i){for(var r=i.getModuleCount(),y=0,f=0;f<r;f+=1)for(var g=0;g<r;g+=1){for(var T=0,E=i.isDark(f,g),P=-1;P<=1;P+=1)if(!(f+P<0||r<=f+P))for(var I=-1;I<=1;I+=1)g+I<0||r<=g+I||P==0&&I==0||E==i.isDark(f+P,g+I)&&(T+=1);T>5&&(y+=3+T-5)}for(var f=0;f<r-1;f+=1)for(var g=0;g<r-1;g+=1){var q=0;i.isDark(f,g)&&(q+=1),i.isDark(f+1,g)&&(q+=1),i.isDark(f,g+1)&&(q+=1),i.isDark(f+1,g+1)&&(q+=1),(q==0||q==4)&&(y+=3)}for(var f=0;f<r;f+=1)for(var g=0;g<r-6;g+=1)i.isDark(f,g)&&!i.isDark(f,g+1)&&i.isDark(f,g+2)&&i.isDark(f,g+3)&&i.isDark(f,g+4)&&!i.isDark(f,g+5)&&i.isDark(f,g+6)&&(y+=40);for(var g=0;g<r;g+=1)for(var f=0;f<r-6;f+=1)i.isDark(f,g)&&!i.isDark(f+1,g)&&i.isDark(f+2,g)&&i.isDark(f+3,g)&&i.isDark(f+4,g)&&!i.isDark(f+5,g)&&i.isDark(f+6,g)&&(y+=40);for(var z=0,g=0;g<r;g+=1)for(var f=0;f<r;f+=1)i.isDark(f,g)&&(z+=1);var Q=Math.abs(100*z/r/r-50)/5;return y+=Q*10,y},l})(),p=(function(){for(var M=new Array(256),k=new Array(256),w=0;w<8;w+=1)M[w]=1<<w;for(var w=8;w<256;w+=1)M[w]=M[w-4]^M[w-5]^M[w-6]^M[w-8];for(var w=0;w<255;w+=1)k[M[w]]=w;var b={};return b.glog=function(l){if(l<1)throw"glog("+l+")";return k[l]},b.gexp=function(l){for(;l<0;)l+=255;for(;l>=256;)l-=255;return M[l]},b})();function _(M,k){if(typeof M.length=="undefined")throw M.length+"/"+k;var w=(function(){for(var l=0;l<M.length&&M[l]==0;)l+=1;for(var m=new Array(M.length-l+k),i=0;i<M.length-l;i+=1)m[i]=M[i+l];return m})(),b={};return b.getAt=function(l){return w[l]},b.getLength=function(){return w.length},b.multiply=function(l){for(var m=new Array(b.getLength()+l.getLength()-1),i=0;i<b.getLength();i+=1)for(var r=0;r<l.getLength();r+=1)m[i+r]^=p.gexp(p.glog(b.getAt(i))+p.glog(l.getAt(r)));return _(m,0)},b.mod=function(l){if(b.getLen
Line truncated
|
||||
`),hostName:p,mtu:a.mtu,persistent_keep_alive:a.persistent_keep_alive,port:Number(a.port),psk_key:a.psk_key,server_pub_key:a.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(_),port:String(a.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:p};return a.dns[0]&&($.dns1=a.dns[0]),a.dns[1]&&($.dns2=a.dns[1]),$}function vt(n){let e="";for(let a=0;a<n.length;a+=32768)e+=String.fromCharCode(...n.subarray(a,a+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pt(n){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let a=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(a).arrayBuffer()),v=new Uint8Array(4+o.length);return new DataView(v.buffer).setUint32(0,n.length,!1),v.set(o,4),v}catch{return null}}async function xe(n,e,a=!0){let o=new TextEncoder().encode(JSON.stringify(ht(n,e))),v=a?await pt(o):null;return`vpn://${vt(v!=null?v:o)}`}function t(n,e={},...a){let o=document.createElement(n);for(let[p,_]of Object.entries(e))_==null||_===!1||(p.startsWith("on")&&typeof _=="function"?o.addEventListener(p.slice(2),_):p==="class"?o.className=String(_):_===!0?o.setAttribute(p,""):o.setAttribute(p,String(_)));let v=p=>{p==null||p===!1||(Array.isArray(p)?p.forEach(v):o.appendChild(typeof p=="string"?document.createTextNode(p):p))};return a.forEach(v),o}function O(n){let e=t("span",{class:"ic"});return e.innerHTML=He(n,"ic-svg"),e}var gt='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>',Ce=document.getElementById("app"),Ye,de=(Ye=Ce.dataset.base)!=null?Ye:"",mt=Ce.dataset.title||"Dawnline",ke=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),R=null,Fe=0,yt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(de)?de.slice(1):"",Ae=class extends Error{constructor(a,o){super(o);this.status=a}};async function oe(n,e){var v;let a=await fetch(`${de}/api/${n}`,{method:e===void 0?"GET":"POST",credentials:"omit",headers:e===void 0?{}:{"Content-Type":"application/json"},body:e===void 0?void 0:JSON.stringify(e),cache:"no-store"}),o=null;try{o=await a.json()}catch{}if(!a.ok)throw new Ae(a.status,(v=o==null?void 0:o.error)!=null?v:`Request failed (${a.status})`);return o}function se(n,e=!1){let a=t("div",{class:`toast${e?" bad":""}`,role:"status"},n);document.body.appendChild(a),requestAnimationFrame(()=>a.classList.add("show")),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>a.remove(),300)},2600)}async function ve(n,e="Copied"){try{await navigator.clipboard.writeText(n)}catch{let a=t("textarea",{class:"offscreen"},n);document.body.appendChild(a),a.select(),document.execCommand("copy"),a.remove()}se(e)}function je(n,e){let a=URL.createObjectURL(new Blob([e],{type:"application/octet-stream"})),o=t("a",{href:a,download:n,class:"offscreen"});document.body.appendChild(o),o.click(),setTimeout(()=>{URL.revokeObjectURL(a),o.remove()},1e3)}var Z=null;function ze(n,e){let a=o=>{Z!=null||(Z=document.body.appendChild(t("div",{class:"tip"}))),Z.replaceChildren(...e().map((v,p)=>t("div",{class:p?"muted":"tip-title"},v))),Z.style.display="",Z.style.left=`${o.clientX}px`,Z.style.top=`${o.clientY-10}px`};n.addEventListener("mouseenter",a),n.addEventListener("mousemove",a),n.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function wt(n){let e=Math.max(1,...n),a=t("div",{class:"spark"});return n.forEach((o,v)=>{let p=t("i",{class:o?"":"zero"});p.style.height=`${Math.max(8,o/e*100)}%`;let _=n.length-1-v,$=new Date(Date.now()-_*864e5);ze(p,()=>[_===0?"Today":_===1?"Yesterday":$.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ee(o)]),a.appendChild(p)}),a}var ie=null,le=null;function te(n=!1){if(!ie)return;let e=ie;if(ie=null,document.body.classList.remove("locked"),le==null||le(),le=null,n){e.remove();return}e.classList.remove("open"),setTimeout(()=>e.remove(),250)}function pe(n,e,...a){let o=!!ie;te(!0);let v=t("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":n},t("div",{class:"grab"}),t("div",{class:"sheet-head"},t("div",{class:"stack"},t("h2",{},n),e?t("span",{class:"muted s"},e):null),t("button",{class:"icon-btn","aria-label":"Close",onclick:()=>te()},O("x"))),t("div",{class:"sheet-body"},...a)),p=t("div",{class:"sheet",onclick:_=>{_.target===p&&te()}},v);return document.body.appendChild(p),document.body.classList.add("locked"),o?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open")),ie=p,v}document.addEventListener("keydown",n=>{n.key==="Escape"&&(he(),te())});var X=null;function he(){X==null||X.remove(),X=null}document.addEventListener("click",n=>{X&&!X.contains(n.target)&&he()});function bt(n,e){he();let a=t("
Line truncated
|
||||
`).flatMap((p,_)=>_?[`
|
||||
`,Ve(p,e)]:[Ve(p,e)])),v=t("button",{class:"btn small",onclick:p=>{p.preventDefault(),e=!e,v.replaceChildren(O(e?"x":"key"),t("span",{},e?"Hide key":"Show key")),o()}},O("key"),t("span",{},"Show key"));return o(),t("div",{class:"pane"},t("div",{class:"filecard"},t("span",{class:"filecard-ic"},".conf"),t("span",{class:"stack"},t("span",{class:"mono ellipsis"},n.filename),t("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),t("button",{class:"btn primary",onclick:()=>je(n.filename,n.conf)},O("download"),t("span",{},"Download"))),t("details",{class:"confbox"},t("summary",{},O("chevron"),t("span",{},"Configuration"),t("span",{class:"grow"}),v,t("button",{class:"btn small",onclick:p=>{p.preventDefault(),ve(n.conf,"Configuration copied")}},O("copy"),t("span",{},"Copy"))),a))}async function fe(n,e,a){let o=a!=null?a:await Te(n);if(!o)return;let v=await xe(o,`${o.server} · ${o.name}`),p=ke(),_={app:()=>t("div",{class:"pane"},t("a",{class:"btn primary block big",href:v},O("open"),t("span",{},"Open in AmneziaVPN")),t("ol",{class:"steps"},t("li",{},"No AmneziaVPN yet? ",t("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),t("li",{},"Tap ",t("b",{},"Open in AmneziaVPN")," and confirm the import."),t("li",{},"Turn the connection on — this page shows ",t("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=t("div",{class:"qr"});return H.innerHTML=qe(o.conf),t("div",{class:"pane center"},H,t("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>t("div",{class:"pane"},t("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),t("div",{class:"keybox"},t("span",{class:"mono"},v),t("button",{class:"btn small",onclick:()=>ve(v,"Key copied")},"Copy")),t("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Et(o)},$=p?["app","qr","key","file"]:["qr","key","file"],B={app:"Open in app",qr:"QR code",key:"Key",file:"File"},D=t("div",{class:"tab-body"}),F=t("div",{class:"tabs",role:"tablist"}),J=H=>{F.querySelectorAll("button").forEach(ne=>ne.classList.toggle("on",ne.dataset.id===H)),D.replaceChildren(_[H]())};for(let H of $)F.appendChild(t("button",{role:"tab","data-id":H,onclick:()=>J(H)},B[H]));J(e&&$.includes(e)?e:$[0]);let U=t("div",{class:"waiting"}),N=H=>{H!=null&&H.online?U.replaceChildren(t("i",{class:"dot ok"}),t("span",{class:"ok"},`${n.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(t("i",{class:"dot"}),t("span",{class:"muted"},`Last connected ${ye(H.handshake)}`)):U.replaceChildren(t("i",{class:"dot warn pulse"}),t("span",{class:"muted"},"Waiting for the first connection…"))};N(n);let G=window.setInterval(async()=>{try{let H=await oe("state");R=H,N(H.person.devices.find(ne=>ne.id===n.id))}catch{}},5e3);pe(n.handshake?`Connect ${n.name}`:`${n.name} is ready`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",F,D,U),le=()=>{clearInterval(G),R&&ge(R)}}function Bt(n){let e=t("input",{type:"text",value:n.name,maxlength:48,"aria-label":"Device name"});pe(`Rename ${n.name}`,null,t("form",{class:"stack gap",onsubmit:async a=>{a.preventDefault();try{R=(await oe(`devices/${n.id}`,{action:"rename",name:e.value})).state,te(),ge(R),se("Renamed")}catch(o){se(o.message,!0)}}},e,t("button",{class:"btn primary block",type:"submit"},"Save"))),setTimeout(()=>e.select(),50)}function Dt(n){pe(`Remove ${n.name}?`,null,t("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),t("div",{class:"row gap"},t("button",{class:"btn block",onclick:()=>te()},"Cancel"),t("button",{class:"btn danger-solid block",onclick:async()=>{try{R=(await oe(`devices/${n.id}`,{action:"delete"})).state,te(),ge(R),se("Device removed")}catch(e){se(e.message,!0)}}},"Remove")))}var V=navigator.userAgent,Qe=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function Me(){return Qe||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var $t=[[/^SM-S93/,"Galaxy S25"],[/^SM-S92/,"Galaxy S24"],[/^SM-S91/,"Galaxy S23"],[/^SM-S90/,"Galaxy S22"],[/^SM-G99/,"Galaxy S21"],[/^SM-F9/,"Galaxy Z Fold"],[/^SM-F7/,"Galaxy Z Flip"],[/^SM-A5/,"Galaxy A5x"],[/^SM-A3/,"Galaxy A3x"],[/^SM-X/,"Galaxy Tab"]],_e="",Pt=(async()=>{var e;let n=navigator.userAgentData;if(!n||!/Android/.test(V))return"";try{let a=((e=(await n.getHighEntropyValues(["model"])).model)!=null?e:"").trim();if(!a||a==="K")return"";let o=$t.find(([v])=>v.test(a));_e=o?`${o[1]} (${a})`:/^SM-/.test(a)?`Galaxy ${a}`:a}catch{}return _e})();function St(n){return/iPhone/.test(V)?"iPhone":Qe?"iPad":/Android/.test(V)?_e||(n==="tablet"?"Android tablet":"Android phone"):/CrOS/.test(V)?"Chromebook":/Mac OS X/.test(V)?"Mac":/Windows/.test(V)?"Windows PC":/Linux/.test(V)?"Linux PC":ue[n]}function Rt(){if(!R)return;let n=Me(),e=new Set(R.person.devices.map(B=>B
Line truncated
|
||||
"use strict";(()=>{var Xi=Object.create;var Xo=Object.defineProperty;var Ji=Object.getOwnPropertyDescriptor;var Zi=Object.getOwnPropertyNames;var ea=Object.getPrototypeOf,ta=Object.prototype.hasOwnProperty;var na=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var oa=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Zi(t))!ta.call(e,r)&&r!==n&&Xo(e,r,{get:()=>t[r],enumerable:!(o=Ji(t,r))||o.enumerable});return e};var ra=(e,t,n)=>(n=e!=null?Xi(ea(e)):{},oa(t||!e||!e.__esModule?Xo(n,"default",{value:e,enumerable:!0}):n,e));var qr=na((Fr,Wr)=>{"use strict";var Gr=(function(){var e=function(g,v){var u=236,d=17,l=g,b=n[v],y=null,p=0,L=null,E=[],A={},F=function(S,H){p=l*4+17,y=(function(k){for(var D=new Array(k),$=0;$<k;$+=1){D[$]=new Array(k);for(var I=0;I<k;I+=1)D[$][I]=null}return D})(p),B(0,0),B(p-7,0),B(0,p-7),Y(),q(),te(S,H),l>=7&&Z(S),L==null&&(L=Be(l,b,E)),le(L,H)},B=function(S,H){for(var k=-1;k<=7;k+=1)if(!(S+k<=-1||p<=S+k))for(var D=-1;D<=7;D+=1)H+D<=-1||p<=H+D||(0<=k&&k<=6&&(D==0||D==6)||0<=D&&D<=6&&(k==0||k==6)||2<=k&&k<=4&&2<=D&&D<=4?y[S+k][H+D]=!0:y[S+k][H+D]=!1)},N=function(){for(var S=0,H=0,k=0;k<8;k+=1){F(!0,k);var D=r.getLostPoint(A);(k==0||S>D)&&(S=D,H=k)}return H},q=function(){for(var S=8;S<p-8;S+=1)y[S][6]==null&&(y[S][6]=S%2==0);for(var H=8;H<p-8;H+=1)y[6][H]==null&&(y[6][H]=H%2==0)},Y=function(){for(var S=r.getPatternPosition(l),H=0;H<S.length;H+=1)for(var k=0;k<S.length;k+=1){var D=S[H],$=S[k];if(y[D][$]==null)for(var I=-2;I<=2;I+=1)for(var G=-2;G<=2;G+=1)I==-2||I==2||G==-2||G==2||I==0&&G==0?y[D+I][$+G]=!0:y[D+I][$+G]=!1}},Z=function(S){for(var H=r.getBCHTypeNumber(l),k=0;k<18;k+=1){var D=!S&&(H>>k&1)==1;y[Math.floor(k/3)][k%3+p-8-3]=D}for(var k=0;k<18;k+=1){var D=!S&&(H>>k&1)==1;y[k%3+p-8-3][Math.floor(k/3)]=D}},te=function(S,H){for(var k=b<<3|H,D=r.getBCHTypeInfo(k),$=0;$<15;$+=1){var I=!S&&(D>>$&1)==1;$<6?y[$][8]=I:$<8?y[$+1][8]=I:y[p-15+$][8]=I}for(var $=0;$<15;$+=1){var I=!S&&(D>>$&1)==1;$<8?y[8][p-$-1]=I:$<9?y[8][15-$-1+1]=I:y[8][15-$-1]=I}y[p-8][8]=!S},le=function(S,H){for(var k=-1,D=p-1,$=7,I=0,G=r.getMaskFunction(H),W=p-1;W>0;W-=2)for(W==6&&(W-=1);;){for(var X=0;X<2;X+=1)if(y[D][W-X]==null){var oe=!1;I<S.length&&(oe=(S[I]>>>$&1)==1);var U=G(D,W-X);U&&(oe=!oe),y[D][W-X]=oe,$-=1,$==-1&&(I+=1,$=7)}if(D+=k,D<0||p<=D){D-=k,k=-k;break}}},me=function(S,H){for(var k=0,D=0,$=0,I=new Array(H.length),G=new Array(H.length),W=0;W<H.length;W+=1){var X=H[W].dataCount,oe=H[W].totalCount-X;D=Math.max(D,X),$=Math.max($,oe),I[W]=new Array(X);for(var U=0;U<I[W].length;U+=1)I[W][U]=255&S.getBuffer()[U+k];k+=X;var we=r.getErrorCorrectPolynomial(oe),ue=i(I[W],we.getLength()-1),Yo=ue.mod(we);G[W]=new Array(we.getLength()-1);for(var U=0;U<G[W].length;U+=1){var jo=U+Yo.getLength()-G[W].length;G[W][U]=jo>=0?Yo.getAt(jo):0}}for(var Qo=0,U=0;U<H.length;U+=1)Qo+=H[U].totalCount;for(var ao=new Array(Qo),fn=0,U=0;U<D;U+=1)for(var W=0;W<H.length;W+=1)U<I[W].length&&(ao[fn]=I[W][U],fn+=1);for(var U=0;U<$;U+=1)for(var W=0;W<H.length;W+=1)U<G[W].length&&(ao[fn]=G[W][U],fn+=1);return ao},Be=function(S,H,k){for(var D=c.getRSBlocks(S,H),$=f(),I=0;I<k.length;I+=1){var G=k[I];$.put(G.getMode(),4),$.put(G.getLength(),r.getLengthInBits(G.getMode(),S)),G.write($)}for(var W=0,I=0;I<D.length;I+=1)W+=D[I].dataCount;if($.getLengthInBits()>W*8)throw"code length overflow. ("+$.getLengthInBits()+">"+W*8+")";for($.getLengthInBits()+4<=W*8&&$.put(0,4);$.getLengthInBits()%8!=0;)$.putBit(!1);for(;!($.getLengthInBits()>=W*8||($.put(u,8),$.getLengthInBits()>=W*8));)$.put(d,8);return me($,D)};A.addData=function(S,H){H=H||"Byte";var k=null;switch(H){case"Numeric":k=m(S);break;case"Alphanumeric":k=M(S);break;case"Byte":k=h(S);break;case"Kanji":k=x(S);break;default:throw"mode:"+H}E.push(k),L=null},A.isDark=function(S,H){if(S<0||p<=S||H<0||p<=H)throw S+","+H;return y[S][H]},A.getModuleCount=function(){return p},A.make=function(){if(l<1){for(var S=1;S<40;S++){for(var H=c.getRSBlocks(S,b),k=f(),D=0;D<E.length;D++){var $=E[D];k.put($.getMode(),4),k.put($.getLength(),r.getLengthInBits($.getMode(),S)),$.write(k)}for(var I=0,D=0;D<H.length;D++)I+=H[D].dataCount;if(k.getLengthInBits()<=I*8)break}l=S}F(!1,N())},A.createTableTag=function(S,H){S=S||2,H=typeof H=="undefined"?S*4:H;var k="";k+='<table style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: "+H+"px;",k+='">',k+="<tbody>";for(var D=0;D<A.getModuleCount();D+=1){k+="<tr>";for(var $=0;$<A.getModuleCount();$+=1)k+='<td style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: 0px;",k+=" width: "+S+"px;",k+=" height: "+S+"px;",k+=" background-color: ",k+=A.isDark(D,$)?"#000000":"#ffffff",k+=";",k+='"/>';k+="</tr>"}return k+="</tbody>",k+="</table>",k},A.createSvgTag=function(S,H,k,D){var $={};typeof arguments[0]=="object"&&($=arguments[0],S=$.cellSize,H=$.margin,k=$.alt,D=$.title),S=S||2,H=typeof H=="undefined"?S*4:H,k=typeof k=="string"?{text:k}:k||{Line truncated
|
||||
`}return k%2&&S>0?ue.substring(0,ue.length-k-1)+Array(k+1).join("▀"):ue.substring(0,ue.length-1)};return A.createASCII=function(S,H){if(S=S||1,S<2)return Ie(H);S-=1,H=typeof H=="undefined"?S*2:H;var k=A.getModuleCount()*S+H*2,D=H,$=k-H,I,G,W,X,oe=Array(S+1).join("██"),U=Array(S+1).join(" "),we="",ue="";for(I=0;I<k;I+=1){for(W=Math.floor((I-D)/S),ue="",G=0;G<k;G+=1)X=1,D<=G&&G<$&&D<=I&&I<$&&A.isDark(W,Math.floor((G-D)/S))&&(X=0),ue+=X?oe:U;for(W=0;W<S;W+=1)we+=ue+`
|
||||
`}return we.substring(0,we.length-1)},A.renderTo2dContext=function(S,H){H=H||2;for(var k=A.getModuleCount(),D=0;D<k;D++)for(var $=0;$<k;$++)S.fillStyle=A.isDark(D,$)?"black":"white",S.fillRect(D*H,$*H,H,H)},A};e.stringToBytesFuncs={default:function(g){for(var v=[],u=0;u<g.length;u+=1){var d=g.charCodeAt(u);v.push(d&255)}return v}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(g,v){var u=(function(){for(var l=R(g),b=function(){var q=l.read();if(q==-1)throw"eof";return q},y=0,p={};;){var L=l.read();if(L==-1)break;var E=b(),A=b(),F=b(),B=String.fromCharCode(L<<8|E),N=A<<8|F;p[B]=N,y+=1}if(y!=v)throw y+" != "+v;return p})(),d=63;return function(l){for(var b=[],y=0;y<l.length;y+=1){var p=l.charCodeAt(y);if(p<128)b.push(p);else{var L=u[l.charAt(y)];typeof L=="number"?(L&255)==L?b.push(L):(b.push(L>>>8),b.push(L&255)):b.push(d)}}return b}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},o={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var g=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],v=1335,u=7973,d=21522,l={},b=function(y){for(var p=0;y!=0;)p+=1,y>>>=1;return p};return l.getBCHTypeInfo=function(y){for(var p=y<<10;b(p)-b(v)>=0;)p^=v<<b(p)-b(v);return(y<<10|p)^d},l.getBCHTypeNumber=function(y){for(var p=y<<12;b(p)-b(u)>=0;)p^=u<<b(p)-b(u);return y<<12|p},l.getPatternPosition=function(y){return g[y-1]},l.getMaskFunction=function(y){switch(y){case o.PATTERN000:return function(p,L){return(p+L)%2==0};case o.PATTERN001:return function(p,L){return p%2==0};case o.PATTERN010:return function(p,L){return L%3==0};case o.PATTERN011:return function(p,L){return(p+L)%3==0};case o.PATTERN100:return function(p,L){return(Math.floor(p/2)+Math.floor(L/3))%2==0};case o.PATTERN101:return function(p,L){return p*L%2+p*L%3==0};case o.PATTERN110:return function(p,L){return(p*L%2+p*L%3)%2==0};case o.PATTERN111:return function(p,L){return(p*L%3+(p+L)%2)%2==0};default:throw"bad maskPattern:"+y}},l.getErrorCorrectPolynomial=function(y){for(var p=i([1],0),L=0;L<y;L+=1)p=p.multiply(i([1,s.gexp(L)],0));return p},l.getLengthInBits=function(y,p){if(1<=p&&p<10)switch(y){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+y}else if(p<27)switch(y){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+y}else if(p<41)switch(y){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+y}else throw"type:"+p},l.getLostPoint=function(y){for(var p=y.getModuleCount(),L=0,E=0;E<p;E+=1)for(var A=0;A<p;A+=1){for(var F=0,B=y.isDark(E,A),N=-1;N<=1;N+=1)if(!(E+N<0||p<=E+N))for(var q=-1;q<=1;q+=1)A+q<0||p<=A+q||N==0&&q==0||B==y.isDark(E+N,A+q)&&(F+=1);F>5&&(L+=3+F-5)}for(var E=0;E<p-1;E+=1)for(var A=0;A<p-1;A+=1){var Y=0;y.isDark(E,A)&&(Y+=1),y.isDark(E+1,A)&&(Y+=1),y.isDark(E,A+1)&&(Y+=1),y.isDark(E+1,A+1)&&(Y+=1),(Y==0||Y==4)&&(L+=3)}for(var E=0;E<p;E+=1)for(var A=0;A<p-6;A+=1)y.isDark(E,A)&&!y.isDark(E,A+1)&&y.isDark(E,A+2)&&y.isDark(E,A+3)&&y.isDark(E,A+4)&&!y.isDark(E,A+5)&&y.isDark(E,A+6)&&(L+=40);for(var A=0;A<p;A+=1)for(var E=0;E<p-6;E+=1)y.isDark(E,A)&&!y.isDark(E+1,A)&&y.isDark(E+2,A)&&y.isDark(E+3,A)&&y.isDark(E+4,A)&&!y.isDark(E+5,A)&&y.isDark(E+6,A)&&(L+=40);for(var Z=0,A=0;A<p;A+=1)for(var E=0;E<p;E+=1)y.isDark(E,A)&&(Z+=1);var te=Math.abs(100*Z/p/p-50)/5;return L+=te*10,L},l})(),s=(function(){for(var g=new Array(256),v=new Array(256),u=0;u<8;u+=1)g[u]=1<<u;for(var u=8;u<256;u+=1)g[u]=g[u-4]^g[u-5]^g[u-6]^g[u-8];for(var u=0;u<255;u+=1)v[g[u]]=u;var d={};return d.glog=function(l){if(l<1)throw"glog("+l+")";return v[l]},d.gexp=function(l){for(;l<0;)l+=255;for(;l>=256;)l-=255;return g[l]},d})();function i(g,v){if(typeof g.length=="undefined")throw g.length+"/"+v;var u=(function(){for(var l=0;l<g.length&&g[l]==0;)l+=1;for(var b=new Array(g.length-l+v),y=0;y<g.length-l;y+=1)b[y]=g[y+l];return b})(),d={};return d.getAt=function(l){return u[l]},d.getLength=function(){return u.length},d.multiply=function(l){for(var b=new Array(d.getLength()+l.getLength()-1),y=0;y<d.getLength();y+=1)for(var p=0;p<l.getLength();p+=1)b[y+p]^=s.gexp(s.glog(d.getAt(y))+s.glog(l.getAt(p)));return i(b,0)},d.mod=function(l){if(d.ge
Line truncated
|
||||
`),hostName:s,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},c={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(i),port:String(n.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:s};return n.dns[0]&&(c.dns1=n.dns[0],c.dns2=n.dns[1]||n.dns[0]),c}function bc(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function xc(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let n=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),o=new Uint8Array(await new t.Response(n).arrayBuffer()),r=new Uint8Array(4+o.length);return new DataView(r.buffer).setUint32(0,e.length,!1),r.set(o,4),r}catch{return null}}async function Oo(e,t,n=!0){let o=new TextEncoder().encode(JSON.stringify(vc(e,t))),r=n?await xc(o):null;return`vpn://${bc(r!=null?r:o)}`}var Us=e=>e.replace(/^vpn:\/\//,"");var Ys=["height","marginTop","marginBottom","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],wc={opacity:0,filter:"blur(2px)"};function js(e,t,n){let o=e.getAnimations();O(e,t,n),o.forEach(r=>r.cancel())}var Mc=new Set(["offset","computedOffset","easing","composite"]),Ec=e=>e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`);function Gt(...e){let t=[],n=[],o=new Set;for(let s of e)for(let i=s;i&&!o.has(i);i=i.parentElement)if(o.add(i),!(!(i instanceof HTMLElement)||i.classList.contains("closing")))for(let c of i.getAnimations()){let f=c.playState==="running"&&c.effect instanceof KeyframeEffect?c.effect.getKeyframes():[],m=f[f.length-1];if(m&&("width"in m||"maxWidth"in m)&&n.push({a:c,t:c.currentTime}),!(m!=null&&m.height)||m.height==="0px")continue;let M=getComputedStyle(i),h={},x={};for(let w of Object.keys(m))Mc.has(w)||(h[w]=M.getPropertyValue(Ec(w)),x[w]=m[w]);t.push({el:i,a:c,t:c.currentTime,cur:h,to:x})}if(!t.length)return;[...t,...n].forEach(s=>s.a.cancel());let r=t.map(s=>getComputedStyle(s.el).height);for(let s of n)s.a.play(),s.a.currentTime=s.t;t.forEach((s,i)=>{s.a.play(),Math.abs(parseFloat(r[i])-parseFloat(String(s.to.height)))<.5?s.a.currentTime=s.t:s.a.effect.setKeyframes([s.cur,{...s.to,height:r[i]}])})}function ut(e,t={}){let n=a("div",{class:`acc${t.inset?" inset":""}`}),o=e.map((h,x)=>{var v;let w=h.body.filter(u=>!!u),C=!w.length,R=[h.icon,a("span",{class:"acc-title"},a("span",{class:"t"},h.title),(v=h.tag)!=null?v:null),h.val?a("span",{class:`acc-val${h.valHide?" hide-open":""}`},h.val):null],P=x===t.open&&!C,T=C?a("div",{class:"acc-head"},...R):a("button",{type:"button",class:"acc-head","aria-expanded":String(P),onclick:()=>M(g)},...R,V("chevron","i acc-chev")),g=a("div",{class:`acc-row${C?" still":""}${P?" open":""}${h.aside?" has-aside":""}`},T,h.aside?a("div",{class:"acc-aside"},h.aside):null,a("div",{class:"acc-body"},...w));return n.appendChild(g),g}),r=h=>h.querySelector(".acc-body"),s=()=>{let h=o.filter(x=>!x.hidden);h.forEach((x,w)=>{let C=x.classList.contains("open");x.classList.toggle("rt",w===0||C||h[w-1].classList.contains("open")),x.classList.toggle("rb",w===h.length-1||C||h[w+1].classList.contains("open"))}),o.forEach(x=>{x.classList.toggle("first",x===h[0]),x.classList.toggle("last",x===h[h.length-1])})},i=h=>{let x=getComputedStyle(h),w={};for(let C of Ys)w[C]=C==="height"?`${h.getBoundingClientRect().height}px`:x[C];return w},c=()=>o.forEach(h=>{var x;return(x=h.querySelector("button.acc-head"))==null?void 0:x.setAttribute("aria-expanded",String(h.classList.contains("open")))}),f=h=>h.classList.contains("open")||h.classList.contains("closing"),m=h=>{if(!f(h))return wc;let x=getComputedStyle(r(h));return{opacity:x.opacity,filter:x.filter==="none"?"blur(0px)":x.filter}};function M(h){var v,u;let x=o.map(i),w=o.map(m),C=(v=t.hold)==null?void 0:v.call(t);o.forEach(d=>d.getAnimations().forEach(l=>l.cancel()));let R=!h.classList.contains("open"),P=o.filter(d=>f(d)&&!(d===h&&R));o.forEach(d=>{d.classList.remove("closing"),d!==h&&d.classList.remove("open")}),h.classList.toggle("open",R),R&&h.classList.add("opened"),s();let T=Ot(),g=o.map(i);if(C==null||C(),Gt(n.parentElement),o.forEach((d,l)=>{let b=()=>{d.classList.remove("closing"),d.classList.contains("open")||d.classList.remove("opened")};if(!Ys.some(y=>x[l][y]!==g[l][y]))return b();P.includes(d)&&d.classList.add("closing"),O(d,[x[l],g[l]],{duration:he.duration,easing:he.easing}).onfinish=b}),P.forEach(d=>{let l=w[o.indexOf(d)];js(r(d),[l,{opacity:0,filter:"blur(2px)"}],{duration:160*Number(l.opacity),easing:J,fill:"forwards"})}),R){let d=w[o.indexOf(h)];js(r(h),[d,{opacity:1,filter:"blur(0px)"}],{duration:300*(1-Number(d.opacity)),easing:"cubic-bezier(0,0,.58,1)"})}Rt(T),c(),(u=t.onToggle)==null||u.call(t,o.indexOf(h),R,!1)}return s(),{el:n,openInde
Line truncated
|
||||
`).flatMap((h,x)=>x?[`
|
||||
`,ei(h)]:[ei(h)])),o=!!at(e.filename,e.conf),r=V("key"),s=V("x"),i=a("span",{},_("Show key")),c=a("button",{type:"button",class:"btn soft sm",onclick:()=>{t=!t,ee(i,t?_("Hide key"):_("Show key")),n.querySelectorAll(".secret").forEach(h=>Xn(h,t,Js)),n.querySelectorAll(".mask").forEach(h=>Xn(h,!t,Js)),Xn(r,!t,Zs),Xn(s,t,Zs)}},ci(r,s),i),f=a("button",{type:"button",class:"btn soft sm",onclick:h=>ve(e.conf,_("Configuration copied"),h.currentTarget)},V("copy"),a("span",{class:"lbl"},_("Copy"))),m=a("div",{class:"filecard"},a("div",{class:"fc-row"},a("span",{class:"filecard-ic"},".conf"),a("span",{class:"t"},a("span",{class:"mono"},e.filename),a("span",{},_("For computers and routers")))),a("button",{type:"button",class:"btn accent sm block",onclick:()=>Xt(e.filename,e.conf)},V(o?"open":"download"),a("span",{},o?_("Share file"):_("Download")))),M=ut([{icon:ne("file"),title:_("Configuration"),body:[a("div",{class:"confbar"},c,f),n]}],{inset:!0});return a("div",{class:"step-box"},m,M.el)}function di(e){let t=a("span",{class:"osm-p"},Ee[e]),n=ds(Kt(e,"ios"),Kt(e,"android"));return{el:a("span",{class:"scanline"},a("span",{},...ht(_("In %s:"),t)),n.el),set(o){ee(t,Ee[o],void 0,{whole:!0}),n.set(Kt(o,"ios"),Kt(o,"android"))}}}function ui(e){let t=a("span",{class:"tt"}),n=a("span",{class:"tt-m"}),o=a("span",{class:"hp-tip","aria-hidden":"true"},t,n),r=a("button",{type:"button",class:"hp-b",onclick:()=>Xt(e().file,e().text)},V("download")),s=a("button",{type:"button",class:"hp-b"},V("copy")),i=a("div",{class:"hpill",role:"group","aria-label":_("The connection"),"data-key":"conn"},r,s,o),c=null,f=0,m=0,M=l=>{var b;return l===s&&s.classList.contains("done")?_("Copied"):(b=l.getAttribute("aria-label"))!=null?b:""},h=(l,b)=>{n.textContent=b;let y=n.offsetWidth+20;return Math.min(l.offsetLeft+l.offsetWidth/2,i.offsetWidth+30-y/2)},x=l=>`translateX(${l}px) translateX(-50%)`,w=()=>{let l=getComputedStyle(o);return{opacity:l.opacity,filter:l.filter==="none"?"blur(0px)":l.filter,transform:l.transform}},C=(l,b)=>{let y=o.getAnimations();O(o,l,b),y.forEach(p=>p.cancel())},R=l=>{let b=w();o.style.transform=x(l),C([b,{opacity:1,filter:"blur(0px)",transform:x(l)}],{duration:K.duration,easing:K.easing})},P=l=>ee(t,l),T=l=>{if(clearTimeout(f),c===l&&o.classList.contains("on"))return;if(c=l,o.classList.contains("on")||+getComputedStyle(o).opacity>0){let y=M(l);return o.classList.add("on"),R(h(l,y)),P(y)}let b=()=>{let y=M(l);se(t,y);let p=h(l,y);o.style.transform=x(p),o.classList.add("on"),C([{opacity:0,transform:`${x(p)} translateY(-3px) scale(.96)`,filter:"blur(3px)"},{opacity:1,transform:x(p),filter:"blur(0px)"}],{duration:220,easing:Q})};performance.now()<m?b():f=window.setTimeout(b,420)},g=()=>{if(clearTimeout(f),c=null,!o.classList.contains("on"))return;m=performance.now()+500;let l=w();o.classList.remove("on"),C([l,{...l,opacity:0}],{duration:120,easing:"ease-out"})};for(let l of[r,s])l.addEventListener("pointerenter",b=>{b.pointerType==="mouse"&&T(l)}),l.addEventListener("focus",()=>{l.matches(":focus-visible")&&T(l)}),l.addEventListener("blur",b=>{i.contains(b.relatedTarget)||g()});i.addEventListener("pointerleave",g);let v=l=>{let b=V(l);s.querySelector("svg").replaceWith(b),O(b,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:Fe.duration,easing:Fe.easing})},u=()=>{if(c!==s||!o.classList.contains("on"))return;let l=M(s);R(h(s,l)),P(l)},d=0;return s.addEventListener("click",()=>{let l=e();ve(l.text,l.msg),clearTimeout(d),s.classList.contains("done")||(s.classList.add("done"),v("check"),u()),d=window.setTimeout(()=>{s.classList.remove("done"),v("copy"),u()},1600)}),{el:i,sync(){let l=e().app;r.setAttribute("aria-label",z(_("Download %s config"),l)),s.setAttribute("aria-label",z(_("Copy %s config"),l))}}}function pi(e,t){var n,o,r;return e?((n=e.setup)==null?void 0:n.state)==="trying"?"trying":e.handshake<=t?"waiting":((o=e.setup)==null?void 0:o.state)==="flowing"?"connected":((r=e.setup)==null?void 0:r.state)==="nodata"?"nodata":"waiting":"waiting"}function Tc(e,t){switch(e){case"trying":return[_("Unable to complete the handshake"),_("Your network may be blocking the connection.")];case"connected":return[z(_("%s connected"),t.name),""];case"nodata":return[_("Handshake complete, but no data"),_("The router drops its traffic: the address does not match.")];case"waiting":return[_("Waiting for the connection"),""]}}var fi={waiting:"",trying:"trying",connected:"done",nodata:"nodata"};function hi(e){let t=a("b",{},_("Waiting for the connection")),n=a("span",{class:"ws",hidden:!0}),o=a("span",{class:"t"},t,n),r=a("div",{class:"way-text"},o),s=a("span",{class:"way-track"},a("span",{class:"way-glow"},a("span",{class:"run"},a("i")),a("span",{class:"knock"},a("i"))),a("span",{class:"way-fill"}),a("span",{class:"way-break"},a("i"))),i=a("div",{class:"way",role:"status","aria-live":"polite"},a("div",{class:"way-row"},a("span",{class:"way-end"},V(e.kind)),s,a("span",{class:"way-end ho
Line truncated
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/ucode
|
||||
// Dawnline personal portal as a CGI script: the request handling itself is
|
||||
// dawnline.portal. www/cgi-bin/portal (a shell) runs it for requests shaped
|
||||
// like a personal link and answers the rest itself.
|
||||
'use strict';
|
||||
|
||||
import { stdin } from 'fs';
|
||||
import { serve } from 'dawnline.portal';
|
||||
|
||||
let env = {};
|
||||
for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE',
|
||||
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE',
|
||||
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
|
||||
'HTTP_CF_CONNECTING_IP' ])
|
||||
env[k] = getenv(k);
|
||||
|
||||
serve({
|
||||
env,
|
||||
headers: {},
|
||||
read: (n) => stdin.read(n),
|
||||
write: (s) => print(s),
|
||||
});
|
||||
@@ -1,344 +1,51 @@
|
||||
#!/usr/bin/ucode
|
||||
// Dawnline personal portal (CGI behind a dedicated uhttpd instance).
|
||||
//
|
||||
// GET /<code> the app shell (<code> = three words, the personal link)
|
||||
// GET /<code>/assets/<file> its script, styles, fonts
|
||||
// GET /<code>/api/state
|
||||
// POST /<code>/api/devices { name, kind, public_key? }
|
||||
// GET /<code>/api/devices/<id>/config
|
||||
// POST /<code>/api/devices/<id> { action: rename|delete, name? }
|
||||
//
|
||||
// The personal link is the key: every request carries its code, there are
|
||||
// no sessions. Without a valid code every path answers the same bare 404 —
|
||||
// the root, a person's link, the API and the assets alike — so nothing tells
|
||||
// a scanner there is a portal here. Wrong codes are rate-limited per IP
|
||||
// (blocked addresses get the same 404 even with the right code).
|
||||
// Regenerating the code in LuCI locks the old link out at once. POST bodies
|
||||
// must be JSON from the same origin; Referrer-Policy keeps the code out of
|
||||
// other sites' logs.
|
||||
//
|
||||
// The portal can only manage the person's own devices within their limit.
|
||||
'use strict';
|
||||
#!/bin/sh
|
||||
# Dawnline personal portal, the door: uhttpd runs this for every request.
|
||||
# Anything that is not shaped like a personal link (/<word-code>[/…]) gets
|
||||
# the portal's bare answer from here, in a shell that costs nothing, so a
|
||||
# scanner or a flood on the root never starts ucode (compiling the portal's
|
||||
# module graph is ~140 ms of CPU). Links go on to the portal itself
|
||||
# (/usr/share/dawnline/portal/cgi.uc), which judges the code.
|
||||
#
|
||||
# The answer here is byte for byte the portal's own not_found(): keep both
|
||||
# in step (dawnline.portal headers(), SECURITY_HEADERS, not_found()).
|
||||
|
||||
import { stdin, stat, unlink, readfile } from 'fs';
|
||||
import {
|
||||
read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, VERSION, RUN_DIR, DATA_DIR
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as view from 'dawnline.view';
|
||||
path="${REQUEST_URI%%\?*}"
|
||||
w='[a-z][a-z][a-z][a-z][a-z][a-z]'
|
||||
# The expansion is meant as a pattern (a word of six letters), not literally.
|
||||
# shellcheck disable=SC2254
|
||||
case "$path" in
|
||||
/$w-$w-$w|/$w-$w-$w/*) exec /usr/bin/ucode /usr/share/dawnline/portal/cgi.uc ;;
|
||||
esac
|
||||
|
||||
const RATE = `${RUN_DIR}/portal-rate.json`;
|
||||
const ASSETS = '/usr/share/dawnline/portal/assets';
|
||||
const TYPES = { js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml', woff2: 'font/woff2' };
|
||||
const FAIL_LIMIT = 8;
|
||||
const FAIL_WINDOW = 900;
|
||||
# HSTS pins the whole name: only when the visitor is on the standard port.
|
||||
hsts=
|
||||
if [ "$HTTPS" = on ]; then
|
||||
port="${HTTP_HOST##*:}"
|
||||
case "$HTTP_HOST" in *:*) ;; *) port=443 ;; esac
|
||||
case "$HTTP_HOST" in *\]) port=443 ;; esac
|
||||
[ "$port" = 443 ] && hsts=1
|
||||
fi
|
||||
|
||||
const SECURITY_HEADERS = {
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
'X-Frame-Options': 'DENY',
|
||||
'Cache-Control': 'no-store',
|
||||
'Strict-Transport-Security': 'max-age=31536000',
|
||||
};
|
||||
# Files always get the 404: a missing asset must not turn into someone's website.
|
||||
file=
|
||||
case "$path" in
|
||||
/luci-static|/luci-static/*|/cgi-bin|/cgi-bin/*|/ubus|/ubus/*) file=1 ;;
|
||||
*) case "${path##*/}" in *.*) file=1 ;; esac ;;
|
||||
esac
|
||||
redirect=
|
||||
[ -n "$file" ] || redirect="$(uci -q get dawnline.settings.portal_redirect)"
|
||||
|
||||
function headers(status, extra) {
|
||||
let h = `Status: ${status}\r\n`;
|
||||
for (let k, v in { ...SECURITY_HEADERS, ...(extra ?? {}) })
|
||||
h += `${k}: ${v}\r\n`;
|
||||
print(h + '\r\n');
|
||||
}
|
||||
|
||||
function send_json(status, obj, extra) {
|
||||
headers(status, { 'Content-Type': 'application/json', ...(extra ?? {}) });
|
||||
print(sprintf('%J', obj));
|
||||
exit(0);
|
||||
}
|
||||
|
||||
function fail(status, msg) {
|
||||
send_json(status, { error: msg });
|
||||
}
|
||||
|
||||
function html_escape(s) {
|
||||
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
||||
}
|
||||
|
||||
function page(status, base, title, code) {
|
||||
// The build's time joins the version so every update busts the hour-long asset cache.
|
||||
let q = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
|
||||
headers(status, {
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
|
||||
"connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
|
||||
});
|
||||
print(`<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>${html_escape(title)}</title>
|
||||
<link rel="icon" href="${base}/assets/icon.svg${q}" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="${base}/assets/portal.css${q}">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" data-base="${html_escape(base ?? '')}" data-title="${html_escape(title)}"></div>
|
||||
<script src="${base}/assets/portal.js${q}" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
`);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/* ---------- request ---------- */
|
||||
|
||||
const method = getenv('REQUEST_METHOD') ?? 'GET';
|
||||
const uri = getenv('REQUEST_URI') ?? '/';
|
||||
// Behind a Cloudflare-proxied hostname every request comes from Cloudflare,
|
||||
// and uhttpd does not hand CF-Connecting-IP to CGI: all those visitors share
|
||||
// one bucket with a higher limit (three-word codes can't be guessed anyway).
|
||||
const peer = getenv('REMOTE_ADDR') ?? '';
|
||||
const via_cf = cloudflare_ip(peer);
|
||||
const ip = via_cf ? 'cloudflare' : peer;
|
||||
const fail_limit = via_cf ? FAIL_LIMIT * 25 : FAIL_LIMIT;
|
||||
const qpos = index(uri, '?');
|
||||
const path = qpos >= 0 ? substr(uri, 0, qpos) : uri;
|
||||
const query = qpos >= 0 ? substr(uri, qpos + 1) : '';
|
||||
const segs = filter(split(path, '/'), (s) => s != '');
|
||||
|
||||
function query_param(name) {
|
||||
for (let kv in split(query, '&')) {
|
||||
let eq = index(kv, '=');
|
||||
if (eq > 0 && substr(kv, 0, eq) == name)
|
||||
return substr(kv, eq + 1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function body() {
|
||||
let len = +(getenv('CONTENT_LENGTH') ?? 0);
|
||||
if (len <= 0)
|
||||
return {};
|
||||
if (len > 8192)
|
||||
fail('413 Payload Too Large', 'Request too large.');
|
||||
let raw = stdin.read(len);
|
||||
try {
|
||||
let j = json(raw);
|
||||
return type(j) == 'object' ? j : {};
|
||||
}
|
||||
catch (e) {
|
||||
fail('400 Bad Request', 'Invalid JSON.');
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- rate limiting ---------- */
|
||||
|
||||
function rate_state() {
|
||||
let st = read_json(RATE, {});
|
||||
let now = time();
|
||||
for (let k, v in st)
|
||||
if (now - v.first > FAIL_WINDOW)
|
||||
delete st[k];
|
||||
return st;
|
||||
}
|
||||
|
||||
function rate_blocked() {
|
||||
let v = rate_state()[ip];
|
||||
return v != null && v.count >= fail_limit;
|
||||
}
|
||||
|
||||
function rate_fail() {
|
||||
let l = lock('portal-rate');
|
||||
let st = rate_state();
|
||||
let v = st[ip] ?? { first: time(), count: 0 };
|
||||
v.count++;
|
||||
st[ip] = v;
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(RATE, st, 0o600);
|
||||
unlock(l);
|
||||
if (v.count == fail_limit)
|
||||
live.add_event({ type: 'portal_blocked', detail: ip });
|
||||
}
|
||||
|
||||
// Older versions kept sign-in sessions on flash; they mean nothing now.
|
||||
if (stat(`${DATA_DIR}/sessions.json`))
|
||||
unlink(`${DATA_DIR}/sessions.json`);
|
||||
|
||||
/* ---------- routing ---------- */
|
||||
|
||||
let m = core.load();
|
||||
const redirect = m.settings.portal_redirect;
|
||||
|
||||
/**
|
||||
* The one answer for anything without a valid code: a bare 404, or the redirect from Settings.
|
||||
* Files and LuCI's own paths always get the 404: at home this script is LuCI's error page, and a
|
||||
* missing script must not turn into someone's website.
|
||||
*/
|
||||
function not_found() {
|
||||
let parts = split(split(uri, '?')[0], '/');
|
||||
let file = match(uri, /^\/(luci-static|cgi-bin|ubus)(\/|$)/) || match(parts[length(parts) - 1], /\./);
|
||||
if (redirect && !file) {
|
||||
headers('302 Found', { 'Location': redirect, 'Cache-Control': 'no-store', 'Content-Type': 'text/plain' });
|
||||
print('Moved\n');
|
||||
}
|
||||
else {
|
||||
headers('404 Not Found', { 'Content-Type': 'text/plain' });
|
||||
print('Not found\n');
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
|
||||
const title = m.settings.portal_title || 'Dawnline';
|
||||
// Plain HTTP only for an IP address chosen in Settings (no certificate exists
|
||||
// for it); names, and LuCI's web server at home, stay HTTPS-only.
|
||||
if (getenv('HTTPS') != 'on') {
|
||||
let h = getenv('HTTP_HOST') ?? '';
|
||||
h = match(h, /^\[/) ? h : split(h, ':')[0];
|
||||
if (ip2int(h) == null || index(core.portal_hosts(m), h) < 0)
|
||||
not_found();
|
||||
}
|
||||
// The link is /<word-code>[/assets/…|/api/…]: the code is the address.
|
||||
if (length(segs) < 1 || !match(segs[0], core.WORD_CODE))
|
||||
not_found();
|
||||
const code = segs[0];
|
||||
const base = `/${code}`;
|
||||
const rest = slice(segs, 1);
|
||||
let person = null;
|
||||
for (let id, p in m.people)
|
||||
if (p.code == code)
|
||||
person = p;
|
||||
|
||||
// A wrong code or a blocked address: indistinguishable from a path that does
|
||||
// not exist. Only well-formed guesses count towards the limit.
|
||||
if (rate_blocked())
|
||||
not_found();
|
||||
if (person == null) {
|
||||
rate_fail();
|
||||
not_found();
|
||||
}
|
||||
|
||||
const person_id = person.id;
|
||||
|
||||
// The app shell; it reads the code from its own URL and sends it along.
|
||||
if (length(rest) == 0 && method == 'GET')
|
||||
page('200 OK', base, title, code);
|
||||
|
||||
// Script, styles, icon and fonts (kept outside the web root).
|
||||
if (rest[0] == 'assets' && length(rest) == 2 && method == 'GET') {
|
||||
let name = rest[1];
|
||||
let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2)$/)?.[1];
|
||||
let data = ext ? readfile(`${ASSETS}/${name}`) : null;
|
||||
if (data == null)
|
||||
not_found();
|
||||
headers('200 OK', { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=3600' });
|
||||
print(data);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
if (rest[0] != 'api')
|
||||
not_found();
|
||||
|
||||
// CSRF: only same-origin JSON requests (uhttpd passes no custom headers to
|
||||
// CGI; a cross-site page cannot send application/json without CORS, and it
|
||||
// would need the code anyway).
|
||||
if (method == 'POST') {
|
||||
let origin = getenv('HTTP_ORIGIN');
|
||||
if (!match(getenv('CONTENT_TYPE') ?? '', /^application\/json/) ||
|
||||
(origin != null && origin != `${getenv('HTTPS') == 'on' ? 'https' : 'http'}://${getenv('HTTP_HOST')}`))
|
||||
fail('403 Forbidden', 'Cross-site request refused.');
|
||||
}
|
||||
else if (method != 'GET')
|
||||
fail('405 Method Not Allowed', 'Method not allowed.');
|
||||
|
||||
const api = slice(rest, 1);
|
||||
|
||||
function state() {
|
||||
let usage = core.load_usage();
|
||||
let dmp = live.dump();
|
||||
let v = view.person_view(m, person, usage, dmp, view.states(m, usage));
|
||||
let srv = m.servers[person.server];
|
||||
return {
|
||||
title,
|
||||
person: v,
|
||||
server: { name: srv?.name, endpoint: core.endpoint_host(m, srv) },
|
||||
can_add: length(person.devices) < person.device_limit,
|
||||
kinds: core.KINDS,
|
||||
version: VERSION,
|
||||
};
|
||||
}
|
||||
|
||||
function own_device(id) {
|
||||
let d = m.devices[id];
|
||||
if (!d || d.person != person.id)
|
||||
fail('404 Not Found', 'Device not found.');
|
||||
return d;
|
||||
}
|
||||
|
||||
if (api[0] == 'state' && method == 'GET')
|
||||
send_json('200 OK', state());
|
||||
|
||||
if (api[0] == 'devices' && length(api) == 1 && method == 'POST') {
|
||||
let b = body();
|
||||
let l = lock('config');
|
||||
let id;
|
||||
try {
|
||||
let c = core.open_cursor();
|
||||
m = core.load(c);
|
||||
person = m.people[person_id];
|
||||
id = core.create_device(c, m, person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key || null });
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
}
|
||||
catch (e) {
|
||||
unlock(l);
|
||||
fail('400 Bad Request', e.message);
|
||||
}
|
||||
unlock(l);
|
||||
apply.sync();
|
||||
m = core.load();
|
||||
person = m.people[person_id];
|
||||
live.add_event({ type: 'device_added', person: person.id, device: id, detail: `${m.devices[id].name} (portal)` });
|
||||
core.mark_issued(m, id);
|
||||
send_json('200 OK', { id, config: core.client_config(m, m.devices[id]), state: state() });
|
||||
}
|
||||
|
||||
if (api[0] == 'devices' && length(api) == 3 && api[2] == 'config' && method == 'GET') {
|
||||
let d = own_device(api[1]);
|
||||
core.mark_issued(m, d.id);
|
||||
send_json('200 OK', core.client_config(m, d));
|
||||
}
|
||||
|
||||
if (api[0] == 'devices' && length(api) == 2 && method == 'POST') {
|
||||
own_device(api[1]);
|
||||
let b = body();
|
||||
let l = lock('config');
|
||||
try {
|
||||
let c = core.open_cursor();
|
||||
m = core.load(c);
|
||||
if (b.action == 'rename')
|
||||
core.rename_device(c, m, api[1], b.name);
|
||||
else if (b.action == 'delete') {
|
||||
let d = m.devices[api[1]];
|
||||
core.delete_device(c, m, api[1]);
|
||||
live.add_event({ type: 'device_removed', person: person.id, device: api[1], detail: `${d.name} (portal)` });
|
||||
}
|
||||
else
|
||||
die('Unknown action.');
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
}
|
||||
catch (e) {
|
||||
unlock(l);
|
||||
fail('400 Bad Request', e.message);
|
||||
}
|
||||
unlock(l);
|
||||
if (b.action == 'delete')
|
||||
apply.sync();
|
||||
m = core.load();
|
||||
person = m.people[person_id];
|
||||
send_json('200 OK', { ok: true, state: state() });
|
||||
}
|
||||
|
||||
fail('404 Not Found', 'Not found.');
|
||||
if [ -n "$redirect" ]; then
|
||||
printf 'Status: 302 Found\r\n'
|
||||
printf 'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\nCache-Control: no-store\r\n'
|
||||
printf 'Location: %s\r\nContent-Type: text/plain\r\n' "$redirect"
|
||||
[ -n "$hsts" ] && printf 'Strict-Transport-Security: max-age=31536000\r\n'
|
||||
printf '\r\nMoved\n'
|
||||
else
|
||||
printf 'Status: 404 Not Found\r\n'
|
||||
printf 'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\nCache-Control: no-store\r\n'
|
||||
printf 'Content-Type: text/plain\r\n'
|
||||
[ -n "$hsts" ] && printf 'Strict-Transport-Security: max-age=31536000\r\n'
|
||||
printf '\r\nNot found\n'
|
||||
fi
|
||||
exit 0
|
||||
@@ -28,8 +28,6 @@
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/activity": {
|
||||
"title": "Activity",
|
||||
"order": 25,
|
||||
"action": {
|
||||
"type": "view",
|
||||
"path": "dawnline/activity"
|
||||
@@ -49,9 +47,15 @@
|
||||
"path": "dawnline/server"
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/health": {
|
||||
"title": "Health",
|
||||
"admin/network/dawnline/diagnostics": {
|
||||
"title": "Diagnostics",
|
||||
"order": 40,
|
||||
"action": {
|
||||
"type": "view",
|
||||
"path": "dawnline/diagnostics"
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/health": {
|
||||
"action": {
|
||||
"type": "view",
|
||||
"path": "dawnline/health"
|
||||
@@ -66,7 +70,7 @@
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/updates": {
|
||||
"title": "Updates",
|
||||
"title": "Components",
|
||||
"order": 70,
|
||||
"action": {
|
||||
"type": "view",
|
||||
|
||||
@@ -4,32 +4,33 @@
|
||||
"read": {
|
||||
"ubus": {
|
||||
"luci.dawnline": [
|
||||
"rev",
|
||||
"status",
|
||||
"meter",
|
||||
"setup_defaults",
|
||||
"health",
|
||||
"service_log",
|
||||
"backup_list",
|
||||
"updates_status",
|
||||
"updates_releases",
|
||||
"updates_notes",
|
||||
"updates_changes",
|
||||
"person_usage",
|
||||
"settings_get",
|
||||
"portal_info",
|
||||
"interfaces",
|
||||
"server_ports",
|
||||
"endpoint_probe",
|
||||
"events"
|
||||
]
|
||||
},
|
||||
"uci": [
|
||||
"dawnline",
|
||||
"network",
|
||||
"firewall"
|
||||
]
|
||||
}
|
||||
},
|
||||
"write": {
|
||||
"ubus": {
|
||||
"luci.dawnline": [
|
||||
"*"
|
||||
]
|
||||
},
|
||||
"uci": [
|
||||
"dawnline"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
// Dawnline: "Check access" — walks the same rules the nft table and the
|
||||
// client configuration apply, and says in words where a connection stops
|
||||
// (in the admin's language: each step is a whole sentence).
|
||||
|
||||
'use strict';
|
||||
|
||||
import { ip2int, in_nets } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as view from 'dawnline.view';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
/** "Bob can't connect: they are paused", by the person's state (core.person_state). */
|
||||
function cant_connect(name, st) {
|
||||
if (st == 'no_server')
|
||||
return sprintf(_("%s can't connect: they have no server"), name);
|
||||
if (st == 'server_off')
|
||||
return sprintf(_("%s can't connect: their server is turned off"), name);
|
||||
if (st == 'paused')
|
||||
return sprintf(_("%s can't connect: they are paused"), name);
|
||||
if (st == 'expired')
|
||||
return sprintf(_("%s can't connect: their access has ended"), name);
|
||||
if (st == 'quota')
|
||||
return sprintf(_("%s can't connect: they used up their data"), name);
|
||||
if (st == 'hours')
|
||||
return sprintf(_("%s can't connect: it is outside their allowed hours"), name);
|
||||
return sprintf(_("%s can't connect: %s"), name, st);
|
||||
}
|
||||
|
||||
/** "Bob · Phone can't be reached: it is turned off", by the device and its person's state. */
|
||||
function cant_reach(who, disabled, st) {
|
||||
if (disabled)
|
||||
return sprintf(_("%s can't be reached: it is turned off"), who);
|
||||
if (st == 'no_server')
|
||||
return sprintf(_("%s can't be reached: they have no server"), who);
|
||||
if (st == 'server_off')
|
||||
return sprintf(_("%s can't be reached: their server is turned off"), who);
|
||||
if (st == 'paused')
|
||||
return sprintf(_("%s can't be reached: they are paused"), who);
|
||||
if (st == 'expired')
|
||||
return sprintf(_("%s can't be reached: their access has ended"), who);
|
||||
if (st == 'quota')
|
||||
return sprintf(_("%s can't be reached: they used up their data"), who);
|
||||
if (st == 'hours')
|
||||
return sprintf(_("%s can't be reached: it is outside their allowed hours"), who);
|
||||
return sprintf(_("%s can't be reached: %s"), who, st);
|
||||
}
|
||||
|
||||
/** A person's access as the admin page names it. */
|
||||
function access_text(a) {
|
||||
if (a == 'lan')
|
||||
return _('Home only');
|
||||
if (a == 'internet')
|
||||
return _('Internet only');
|
||||
if (a == 'both')
|
||||
return _('Home and Internet');
|
||||
return a;
|
||||
}
|
||||
|
||||
/** "Bob has Internet only": the step where access stops a connection. */
|
||||
function has_access(name, a) {
|
||||
if (a == 'lan')
|
||||
return sprintf(_('%s has Home only'), name);
|
||||
if (a == 'internet')
|
||||
return sprintf(_('%s has Internet only'), name);
|
||||
return sprintf(_('%s has Home and Internet'), name);
|
||||
}
|
||||
|
||||
/** "Bob reaches lan, guest." (the person's home networks), or that there is none. */
|
||||
function reaches(name, devs) {
|
||||
return length(devs) ? sprintf(_('%s reaches %s.'), name, join(', ', devs)) : sprintf(_('%s reaches no home network.'), name);
|
||||
}
|
||||
|
||||
function step(ok, title, detail) {
|
||||
return { ok: !!ok, title, detail: detail ?? '' };
|
||||
}
|
||||
|
||||
/** Add the step where it stops and end the walk. */
|
||||
function stop(steps, s) {
|
||||
push(steps, s);
|
||||
return steps;
|
||||
}
|
||||
|
||||
/** The tunnel subnet (of any server) that holds `ip`: never home, whatever routes cover it. */
|
||||
function in_tunnels(m, ip) {
|
||||
let nets = [];
|
||||
for (let id, s in m.servers)
|
||||
for (let t in core.tunnels(s))
|
||||
push(nets, t.subnet);
|
||||
return in_nets(ip, nets);
|
||||
}
|
||||
|
||||
/** "10.0.1.20:445" → [ip, port]; a device id → its address. */
|
||||
function parse_target(m, s) {
|
||||
s = trim(`${s ?? ''}`);
|
||||
if (m.devices[s])
|
||||
return { dev: m.devices[s], ip: m.devices[s].address, port: null };
|
||||
let mm = match(s, /^([0-9.]+)(:([0-9]{1,5}))?$/);
|
||||
if (!mm || ip2int(mm[1]) == null)
|
||||
return null;
|
||||
let ip = mm[1];
|
||||
for (let id, d in m.devices)
|
||||
if (d.address == ip)
|
||||
return { dev: d, ip, port: mm[3] ? +mm[3] : null };
|
||||
return { ip, port: mm[3] ? +mm[3] : null };
|
||||
}
|
||||
|
||||
function home_access(p) {
|
||||
return p.access == 'both' || (p.access == 'lan' && !length(p.services));
|
||||
}
|
||||
|
||||
function peer_of(dmp, d) {
|
||||
return dmp.peers[d.public_key];
|
||||
}
|
||||
|
||||
/** What the device sends to the router: its configuration's AllowedIPs (its own, with lan_bypass). */
|
||||
function routed(m, srv, p, d) {
|
||||
return awg.allowed_ips(m, srv, p, d);
|
||||
}
|
||||
|
||||
/** The home network (interface) of a server that holds an address. */
|
||||
function home_dev_of(srv, ip, snap) {
|
||||
for (let h in net.server_net(srv, snap).home)
|
||||
if (in_nets(ip, h.nets))
|
||||
return h.dev;
|
||||
return null;
|
||||
}
|
||||
|
||||
function router_addrs(snap) {
|
||||
let out = [];
|
||||
for (let dev, d in snap.devices)
|
||||
for (let a in d.addrs ?? [])
|
||||
push(out, split(a, '/')[0]);
|
||||
return out;
|
||||
}
|
||||
|
||||
function person_ok(m, p, d, states) {
|
||||
let st = states[p.id] ?? 'active';
|
||||
if (d.disabled)
|
||||
return step(false, sprintf(_('%s is turned off'), d.name), _('Turn the device on again on its page.'));
|
||||
if (st != 'active')
|
||||
return step(false, cant_connect(p.name, st), '');
|
||||
return step(true, sprintf(_('%s is active'), p.name), access_text(p.access));
|
||||
}
|
||||
|
||||
function connected(dmp, d, who) {
|
||||
let peer = peer_of(dmp, d);
|
||||
if (!peer || !(peer.handshake > 0))
|
||||
return step(false, sprintf(_('%s has never connected'), who), _('There is no session the router could reach.'));
|
||||
if (!live.online(dmp, d.id, peer))
|
||||
return step(false, sprintf(_("%s isn't connected right now"), who), _('The router reaches it only while its VPN is on.'));
|
||||
return step(true, sprintf(_('%s is connected'), who), '');
|
||||
}
|
||||
|
||||
/** A device → somewhere: the router, home, another device or the internet. */
|
||||
function from_device(m, d, t, states, dmp, snap) {
|
||||
let p = m.people[d.person];
|
||||
let srv = p ? m.servers[p.server] : null;
|
||||
if (!p || !srv)
|
||||
return [ step(false, sprintf(_('%s has no server'), d.name), '') ];
|
||||
let steps = [ person_ok(m, p, d, states) ];
|
||||
if (!steps[0].ok)
|
||||
return steps;
|
||||
let allowed = routed(m, srv, p, d);
|
||||
let via = (ip) => {
|
||||
let hit = in_nets(ip, allowed);
|
||||
// The configuration's own words: the option and its value.
|
||||
let what = `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`;
|
||||
return hit
|
||||
? step(true, _('Its configuration sends it to the router'), what)
|
||||
: step(false, _("Its configuration doesn't send it to the router"), sprintf(_("%s: the device's own network handles it."), what));
|
||||
};
|
||||
|
||||
// Another device.
|
||||
if (t.dev) {
|
||||
let q = m.people[t.dev.person];
|
||||
let who = `${q?.name ?? '?'} · ${t.dev.name}`;
|
||||
if (t.dev.id == d.id)
|
||||
return [ step(false, _('That is the same device'), '') ];
|
||||
if (!q || q.server != p.server)
|
||||
return stop(steps, step(false, sprintf(_('%s is on another server'), who), _('Devices of different servers never reach each other.')));
|
||||
if (!home_access(p))
|
||||
return stop(steps, step(false, has_access(p.name, p.access), _('Only people with home access reach other devices.')));
|
||||
if (!home_access(q))
|
||||
return stop(steps, step(false, has_access(q.name, q.access), _('Only devices of people with home access can be reached.')));
|
||||
if (srv.mesh == 'off')
|
||||
return stop(steps, step(false, sprintf(_('"Devices reach each other" is off on %s'), srv.name), _('Server → Access → Home network.')));
|
||||
if (srv.mesh == 'circles' && q.id != p.id) {
|
||||
let a = core.person_circle(m, p), b = core.person_circle(m, q);
|
||||
if (!a || !b || a.id != b.id)
|
||||
return stop(steps, step(false, sprintf(_('%s and %s are not in one circle'), p.name, q.name),
|
||||
`${p.name}: ${a?.name ?? _('no circle')} · ${q.name}: ${b?.name ?? _('no circle')}`));
|
||||
push(steps, step(true, sprintf(_('Both are in %s'), a.name), _('Devices in one circle reach each other.')));
|
||||
}
|
||||
else
|
||||
push(steps, step(true, q.id == p.id ? sprintf(_("Both are %s's devices"), p.name) : _('Devices reach each other on this server'), ''));
|
||||
let st = states[q.id] ?? 'active';
|
||||
if (st != 'active' || t.dev.disabled)
|
||||
return stop(steps, step(false, cant_reach(who, t.dev.disabled, st), ''));
|
||||
push(steps, via(t.ip));
|
||||
push(steps, connected(dmp, t.dev, who));
|
||||
return steps;
|
||||
}
|
||||
|
||||
// A device that keeps its own local network out of the tunnel (lan_bypass;
|
||||
// Home only is the same either way) sends a private address there, router
|
||||
// or home address alike: it never reaches this router's rules.
|
||||
if (d.lan_bypass && p.access != 'lan' && !in_nets(t.ip, allowed))
|
||||
return stop(steps, via(t.ip));
|
||||
|
||||
// The router itself.
|
||||
if (index(router_addrs(snap), t.ip) >= 0) {
|
||||
let portal = m.settings.portal_enabled && (t.port == m.settings.portal_port || (core.portal_http(m) && t.port == core.portal_http_port(m)));
|
||||
if (t.port == 53)
|
||||
push(steps, step(true, sprintf(_('%s is this router: DNS is open to everyone'), t.ip), ''));
|
||||
else if (portal)
|
||||
push(steps, step(true, sprintf(_('%s is this router: the personal portal is open to everyone'), t.ip), ''));
|
||||
else if (!home_access(p))
|
||||
return stop(steps, step(false, sprintf(_('%s is this router'), t.ip), sprintf(p.access == 'lan'
|
||||
? _('%s has Home only: only DNS and the portal on the router.')
|
||||
: _('%s has Internet only: only DNS and the portal on the router.'), p.name)));
|
||||
else {
|
||||
// Like any home address: only on the networks the person reaches.
|
||||
let h = core.person_home(srv, p, snap);
|
||||
if (!h.all && !in_nets(t.ip, h.nets))
|
||||
return stop(steps, step(false, sprintf(_("%s is this router on a network %s doesn't reach"), t.ip, p.name), reaches(p.name, h.devs)));
|
||||
push(steps, step(true, sprintf(_('%s is this router'), t.ip),
|
||||
h.all ? _('Home access includes the router.') : sprintf(_('On one of the networks %s reaches.'), p.name)));
|
||||
}
|
||||
push(steps, via(t.ip));
|
||||
return steps;
|
||||
}
|
||||
|
||||
// A tunnel address no device has.
|
||||
let tn = in_tunnels(m, t.ip);
|
||||
if (tn)
|
||||
return stop(steps, step(false, sprintf(_('No device uses %s'), t.ip), sprintf(_('It is in the tunnel network %s.'), tn)));
|
||||
|
||||
// Home.
|
||||
let sn = net.server_net(srv, snap);
|
||||
let hdev = home_dev_of(srv, t.ip, snap);
|
||||
if (hdev) {
|
||||
if (p.access == 'internet')
|
||||
return stop(steps, step(false, sprintf(_('%s is at home (%s)'), t.ip, hdev), sprintf(_('%s has Internet only.'), p.name)));
|
||||
if (p.access == 'lan' && length(p.services)) {
|
||||
let hit = null;
|
||||
for (let sid in p.services) {
|
||||
let s = m.services[sid];
|
||||
if (s?.address == t.ip && (!length(s.ports) || t.port == null || index(s.ports, `${t.port}`) >= 0))
|
||||
hit = s;
|
||||
}
|
||||
let names = join(', ', map(filter(map(p.services, (x) => m.services[x]), (x) => x), (x) => x.name));
|
||||
if (!hit)
|
||||
return stop(steps, step(false, sprintf(_("%s is not one of %s's home services"), t.port ? `${t.ip}:${t.port}` : t.ip, p.name),
|
||||
sprintf(_('Allowed: %s'), names)));
|
||||
push(steps, step(true, sprintf(_("%s is %s, one of %s's home services"), t.ip, hit.name, p.name),
|
||||
length(hit.ports) ? sprintf(_('Ports %s'), join(', ', hit.ports)) : _('All ports')));
|
||||
}
|
||||
else {
|
||||
let h = core.person_home(srv, p, snap);
|
||||
if (!in_nets(t.ip, h.nets))
|
||||
return stop(steps, step(false, sprintf(_("%s is in %s, which %s doesn't reach"), t.ip, hdev, p.name), reaches(p.name, h.devs)));
|
||||
push(steps, step(true, sprintf(_('%s is in home network %s'), t.ip, hdev),
|
||||
h.all ? _('Home access reaches every home network.') : sprintf(_('One of the networks %s reaches.'), p.name)));
|
||||
}
|
||||
push(steps, via(t.ip));
|
||||
push(steps, step(true, _('The firewall lets it through'), `${srv.ifname} → ${join(', ', sn.zones) || _('home')}`));
|
||||
return steps;
|
||||
}
|
||||
|
||||
// Another private address, or the internet.
|
||||
if (in_nets(t.ip, [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16' ]))
|
||||
return stop(steps, step(false, sprintf(_("%s isn't in %s's home network"), t.ip, srv.name), _('Private addresses outside the home network are blocked.')));
|
||||
if (p.access == 'lan')
|
||||
return stop(steps, step(true, sprintf(_('%s is on the internet'), t.ip),
|
||||
sprintf(_("%s has Home only: their device's own internet reaches it, not the tunnel."), p.name)));
|
||||
push(steps, via(t.ip));
|
||||
push(steps, step(true, sprintf(_('%s is on the internet'), t.ip), srv.lan_like ? _('It leaves like a home device would.')
|
||||
: sn.wan.dev != null ? sprintf(_('It leaves through %s.'), sn.wan.dev) : _('It leaves through the WAN.')));
|
||||
return steps;
|
||||
}
|
||||
|
||||
/** A home address → a device. */
|
||||
function to_device(m, ip, d, states, dmp, snap) {
|
||||
let p = m.people[d.person];
|
||||
let srv = p ? m.servers[p.server] : null;
|
||||
if (!p || !srv)
|
||||
return [ step(false, sprintf(_('%s has no server'), d.name), '') ];
|
||||
let who = `${p.name} · ${d.name}`;
|
||||
let hdev = in_tunnels(m, ip) ? null : home_dev_of(srv, ip, snap);
|
||||
if (!hdev)
|
||||
return [ step(false, sprintf(_("%s isn't in %s's home network"), ip, srv.name), _("Only home devices reach people's devices.")) ];
|
||||
let steps = [ step(true, sprintf(_('%s is at home (%s)'), ip, hdev), '') ];
|
||||
if (!home_access(p))
|
||||
return stop(steps, step(false, p.access == 'lan' ? sprintf(_('%s has only some home services'), p.name) : has_access(p.name, p.access),
|
||||
_('Home devices reach only people with home access.')));
|
||||
let h = core.person_home(srv, p, snap);
|
||||
if (!in_nets(ip, h.nets))
|
||||
return stop(steps, step(false, sprintf(_("%s doesn't reach %s"), p.name, hdev), _('Networks a person does not reach cannot reach them either.')));
|
||||
push(steps, person_ok(m, p, d, states));
|
||||
if (!steps[length(steps) - 1].ok)
|
||||
return steps;
|
||||
push(steps, step(true, _('The firewall lets it through'), `${join(', ', net.server_net(srv, snap).zones) || _('home')} → ${srv.ifname}`));
|
||||
push(steps, connected(dmp, d, who));
|
||||
return steps;
|
||||
}
|
||||
|
||||
/**
|
||||
* `from` and `to`: a device id, or an IPv4 address (optionally :port).
|
||||
* `ctx` = { states, dmp, snap } (a test's own); read from the router when not
|
||||
* given. Returns { ok, steps: [{ ok, title, detail }] }.
|
||||
*/
|
||||
export function check(m, from, to, ctx) {
|
||||
let a = parse_target(m, from), b = parse_target(m, to);
|
||||
if (!a)
|
||||
die(sprintf(_('"%s" is not a device or an IPv4 address.'), from));
|
||||
if (!b)
|
||||
die(sprintf(_('"%s" is not a device or an IPv4 address.'), to));
|
||||
let states = ctx?.states ?? view.states(m, core.load_usage());
|
||||
let dmp = ctx?.dmp ?? live.dump(m);
|
||||
let snap = ctx?.snap ?? net.snapshot(true);
|
||||
let steps;
|
||||
if (a.dev)
|
||||
steps = from_device(m, a.dev, b, states, dmp, snap);
|
||||
else if (b.dev)
|
||||
steps = to_device(m, a.ip, b.dev, states, dmp, snap);
|
||||
else
|
||||
die(_('Choose a device on at least one side.'));
|
||||
let ok = length(filter(steps, (s) => !s.ok)) == 0;
|
||||
return { ok, steps };
|
||||
};
|
||||
@@ -1,424 +1,52 @@
|
||||
// Dawnline — reconciliation. Turns /etc/config/dawnline into router state:
|
||||
// * network interfaces (proto amneziawg), peers applied live with `awg syncconf`
|
||||
// * firewall zones, forwardings and WAN rules (named sections dawnline_*)
|
||||
// * nft table `inet dawnline` enforcing each person's access
|
||||
// * network interfaces (dawnline.netifd) and the devices loaded live into
|
||||
// them (dawnline.awg)
|
||||
// * firewall zones, forwardings, WAN rules and reply routes (dawnline.fw)
|
||||
// * the nft table `inet dawnline` enforcing each person's access (dawnline.nft)
|
||||
// * hostnames in /tmp/hosts/dawnline
|
||||
// * the "like a home device" path and the Home-only resolver (dawnline.loop)
|
||||
// Only objects created by Dawnline are ever modified.
|
||||
//
|
||||
// apply(), sync() and sync_loop() run under one lock ('apply') and read the
|
||||
// model inside it, so a rebuild and a runtime update never interleave and the
|
||||
// last one to run always works from the newest configuration. The config lock
|
||||
// (dawnline.store) is never taken while 'apply' is held.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { readfile, writefile, stat, unlink } from 'fs';
|
||||
import {
|
||||
q, sh, sh_out, sh_bg, ensure_dir, write_file, write_json, read_json, parse_cidr, int2ip, uniq,
|
||||
lock, unlock, RUN_DIR
|
||||
} from 'dawnline.util';
|
||||
import { ensure_dir, write_file, write_json, with_lock, ip2int, slog, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as nft from 'dawnline.nft';
|
||||
import * as fw from 'dawnline.fw';
|
||||
import * as netifd from 'dawnline.netifd';
|
||||
import * as migrate from 'dawnline.migrate';
|
||||
import { _, L_ } from 'dawnline.i18n';
|
||||
|
||||
const HOSTS_FILE = '/tmp/hosts/dawnline';
|
||||
/*
|
||||
* Our own answers leave by the main table: the portal's (TCP) and each
|
||||
* tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule) may mark
|
||||
* the router's own traffic to internet addresses and divert it locally, which
|
||||
* swallows replies to outside clients. These rules sit before such fwmark
|
||||
* rules and only match our listening ports.
|
||||
*/
|
||||
const PREF_REPLY = 90;
|
||||
/** The network signature the last apply() worked from (the agent compares against it). */
|
||||
export const NET_SIG = `${RUN_DIR}/net.sig`;
|
||||
// The last access-table error that was logged (each distinct failure once).
|
||||
const NFT_ERR = `${RUN_DIR}/nft.err`;
|
||||
|
||||
function log(msg) {
|
||||
system(`logger -t dawnline ${q(msg)}`);
|
||||
function log(who, msg, level, detail) {
|
||||
slog('dawnline', level ?? 'info', msg, detail, who);
|
||||
}
|
||||
|
||||
/* ---------- helpers ---------- */
|
||||
|
||||
/** Set an option only when it differs; returns true if something changed. */
|
||||
function put(c, conf, sec, opt, val) {
|
||||
let cur = c.get(conf, sec, opt);
|
||||
if (val == null || val == '' || (type(val) == 'array' && !length(val))) {
|
||||
if (cur != null) {
|
||||
c.delete(conf, sec, opt);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (type(val) == 'array') {
|
||||
if (type(cur) == 'array' && join('\n', cur) == join('\n', val))
|
||||
return false;
|
||||
}
|
||||
else if (cur == `${val}`)
|
||||
return false;
|
||||
c.set(conf, sec, opt, type(val) == 'array' ? val : `${val}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
function ensure_section(c, conf, sec, stype) {
|
||||
if (c.get(conf, sec) == stype)
|
||||
return false;
|
||||
if (c.get(conf, sec) != null)
|
||||
c.delete(conf, sec);
|
||||
c.set(conf, sec, stype);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* After committing a config ourselves (and applying it), record its new
|
||||
* checksum so a later `reload_config` does not treat it as changed and
|
||||
* restart unrelated services that reload on any network change.
|
||||
*/
|
||||
function ack_config(confs) {
|
||||
let md5f = '/var/run/config.md5';
|
||||
if (!stat(md5f))
|
||||
return;
|
||||
let lines = split(trim(readfile(md5f) ?? ''), '\n');
|
||||
for (let conf in confs) {
|
||||
let path = `/var/run/config.check/${conf}`;
|
||||
let sum = sh_out(`uci show ${q(conf)} | md5sum | cut -d' ' -f1`);
|
||||
if (!sum)
|
||||
continue;
|
||||
let found = false;
|
||||
for (let i = 0; i < length(lines); i++)
|
||||
if (substr(lines[i], -length(path) - 2) == ` ${path}`) {
|
||||
lines[i] = `${sum} ${path}`;
|
||||
found = true;
|
||||
}
|
||||
if (!found)
|
||||
push(lines, `${sum} ${path}`);
|
||||
}
|
||||
writefile(md5f, join('\n', lines) + '\n');
|
||||
}
|
||||
|
||||
/* ---------- network ---------- */
|
||||
|
||||
function sync_network(m) {
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
let changed = false, touched = [];
|
||||
let want = {};
|
||||
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.private_key)
|
||||
continue;
|
||||
let ifn = srv.ifname;
|
||||
want[ifn] = true;
|
||||
let addr = core.server_address(srv);
|
||||
let pc = parse_cidr(srv.subnet);
|
||||
let before = changed;
|
||||
changed = ensure_section(c, 'network', ifn, 'interface') || changed;
|
||||
changed = put(c, 'network', ifn, 'proto', 'amneziawg') || changed;
|
||||
changed = put(c, 'network', ifn, 'private_key', srv.private_key) || changed;
|
||||
changed = put(c, 'network', ifn, 'listen_port', srv.port) || changed;
|
||||
changed = put(c, 'network', ifn, 'addresses', [ `${addr}/${pc.prefix}` ]) || changed;
|
||||
changed = put(c, 'network', ifn, 'mtu', srv.mtu) || changed;
|
||||
changed = put(c, 'network', ifn, 'disabled', srv.enabled ? null : '1') || changed;
|
||||
changed = put(c, 'network', ifn, 'auto', srv.enabled ? null : '0') || changed;
|
||||
changed = put(c, 'network', ifn, '_dawnline', id) || changed;
|
||||
for (let k in core.OBF_KEYS)
|
||||
changed = put(c, 'network', ifn, `awg_${k}`, srv.obf[k]) || changed;
|
||||
if (changed != before)
|
||||
push(touched, ifn);
|
||||
}
|
||||
|
||||
// Remove interfaces Dawnline created for servers that no longer exist.
|
||||
let stale = [];
|
||||
c.foreach('network', 'interface', (s) => {
|
||||
if (s._dawnline && !want[s['.name']])
|
||||
push(stale, s['.name']);
|
||||
});
|
||||
for (let ifn in stale) {
|
||||
system(`ifdown ${q(ifn)} 2>/dev/null`);
|
||||
c.delete('network', ifn);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
c.commit('network');
|
||||
ack_config([ 'network' ]);
|
||||
system('ubus call network reload');
|
||||
for (let ifn in touched)
|
||||
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
|
||||
system(`ifup ${q(ifn)}`);
|
||||
log(`network updated (${join(', ', touched) || 'removed ' + join(', ', stale)})`);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/* ---------- firewall ---------- */
|
||||
|
||||
const LOOP_ZONE = 'dl_loop';
|
||||
|
||||
function sync_firewall(m) {
|
||||
let c = cursor();
|
||||
c.load('firewall');
|
||||
let changed = false, want = {};
|
||||
|
||||
let sec = (name, stype, opts) => {
|
||||
want[name] = true;
|
||||
changed = ensure_section(c, 'firewall', name, stype) || changed;
|
||||
for (let k, v in opts)
|
||||
changed = put(c, 'firewall', name, k, v) || changed;
|
||||
};
|
||||
|
||||
let snap = net.snapshot(true);
|
||||
let portal_zone = null, want_loop = false;
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.private_key)
|
||||
continue;
|
||||
let z = `dawnline_${id}`;
|
||||
let sn = net.server_net(srv, snap);
|
||||
portal_zone ??= sn.wan.zone;
|
||||
sec(`${z}_zone`, 'zone', {
|
||||
name: srv.ifname, network: [ srv.ifname ],
|
||||
input: 'ACCEPT', output: 'ACCEPT', forward: 'REJECT',
|
||||
});
|
||||
// Access per person is enforced by the inet dawnline table; the zone
|
||||
// only needs to be allowed to reach each home-network zone and WAN.
|
||||
for (let i, zone in sn.zones)
|
||||
if (zone != sn.wan.zone && zone != srv.ifname)
|
||||
sec(i == 0 ? `${z}_lan` : `${z}_lan_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`, 'forwarding', { src: srv.ifname, dest: zone });
|
||||
sec(`${z}_wan`, 'forwarding', { src: srv.ifname, dest: sn.wan.zone });
|
||||
if (srv.lan_like) {
|
||||
sec(`${z}_loop`, 'forwarding', { src: srv.ifname, dest: LOOP_ZONE });
|
||||
want_loop = true;
|
||||
}
|
||||
sec(`${z}_port`, 'rule', {
|
||||
name: `Dawnline-${srv.ifname}`, src: sn.wan.zone, proto: 'udp',
|
||||
dest_port: srv.port, target: 'ACCEPT', enabled: srv.enabled ? null : '0',
|
||||
});
|
||||
}
|
||||
|
||||
// The link into the netns that re-enters the router from the LAN.
|
||||
if (want_loop) {
|
||||
sec('dawnline_loop', 'zone', {
|
||||
name: LOOP_ZONE, device: [ net.INTERNAL.transit ],
|
||||
input: 'REJECT', output: 'ACCEPT', forward: 'REJECT',
|
||||
});
|
||||
// The Home-only resolver in the netns reaches its upstream DNS this way.
|
||||
sec('dawnline_loop_wan', 'forwarding', { src: LOOP_ZONE, dest: portal_zone ?? 'wan' });
|
||||
}
|
||||
|
||||
if (m.settings.portal_enabled) {
|
||||
let wan = portal_zone ?? 'wan';
|
||||
sec('dawnline_portal', 'rule', {
|
||||
name: 'Dawnline-Portal', src: wan, proto: 'tcp',
|
||||
dest_port: m.settings.portal_port, target: 'ACCEPT',
|
||||
});
|
||||
// IP addresses in links: plain HTTP next to the HTTPS port, and 80 forwarded to it.
|
||||
if (core.portal_http(m)) {
|
||||
sec('dawnline_portal_http', 'rule', {
|
||||
name: 'Dawnline-Portal-HTTP', src: wan, proto: 'tcp',
|
||||
dest_port: core.portal_http_port(m), target: 'ACCEPT',
|
||||
});
|
||||
if (core.portal_http_public(m) == 80)
|
||||
sec('dawnline_portal_80', 'redirect', {
|
||||
name: 'Dawnline-Portal-80', src: wan, proto: 'tcp',
|
||||
src_dport: 80, dest_port: core.portal_http_port(m), target: 'DNAT',
|
||||
});
|
||||
}
|
||||
// Links use 443: from outside it lands on the portal (LuCI stays closed there).
|
||||
if (core.portal_public_port(m) == 443 && m.settings.portal_port != 443)
|
||||
sec('dawnline_portal_443', 'redirect', {
|
||||
name: 'Dawnline-Portal-443', src: wan, proto: 'tcp',
|
||||
src_dport: 443, dest_port: m.settings.portal_port, target: 'DNAT',
|
||||
});
|
||||
}
|
||||
|
||||
let stale = [];
|
||||
c.foreach('firewall', null, (s) => {
|
||||
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
|
||||
push(stale, s['.name']);
|
||||
});
|
||||
for (let s in stale) {
|
||||
c.delete('firewall', s);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
c.commit('firewall');
|
||||
ack_config([ 'firewall' ]);
|
||||
system('fw4 -q reload');
|
||||
log('firewall updated');
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/* ---------- nft access table ---------- */
|
||||
|
||||
const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
|
||||
|
||||
/** Per-person runtime membership: which tunnel addresses may reach what. */
|
||||
export function access_sets(m, usage, states) {
|
||||
let sets = { lan_ok: [], inet_ok: [], svc_ok: [], dns_real: [] };
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (!p || d.disabled || !d.address || states[p.id] != 'active')
|
||||
continue;
|
||||
// Plain DNS for whoever's internet does not go through the router.
|
||||
// Home names: the plain resolver (their internet does not use the tunnel).
|
||||
if (p.access == 'lan' && p.dns_mode == 'home')
|
||||
push(sets.dns_real, d.address);
|
||||
if (p.access == 'internet' || p.access == 'both')
|
||||
push(sets.inet_ok, d.address);
|
||||
if (p.access == 'both' || (p.access == 'lan' && !length(p.services)))
|
||||
push(sets.lan_ok, d.address);
|
||||
else if (p.access == 'lan')
|
||||
for (let sid in p.services) {
|
||||
let s = m.services[sid];
|
||||
if (!s || !s.address)
|
||||
continue;
|
||||
for (let port in s.ports)
|
||||
if (match(port, /^[0-9]+$/))
|
||||
push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`);
|
||||
}
|
||||
}
|
||||
return sets;
|
||||
};
|
||||
|
||||
function set_elems(arr) {
|
||||
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
|
||||
}
|
||||
|
||||
function nft_table(m, sets) {
|
||||
let ifs = [], lan = [];
|
||||
let dns_addr = loop.client_dns();
|
||||
let rt = loop.resolver_target();
|
||||
let snap = net.snapshot();
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key) {
|
||||
push(ifs, `"${srv.ifname}"`);
|
||||
push(lan, ...net.server_net(srv, snap).nets);
|
||||
}
|
||||
lan = net.collapse(lan);
|
||||
let t = [];
|
||||
push(t, 'table inet dawnline {');
|
||||
push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`);
|
||||
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
|
||||
push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`);
|
||||
push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`);
|
||||
push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`);
|
||||
push(t, ' chain pre {');
|
||||
// Ahead of mangle-priority hooks (transparent proxies mark at -150).
|
||||
push(t, ' type filter hook prerouting priority -160; policy accept;');
|
||||
if (length(ifs))
|
||||
push(t, ` iifname { ${join(', ', ifs)} } jump guard`);
|
||||
push(t, ' }');
|
||||
push(t, ' chain guard {');
|
||||
push(t, ' meta nfproto ipv6 drop');
|
||||
push(t, ' ct state established,related accept');
|
||||
push(t, ' icmp type echo-request fib daddr type local accept');
|
||||
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
|
||||
push(t, ' fib daddr type local ip saddr @lan_ok accept');
|
||||
push(t, ' fib daddr type local counter drop');
|
||||
if (dns_addr)
|
||||
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
|
||||
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
|
||||
push(t, ' ip daddr @lan_nets ip saddr @lan_ok accept');
|
||||
push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept');
|
||||
push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`);
|
||||
push(t, ' ip saddr @inet_ok accept');
|
||||
push(t, ' counter drop');
|
||||
push(t, ' }');
|
||||
// Devices ask the tunnel address; send each query where it belongs.
|
||||
let to_resolver = rt.mode == 'ns' ? `dnat ip to ${rt.address}:53` : `redirect to :${rt.port}`;
|
||||
let lan_dns = loop.lan_dns();
|
||||
push(t, ' chain dns {');
|
||||
push(t, ' type nat hook prerouting priority dstnat - 5; policy accept;');
|
||||
if (length(ifs))
|
||||
// Home names (and no LAN DNS at all): the plain resolver, whatever address was asked.
|
||||
push(t, ` iifname { ${join(', ', ifs)} } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 ${to_resolver}`);
|
||||
for (let id, srv in m.servers) {
|
||||
let a = srv.private_key ? core.server_address(srv) : null;
|
||||
if (!a)
|
||||
continue;
|
||||
// Everyone else: the LAN's DNS, through the netns (from the LAN side) when internet goes that way.
|
||||
let target = srv.lan_like && dns_addr ? `dnat ip to ${dns_addr}:53` : lan_dns ? `dnat ip to ${lan_dns}:53` : to_resolver;
|
||||
push(t, ` iifname "${srv.ifname}" ip daddr ${a} meta l4proto { tcp, udp } th dport 53 ${target}`);
|
||||
}
|
||||
push(t, ' }');
|
||||
push(t, '}');
|
||||
return join('\n', t) + '\n';
|
||||
}
|
||||
|
||||
function nft_load(script) {
|
||||
ensure_dir(RUN_DIR);
|
||||
let f = `${RUN_DIR}/nft.rules`;
|
||||
writefile(f, script);
|
||||
let r = sh(`nft -f ${f}`);
|
||||
if (r.code != 0)
|
||||
log(`nft failed: ${trim(r.out)}`);
|
||||
return r.code == 0;
|
||||
}
|
||||
|
||||
/** Full table rebuild (structure changes: servers, LAN subnets). */
|
||||
export function rebuild_nft(m, sets) {
|
||||
let s = 'table inet dawnline\ndelete table inet dawnline\n' + nft_table(m, sets);
|
||||
return nft_load(s);
|
||||
};
|
||||
|
||||
/** Atomically replace set contents only. */
|
||||
export function update_sets(sets) {
|
||||
let s = '';
|
||||
for (let name in [ 'lan_ok', 'inet_ok', 'svc_ok', 'dns_real' ]) {
|
||||
s += `flush set inet dawnline ${name}\n`;
|
||||
if (length(sets[name]))
|
||||
s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`;
|
||||
}
|
||||
return nft_load(s);
|
||||
};
|
||||
|
||||
export function remove_nft() {
|
||||
system('nft delete table inet dawnline 2>/dev/null');
|
||||
};
|
||||
|
||||
/* ---------- AmneziaWG peers ---------- */
|
||||
|
||||
/** Push the peer list of every server to the kernel without restarting it. */
|
||||
export function sync_peers(m, states) {
|
||||
ensure_dir(RUN_DIR);
|
||||
let res = {};
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.private_key || !srv.enabled)
|
||||
continue;
|
||||
if (system(`awg show ${q(srv.ifname)} public-key >/dev/null 2>&1`) != 0) {
|
||||
res[id] = 'down';
|
||||
continue;
|
||||
}
|
||||
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
|
||||
for (let did, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !d.public_key || !d.address)
|
||||
continue;
|
||||
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
|
||||
if (d.preshared_key)
|
||||
push(lines, `PresharedKey = ${d.preshared_key}`);
|
||||
push(lines, `AllowedIPs = ${d.address}/32`, '');
|
||||
}
|
||||
let f = `${RUN_DIR}/${srv.ifname}.conf`;
|
||||
write_file(f, join('\n', lines));
|
||||
let r = sh(`awg syncconf ${q(srv.ifname)} ${f}`);
|
||||
unlink(f);
|
||||
res[id] = r.code == 0 ? 'ok' : trim(r.out);
|
||||
if (r.code != 0)
|
||||
log(`awg syncconf ${srv.ifname}: ${trim(r.out)}`);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
/* ---------- hostnames ---------- */
|
||||
|
||||
function host_label(s) {
|
||||
let l = replace(lc(s), /[^a-z0-9]+/g, '-');
|
||||
l = replace(l, /^-+|-+$/g, '');
|
||||
return substr(l, 0, 40) || 'device';
|
||||
}
|
||||
|
||||
export function sync_hosts(m) {
|
||||
let lines = [];
|
||||
if (m.settings.hostnames)
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (p && d.address)
|
||||
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`);
|
||||
for (let pid, p in m.people) {
|
||||
// One label per device, unique within the person (the UI shows the same).
|
||||
let labels = core.device_labels(m, p);
|
||||
for (let id in p.devices) {
|
||||
let d = m.devices[id];
|
||||
if (ip2int(d.address) != null)
|
||||
push(lines, `${d.address} ${labels[id]}.${p.id}.${m.settings.domain}`);
|
||||
}
|
||||
}
|
||||
let ls = loop.status();
|
||||
if (ls.active)
|
||||
@@ -439,7 +67,7 @@ export function sync_hosts(m) {
|
||||
return true;
|
||||
};
|
||||
|
||||
/* ---------- entry points ---------- */
|
||||
/* ---------- access table ---------- */
|
||||
|
||||
export function states_for(m, usage) {
|
||||
let st = {};
|
||||
@@ -448,21 +76,117 @@ export function states_for(m, usage) {
|
||||
return st;
|
||||
};
|
||||
|
||||
/** Runtime sync: peers + access sets + hostnames. Cheap; safe to call often. */
|
||||
export function sync(m, usage) {
|
||||
m ??= core.load();
|
||||
usage ??= core.load_usage();
|
||||
/** Per-person runtime membership (dawnline.nft). */
|
||||
export function access_sets(m, usage, states) {
|
||||
return nft.access_sets(m, usage, states);
|
||||
};
|
||||
|
||||
/**
|
||||
* Log an access-table failure once per distinct error (with what it means
|
||||
* for the devices: none loaded while the table is missing, the previous rules
|
||||
* kept when an older one survived the failed rebuild); the error, or null.
|
||||
*/
|
||||
function nft_result(err, present) {
|
||||
let was = readfile(NFT_ERR);
|
||||
if (err == null) {
|
||||
if (was != null)
|
||||
unlink(NFT_ERR);
|
||||
return null;
|
||||
}
|
||||
if (was != err) {
|
||||
log(L_('Access rules'), present
|
||||
? L_("couldn't be updated - the previous rules stay, and changes to access wait until they load")
|
||||
: L_("couldn't load - no device is loaded into the tunnels until they do"), 'error', err);
|
||||
ensure_dir(RUN_DIR);
|
||||
writefile(NFT_ERR, err);
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
/**
|
||||
* The table in place: rebuilt with `full`, otherwise members only, rebuilt
|
||||
* when that fails (no table yet at boot, or an older shape). Null, or the
|
||||
* error when the rebuild fails too.
|
||||
*/
|
||||
function load_table(m, sets, full) {
|
||||
let err = full ? nft.rebuild(m, sets) : nft.update(sets);
|
||||
if (err != null && !full)
|
||||
err = nft.rebuild(m, sets);
|
||||
return nft_result(err, err != null && nft.present());
|
||||
}
|
||||
|
||||
/** Full table rebuild (structure changes: servers, LAN subnets); true when it loaded. */
|
||||
export function rebuild_nft(m, sets) {
|
||||
let err = nft.rebuild(m, sets);
|
||||
return nft_result(err, err != null && nft.present()) == null;
|
||||
};
|
||||
|
||||
/** Atomically replace set contents only. */
|
||||
export function update_sets(sets) {
|
||||
return nft.update(sets) == null;
|
||||
};
|
||||
|
||||
export function remove_nft() {
|
||||
nft.remove();
|
||||
};
|
||||
|
||||
/** For the watchdog (dawnline.fw). */
|
||||
export function firewall_drift(m) {
|
||||
return fw.drift(m);
|
||||
};
|
||||
|
||||
/* ---------- runtime sync ---------- */
|
||||
|
||||
/**
|
||||
* What an admin should hear when a sync did not fully take: the access table
|
||||
* failed, or a server did not accept its devices (sentences in the caller's
|
||||
* language, with what nft or awg said). Null when all went in.
|
||||
*/
|
||||
function sync_warning(m, table, peers) {
|
||||
let out = [];
|
||||
if (table != null)
|
||||
push(out, nft.present()
|
||||
? sprintf(_("Access rules couldn't be updated (%s): the previous rules stay, so this change isn't in effect yet."), table)
|
||||
: sprintf(_("Access rules couldn't load (%s): no device is loaded into the tunnels until they do."), table));
|
||||
for (let id, r in peers)
|
||||
if (r != 'ok' && r != 'down')
|
||||
push(out, sprintf(_("Couldn't load devices into %s: %s."), m.servers[id]?.name ?? id, r));
|
||||
return length(out) ? join(' ', [ ...out, _('Open Diagnostics → Health.') ]) : null;
|
||||
}
|
||||
|
||||
/*
|
||||
* With the lock held: access sets first, then devices into the tunnels.
|
||||
* Fail closed: without the table the firewall would let every loaded device
|
||||
* reach everything, so while it is missing no device is loaded at all. An
|
||||
* older table that survived a failed rebuild keeps limiting them with the
|
||||
* sets it has, and the devices still follow people's states (a revoked one
|
||||
* leaves).
|
||||
*/
|
||||
function locked_sync(m, usage, full) {
|
||||
let states = states_for(m, usage);
|
||||
let l = lock('apply');
|
||||
let peers = sync_peers(m, states);
|
||||
let sets = access_sets(m, usage, states);
|
||||
if (!update_sets(sets))
|
||||
rebuild_nft(m, sets);
|
||||
let sets = nft.access_sets(m, usage, states);
|
||||
let table = load_table(m, sets, full);
|
||||
let peers = awg.sync_peers(m, table == null || nft.present() ? states : {});
|
||||
sync_hosts(m);
|
||||
unlock(l);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/states.json`, states, 0o644);
|
||||
return { peers, states };
|
||||
return { peers, states, table, warning: sync_warning(m, table, peers) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Runtime sync: devices into the tunnels (AmneziaWG peers), access sets,
|
||||
* hostnames. Cheap; safe to call often. The model is always read again under
|
||||
* the lock (`m` is accepted for older callers and not used); `usage` is the
|
||||
* caller's (the agent holds the live counters). The result carries `warning`
|
||||
* (a sentence for the admin) when the sync did not fully take.
|
||||
*/
|
||||
export function sync(m, usage) {
|
||||
return with_lock('apply', () => locked_sync(core.load(), usage ?? core.load_usage()));
|
||||
};
|
||||
|
||||
/** Is the access table loaded (the agent's tick re-syncs when it is not). */
|
||||
export function table_present() {
|
||||
return nft.present();
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -480,142 +204,67 @@ export function net_signature(m) {
|
||||
return sprintf('%J', { wan: snap.wan, lan: snap.lan, addrs: lan?.addrs, servers: srvs, dns: loop.lan_dns(), loop: loop.client_dns() });
|
||||
};
|
||||
|
||||
const PORTAL_CGI = '/usr/share/dawnline/portal/www/cgi-bin/portal';
|
||||
const LAN_CGI = '/www/cgi-bin/dawnline-portal';
|
||||
const LAN_CGI_URL = '/cgi-bin/dawnline-portal';
|
||||
|
||||
/*
|
||||
* At home the portal's hostname usually points at the router itself, where
|
||||
* LuCI's web server owns 443. Paths it does not know (the portal's) go to the
|
||||
* portal CGI through its error page, so the same link works inside and out.
|
||||
*/
|
||||
function sync_uhttpd(m) {
|
||||
let want = m.settings.portal_enabled && core.portal_public_port(m) == 443 && m.settings.portal_port != 443;
|
||||
let c = cursor();
|
||||
c.load('uhttpd');
|
||||
let cur = c.get('uhttpd', 'main', 'error_page');
|
||||
let changed = false;
|
||||
if (want) {
|
||||
if (!stat(LAN_CGI))
|
||||
system(`ln -sf ${PORTAL_CGI} ${LAN_CGI}`);
|
||||
if (cur == null && c.get('uhttpd', 'main')) {
|
||||
c.set('uhttpd', 'main', 'error_page', LAN_CGI_URL);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (cur == LAN_CGI_URL) {
|
||||
c.delete('uhttpd', 'main', 'error_page');
|
||||
changed = true;
|
||||
}
|
||||
if (stat(LAN_CGI))
|
||||
unlink(LAN_CGI);
|
||||
}
|
||||
if (changed) {
|
||||
c.commit('uhttpd');
|
||||
system('/etc/init.d/uhttpd reload >/dev/null 2>&1');
|
||||
log(want ? 'portal answers on 443 at home too' : 'portal removed from the LuCI web server');
|
||||
}
|
||||
}
|
||||
|
||||
/** One `ipproto <p> sport <port> lookup main` rule per listening port and family. */
|
||||
function sync_reply_routes(m) {
|
||||
let want = [];
|
||||
if (m.settings.portal_enabled) {
|
||||
push(want, `tcp ${+m.settings.portal_port}`);
|
||||
if (core.portal_http(m))
|
||||
push(want, `tcp ${core.portal_http_port(m)}`);
|
||||
}
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key && srv.enabled && +srv.port)
|
||||
push(want, `udp ${+srv.port}`);
|
||||
want = uniq(want);
|
||||
for (let fam in [ '-4', '-6' ]) {
|
||||
let have = [];
|
||||
for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) {
|
||||
let mm = match(line, /ipproto (tcp|udp) sport (\d+) lookup main/);
|
||||
if (mm)
|
||||
push(have, `${mm[1]} ${mm[2]}`);
|
||||
}
|
||||
for (let h in have)
|
||||
if (index(want, h) < 0)
|
||||
sh(`ip ${fam} rule del priority ${PREF_REPLY} ipproto ${split(h, ' ')[0]} sport ${split(h, ' ')[1]} lookup main 2>/dev/null`);
|
||||
for (let w in want)
|
||||
if (index(have, w) < 0)
|
||||
sh(`ip ${fam} rule add priority ${PREF_REPLY} ipproto ${split(w, ' ')[0]} sport ${split(w, ' ')[1]} lookup main`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the "like a home device" path and the resolver in step (agent tick).
|
||||
* Cheap when nothing changed; rebuilds the access table when the netns
|
||||
* address appears, moves or goes away (the guard allows DNS to it).
|
||||
*/
|
||||
export function sync_loop(m, usage, force) {
|
||||
m ??= core.load();
|
||||
let before = `${loop.client_dns()} ${loop.resolver_target().mode}`;
|
||||
let p = loop.ensure(m, force);
|
||||
loop.sync_resolver(m);
|
||||
sync_reply_routes(m);
|
||||
if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before) {
|
||||
usage ??= core.load_usage();
|
||||
rebuild_nft(m, access_sets(m, usage, states_for(m, usage)));
|
||||
sync_hosts(m);
|
||||
}
|
||||
let p = with_lock('apply', () => {
|
||||
let mm = core.load();
|
||||
let before = `${loop.client_dns()} ${loop.resolver_target().mode}`;
|
||||
let lp = loop.ensure(mm, force);
|
||||
loop.sync_resolver(mm);
|
||||
fw.sync_reply_routes(mm);
|
||||
if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before)
|
||||
locked_sync(mm, usage ?? core.load_usage(), true);
|
||||
return lp;
|
||||
});
|
||||
loop.remember(p);
|
||||
return p;
|
||||
};
|
||||
|
||||
/** Every personal code is a word code; older random ones are replaced (their links stop working). */
|
||||
function ensure_word_codes() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let changed = false;
|
||||
c.foreach('dawnline', 'person', (s) => {
|
||||
if (s.code != null && !match(s.code, core.WORD_CODE)) {
|
||||
c.set('dawnline', s['.name'], 'code', core.new_code());
|
||||
c.delete('dawnline', s['.name'], 'words');
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if (changed) {
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
log('personal links moved to word codes');
|
||||
}
|
||||
}
|
||||
/* ---------- entry points ---------- */
|
||||
|
||||
/** Full reconcile: router configuration + runtime state. */
|
||||
export function apply(opts) {
|
||||
opts ??= {};
|
||||
ensure_word_codes();
|
||||
let m = core.load();
|
||||
let usage = core.load_usage();
|
||||
let l = lock('reconcile');
|
||||
let net = sync_network(m);
|
||||
let fw = sync_firewall(m);
|
||||
sync_uhttpd(m);
|
||||
let lp = loop.ensure(m, true);
|
||||
loop.sync_resolver(m);
|
||||
sync_reply_routes(m);
|
||||
let states = states_for(m, usage);
|
||||
rebuild_nft(m, access_sets(m, usage, states));
|
||||
unlock(l);
|
||||
let r = sync(m, usage);
|
||||
return { network: net, firewall: fw, like_home: lp.error ? { error: lp.error } : !lp.off, peers: r.peers };
|
||||
migrate.run();
|
||||
let r = with_lock('apply', () => {
|
||||
let m = core.load();
|
||||
let usage = core.load_usage();
|
||||
let network = netifd.sync(m);
|
||||
let firewall = fw.sync(m);
|
||||
let lp = loop.ensure(m, true);
|
||||
loop.sync_resolver(m);
|
||||
fw.sync_reply_routes(m);
|
||||
let s = locked_sync(m, usage, true);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_file(NET_SIG, net_signature(m), 0o644);
|
||||
return { network, firewall, lp, peers: s.peers, warning: s.warning };
|
||||
});
|
||||
loop.remember(r.lp);
|
||||
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: loop.error_text(r.lp.error) } : !r.lp.off, peers: r.peers, warning: r.warning };
|
||||
};
|
||||
|
||||
/** Remove everything Dawnline created (used by the uninstaller). */
|
||||
export function teardown() {
|
||||
let m = core.load();
|
||||
loop.remove();
|
||||
unlink(loop.RESOLVER.conf);
|
||||
m.servers = {};
|
||||
m.settings.portal_enabled = false;
|
||||
sync_network(m);
|
||||
sync_firewall(m);
|
||||
sync_uhttpd(m);
|
||||
sync_reply_routes(m);
|
||||
remove_nft();
|
||||
unlink(HOSTS_FILE);
|
||||
system('killall -HUP dnsmasq 2>/dev/null');
|
||||
with_lock('apply', () => {
|
||||
let m = core.load();
|
||||
loop.remove();
|
||||
unlink(loop.RESOLVER.conf);
|
||||
m.servers = {};
|
||||
m.settings.portal_enabled = false;
|
||||
netifd.sync(m);
|
||||
fw.sync(m);
|
||||
fw.sync_reply_routes(m);
|
||||
nft.remove();
|
||||
unlink(HOSTS_FILE);
|
||||
unlink(NET_SIG);
|
||||
system('killall -HUP dnsmasq 2>/dev/null');
|
||||
});
|
||||
migrate.uhttpd();
|
||||
// The agent's heartbeat check.
|
||||
if (system('grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root') == 0)
|
||||
system("sed -i '\\#/usr/libexec/dawnline/heartbeat#d' /etc/crontabs/root; /etc/init.d/cron restart >/dev/null 2>&1");
|
||||
};
|
||||
@@ -0,0 +1,170 @@
|
||||
// Dawnline — where AmneziaWG comes from: the awg-openwrt projects publish
|
||||
// builds per OpenWrt release and target (the kernel module must match the
|
||||
// firmware), and the record of what was installed on which kernel and boot
|
||||
// (an update whose module could not be swapped starts with the next boot:
|
||||
// until then caps() and Health go by the module that still runs). Used by
|
||||
// the updater, the Components RPCs, dawnline.awg and Health. Installing
|
||||
// itself is dawnline.upd_awg.
|
||||
|
||||
import { readfile, stat } from 'fs';
|
||||
import { connect } from 'ubus';
|
||||
import { ensure_dir, read_json, write_json, DATA_DIR } from 'dawnline.util';
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
|
||||
export const SOURCES = {
|
||||
slava: { repo: 'Slava-Shchipunov/awg-openwrt', label: 'Slava-Shchipunov' },
|
||||
grey: { repo: '2Grey/awg-openwrt', label: '2Grey' },
|
||||
};
|
||||
/** Tried in this order when no build is chosen. */
|
||||
export const ORDER = [ 'slava', 'grey' ];
|
||||
export const PKGS = [ 'kmod-amneziawg', 'amneziawg-tools', 'luci-proto-amneziawg' ];
|
||||
export const RU = 'luci-i18n-amneziawg-ru';
|
||||
|
||||
/**
|
||||
* This firmware as the builds name it: { tag: 'v24.10.6', postfix:
|
||||
* '_v24.10.6_aarch64_cortex-a53_mediatek_filogic', ext }, or null.
|
||||
*/
|
||||
export function firmware() {
|
||||
let u = connect();
|
||||
let b = u?.call('system', 'board') ?? {};
|
||||
u?.disconnect();
|
||||
let rel = b.release ?? {};
|
||||
let target = split(rel.target ?? '', '/');
|
||||
let arch = rel.arch ?? match(readfile('/etc/openwrt_release') ?? '', /DISTRIB_ARCH='([^']*)'/)?.[1];
|
||||
if (!rel.version || length(target) != 2 || !arch)
|
||||
return null;
|
||||
return { tag: `v${rel.version}`, postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, ext: pkg.ext(),
|
||||
snapshot: match(rel.version, /SNAPSHOT/) != null };
|
||||
};
|
||||
|
||||
/** What was installed, for whom: /etc/dawnline/awg.json (survives a sysupgrade with the data). */
|
||||
export const RECORD = `${DATA_DIR}/awg.json`;
|
||||
|
||||
/** This boot (a new one loads the module on disk), or null when the kernel does not say. */
|
||||
export function boot_id() {
|
||||
return trim(readfile('/proc/sys/kernel/random/boot_id') ?? '') || null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The size in memory of the loaded kernel module, or null when none is
|
||||
* loaded. sysfs has no version for it, but builds differ in size: a module
|
||||
* reloaded by hand ends a wait for a reboot (pending()).
|
||||
*/
|
||||
export function module_core() {
|
||||
let n = int(trim(readfile('/sys/module/amneziawg/coresize') ?? ''));
|
||||
return n > 0 ? n : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Remember which build was installed on which kernel. After a firmware
|
||||
* upgrade the module is gone (it was built for that kernel): Health can then
|
||||
* say so and offer the build for the new one (dawnline.health). `run` comes
|
||||
* from an install: prev_gen and prev_core, the module that ran before it
|
||||
* (module_now()), and reloaded, false while that one stays loaded until the
|
||||
* next boot. null for a module Dawnline did not install (adopt()).
|
||||
*/
|
||||
export function record(source, tag, packages, run) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(RECORD, {
|
||||
osrelease: trim(readfile('/proc/sys/kernel/osrelease') ?? ''),
|
||||
source, tag, packages, installed: time(), boot: boot_id(),
|
||||
prev_gen: run?.prev_gen ?? null, prev_core: run?.prev_core ?? null, reloaded: run?.reloaded ?? null,
|
||||
}, 0o600);
|
||||
};
|
||||
|
||||
/**
|
||||
* A record for a module Dawnline did not install (install.sh, by hand, or
|
||||
* before Dawnline kept records), so kernel_changed() notices the next
|
||||
* firmware upgrade: the kernel it is for, source null, `installed` the time
|
||||
* Dawnline first saw it. Only when there is no record and the module is
|
||||
* loaded or on disk for the running kernel. The agent calls it when it starts.
|
||||
*/
|
||||
export function adopt() {
|
||||
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||
if (stat(RECORD) || (!stat('/sys/module/amneziawg') && (rel == '' || !stat(`/lib/modules/${rel}/amneziawg.ko`))))
|
||||
return;
|
||||
record(null, null, null, null);
|
||||
};
|
||||
|
||||
/**
|
||||
* The firmware the recorded AmneziaWG build was for, when it is not this one
|
||||
* (and the module is gone): { was, now, tag, source }, else null.
|
||||
*/
|
||||
export function kernel_changed() {
|
||||
let r = read_json(RECORD, null);
|
||||
let now = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||
if (!r?.osrelease || r.osrelease == now)
|
||||
return null;
|
||||
return { was: r.osrelease, now, tag: r.tag, source: r.source };
|
||||
};
|
||||
|
||||
/** The file name of a package in a build. */
|
||||
export function asset(fw, name) {
|
||||
return `${name}${fw.postfix}.${fw.ext}`;
|
||||
};
|
||||
|
||||
/** The same firmware, another release of its series (v24.10.6 → v24.10.8). */
|
||||
export function for_tag(fw, tag) {
|
||||
return { ...fw, tag, postfix: replace(fw.postfix, fw.tag, tag) };
|
||||
};
|
||||
|
||||
/**
|
||||
* AmneziaWG generation of a package version: 3.x packages carry 3.1; 1.0.x
|
||||
* ones are 2.0 (S3/S4, I1-I5, header ranges) from July 2025 on, and the
|
||||
* first generation before that. A kernel module's version carries the kernel
|
||||
* release in front (6.12.94.3.1.20260906): the AmneziaWG part is at the end.
|
||||
*/
|
||||
export function gen(version) {
|
||||
if (version == null)
|
||||
return null;
|
||||
let v = match(`${version}`, /([0-9]+\.[0-9]+\.[0-9]{8})(-r?[0-9]+)?$/)?.[1] ?? `${version}`;
|
||||
if (match(v, /^3\./))
|
||||
return '3.1';
|
||||
if (match(v, /^1\.0\.2024/) || match(v, /^1\.0\.20250[1-6]/))
|
||||
return '1.0';
|
||||
return '2.0';
|
||||
};
|
||||
|
||||
/**
|
||||
* An installed update that waits for a reboot: the install could not swap
|
||||
* the kernel module (the old one stayed loaded), this is still the boot it
|
||||
* ran in, and the module loaded is still the one from before it (core:
|
||||
* module_core() now). Pure: rec is the record or null.
|
||||
*/
|
||||
export function pending(rec, boot, core) {
|
||||
return rec?.reloaded === false && rec.boot != null && rec.boot == boot && core != null && rec.prev_core == core;
|
||||
};
|
||||
|
||||
/**
|
||||
* The AmneziaWG generation of the kernel module that runs: the one from
|
||||
* before the install while it waits for a reboot (pending(); null when that
|
||||
* module had no package), else the installed package's version (gen()).
|
||||
* Pure, with the record, this boot and module_core() passed in.
|
||||
*/
|
||||
export function running_gen(rec, boot, core, version) {
|
||||
return pending(rec, boot, core) ? rec.prev_gen : gen(version);
|
||||
};
|
||||
|
||||
/**
|
||||
* The kernel module loaded now, taken before an install changes packages:
|
||||
* { core, gen, pending }. core is null when none is loaded; gen is what it
|
||||
* runs (running_gen(), from `version`, the kmod-amneziawg package installed
|
||||
* now); pending, an earlier update that still waits for a reboot.
|
||||
*/
|
||||
export function module_now(version) {
|
||||
let rec = read_json(RECORD, null), boot = boot_id(), core = module_core();
|
||||
return { core, gen: core == null ? null : running_gen(rec, boot, core, version), pending: pending(rec, boot, core) };
|
||||
};
|
||||
|
||||
/** The installed AmneziaWG update waits for a reboot (pending(), for Health and Components). */
|
||||
export function waits_for_reboot() {
|
||||
return pending(read_json(RECORD, null), boot_id(), module_core());
|
||||
};
|
||||
|
||||
/** The installed AmneziaWG packages: { name: version | null }. */
|
||||
export function installed() {
|
||||
let r = {};
|
||||
for (let p in PKGS)
|
||||
r[p] = pkg.version(p);
|
||||
return r;
|
||||
};
|
||||
@@ -0,0 +1,326 @@
|
||||
// Dawnline — backups (tar.gz of the config and its data files), restoring
|
||||
// them, and the JSON export / import. Whatever comes back in is checked first:
|
||||
// only Dawnline's own regular files, and servers that cannot take over one of
|
||||
// the router's own interfaces or networks, or hand the kernel disguise values
|
||||
// AmneziaWG refuses.
|
||||
|
||||
import { readfile, stat, unlink, lsdir, rename } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import {
|
||||
q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as health from 'dawnline.health';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
const BACKUP_DIR = `${DATA_DIR}/backups`;
|
||||
/**
|
||||
* How many backups of each kind stay (the newest): the nightly ones must not
|
||||
* push out what the admin made by hand or what a removal left behind.
|
||||
*/
|
||||
const KEEP = { manual: 10, auto: 7, 'pre-delete': 5, 'pre-remove': 3, 'pre-update': 3, 'pre-restore': 3, 'pre-import': 3 };
|
||||
const NAME = /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/;
|
||||
/** What a backup holds (paths inside the archive, relative to /). */
|
||||
const FILES = [ 'etc/config/dawnline', 'etc/dawnline/usage.json', 'etc/dawnline/events.json' ];
|
||||
/**
|
||||
* Kinds that hold the config alone (about 20 KB): the history can be a
|
||||
* megabyte or more, and these are made often and never to bring history
|
||||
* back. Manual, pre-restore and pre-import backups protect the data that is
|
||||
* about to be replaced, so they take everything.
|
||||
*/
|
||||
const CONFIG_ONLY = [ 'auto', 'pre-delete', 'pre-remove', 'pre-update' ];
|
||||
/** The unpacked size a backup may have (the upload itself is limited to 4 MB). */
|
||||
const MAX_UNPACKED = 16 * 1024 * 1024;
|
||||
|
||||
/* ---------- checking a configuration before it is used ---------- */
|
||||
|
||||
/**
|
||||
* What is wrong with a configuration about to replace the current one
|
||||
* (cursor `c` holds it): each server must have a valid, unique interface
|
||||
* name that is not one of the router's own interfaces, a free subnet, a
|
||||
* unique port and disguise values AmneziaWG takes (awg.obf_unsafe), and the
|
||||
* people and devices must be consistent (core.model_errors). [] when it can
|
||||
* be used.
|
||||
*/
|
||||
export function config_errors(c) {
|
||||
let m = core.load(c);
|
||||
let errs = core.model_errors(m);
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
let foreign = health.foreign_subnets();
|
||||
let internal = values(net.INTERNAL);
|
||||
let ifnames = {}, ports = {}, subnets = [];
|
||||
for (let id, srv in m.servers) {
|
||||
for (let e in [ ...core.server_errors(m, srv, [ ...foreign, ...subnets ]), ...awg.obf_unsafe(srv.obf) ])
|
||||
push(errs, sprintf(_('Server %s: %s'), srv.name, e));
|
||||
if (ifnames[srv.ifname])
|
||||
push(errs, sprintf(_('Server %s: interface %s is also used by %s.'), srv.name, srv.ifname, ifnames[srv.ifname]));
|
||||
ifnames[srv.ifname] = srv.name;
|
||||
let t = nc.get('network', srv.ifname);
|
||||
if (index(internal, srv.ifname) >= 0 || (t != null && (t != 'interface' || nc.get('network', srv.ifname, '_dawnline') == null)))
|
||||
push(errs, sprintf(_("Server %s: %s is one of the router's own network interfaces."), srv.name, srv.ifname));
|
||||
if (ports[srv.port])
|
||||
push(errs, sprintf(_('Server %s: UDP %s is also used by %s.'), srv.name, srv.port, ports[srv.port]));
|
||||
ports[srv.port] = srv.name;
|
||||
if (srv.subnet)
|
||||
push(subnets, srv.subnet);
|
||||
}
|
||||
return errs;
|
||||
};
|
||||
|
||||
/** Check the config file in `dir` (as /etc/config/dawnline would be); dies listing the problems. */
|
||||
function check_config_dir(dir) {
|
||||
ensure_dir(`${dir}/.delta`, 0o700);
|
||||
// Its own delta directory: changes staged in LuCI must not leak into the check.
|
||||
let c = cursor(dir, `${dir}/.delta`);
|
||||
if (!c.load('dawnline'))
|
||||
die(_('The configuration in this file cannot be read.'));
|
||||
let errs = config_errors(c);
|
||||
if (length(errs))
|
||||
die(sprintf(_("This configuration can't be used: %s"), join(' ', errs)));
|
||||
}
|
||||
|
||||
/** A private scratch directory under RUN_DIR (the caller removes it). */
|
||||
function scratch(kind) {
|
||||
ensure_dir(RUN_DIR);
|
||||
let dir = `${RUN_DIR}/${kind}.${rand_hex(4)}`;
|
||||
system(`rm -rf ${q(dir)}; mkdir -m 700 -p ${q(dir)}`);
|
||||
return dir;
|
||||
}
|
||||
|
||||
/* ---------- backups ---------- */
|
||||
|
||||
export function backup_list() {
|
||||
let out = [];
|
||||
for (let f in lsdir(BACKUP_DIR) ?? []) {
|
||||
let mm = match(f, NAME);
|
||||
if (!mm)
|
||||
continue;
|
||||
let st = stat(`${BACKUP_DIR}/${f}`);
|
||||
push(out, { name: f, created: st?.mtime ?? 0, size: st?.size ?? 0, reason: mm[3] ?? 'manual' });
|
||||
}
|
||||
return sort(out, (a, b) => b.created - a.created);
|
||||
};
|
||||
|
||||
/**
|
||||
* Make a backup now; returns its name. Written whole or not at all (a half
|
||||
* archive from a full flash never shows up as a backup). Of each kind the
|
||||
* oldest beyond KEEP are removed, except `keep` (the backup being restored,
|
||||
* which must survive the backup made just before restoring it).
|
||||
*/
|
||||
export function backup_create(reason, keep) {
|
||||
let kind = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? reason : 'manual';
|
||||
let config_only = index(CONFIG_ONLY, kind) >= 0;
|
||||
// Flush live counters first so the backup has current usage.
|
||||
if (!config_only) {
|
||||
let u = read_json(`${RUN_DIR}/usage.json`, null);
|
||||
if (u)
|
||||
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
|
||||
live.persist_events();
|
||||
}
|
||||
ensure_dir(BACKUP_DIR, 0o700);
|
||||
let t = localtime();
|
||||
let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, kind == 'manual' ? '' : `-${kind}`);
|
||||
let want = config_only ? [ FILES[0] ] : FILES;
|
||||
let files = join(' ', map(filter(want, (f) => file_exists(`/${f}`)), q));
|
||||
// Not a NAME until it is complete.
|
||||
let tmp = `${BACKUP_DIR}/.${name}.tmp`;
|
||||
let r = sh(`tar -czf ${q(tmp)} -C / ${files}`);
|
||||
if (r.code != 0 || !rename(tmp, `${BACKUP_DIR}/${name}`)) {
|
||||
unlink(tmp);
|
||||
let why = trim(r.out);
|
||||
die(why ? sprintf(_('Backup failed: %s'), why) : _('Backup failed: the archive could not be written (is the flash full?)'));
|
||||
}
|
||||
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
|
||||
let by_kind = {};
|
||||
for (let b in backup_list())
|
||||
if (b.name != keep && b.name != name)
|
||||
push(by_kind[b.reason] ??= [], b);
|
||||
for (let k, list in by_kind)
|
||||
for (let i = KEEP[k] ?? 3; i < length(list); i++)
|
||||
unlink(`${BACKUP_DIR}/${list[i].name}`);
|
||||
return name;
|
||||
};
|
||||
|
||||
function backup_path(name) {
|
||||
if (!match(name ?? '', NAME))
|
||||
die(_('Invalid backup name.'));
|
||||
let p = `${BACKUP_DIR}/${name}`;
|
||||
if (!file_exists(p))
|
||||
die(_('Backup not found.'));
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an archive: only Dawnline's own files, all of them regular files
|
||||
* (no links, devices or directories), within a sane unpacked size.
|
||||
*/
|
||||
function check_archive(path) {
|
||||
let r = sh(`tar -tvzf ${q(path)}`);
|
||||
if (r.code != 0)
|
||||
die(_('Not a valid backup archive.'));
|
||||
let has_config = false, total = 0;
|
||||
for (let line in split(trim(r.out), '\n')) {
|
||||
let f = split(trim(line), /[ \t]+/);
|
||||
let name = replace(f[length(f) >= 6 ? 5 : length(f) - 1] ?? '', /^\.?\//, '');
|
||||
// "-rw------- root/root 1234 2026-01-01 12:00:00 etc/config/dawnline"; links show "a -> b".
|
||||
if (substr(line, 0, 1) != '-' || index(line, ' -> ') >= 0 || index(line, ' link to ') >= 0)
|
||||
die(sprintf(_('Unexpected entry in backup: %s'), name));
|
||||
if (index(FILES, name) < 0)
|
||||
die(sprintf(_('Unexpected file in backup: %s'), name));
|
||||
total += +(f[2] ?? 0) || 0;
|
||||
if (name == 'etc/config/dawnline')
|
||||
has_config = true;
|
||||
}
|
||||
if (!has_config)
|
||||
die(_('Backup does not contain /etc/config/dawnline.'));
|
||||
if (total > MAX_UNPACKED)
|
||||
die(_('Backup is too large.'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the files unpacked in `dir` in place, under the config lock. The
|
||||
* config goes first: when it cannot be written nothing else is touched, and
|
||||
* a data file that fails afterwards is reported, not ignored.
|
||||
*/
|
||||
function install_files(dir) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
let l = lock('config');
|
||||
try {
|
||||
for (let f in FILES) {
|
||||
let data = readfile(`${dir}/${f}`);
|
||||
if (data != null && !write_file(`/${f}`, data, 0o600))
|
||||
die(sprintf(_("Couldn't write %s. Is the flash full?"), `/${f}`));
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
unlock(l);
|
||||
die(e.message);
|
||||
}
|
||||
unlock(l);
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
}
|
||||
|
||||
export function backup_restore(name, path) {
|
||||
path ??= backup_path(name);
|
||||
check_archive(path);
|
||||
let dir = scratch('restore');
|
||||
try {
|
||||
let r = sh(`tar -xzf ${q(path)} -C ${q(dir)} ${join(' ', map(FILES, q))} 2>/dev/null; test -f ${q(dir + '/etc/config/dawnline')}`);
|
||||
if (r.code != 0)
|
||||
die(_('Not a valid backup archive.'));
|
||||
check_config_dir(`${dir}/etc/config`);
|
||||
backup_create('pre-restore', name);
|
||||
install_files(dir);
|
||||
}
|
||||
catch (e) {
|
||||
system(`rm -rf ${q(dir)}`);
|
||||
die(e.message);
|
||||
}
|
||||
system(`rm -rf ${q(dir)}`);
|
||||
// Live counters must follow the restored file: the agent reloads them from
|
||||
// flash on its next tick (its watcher may write the old ones again before).
|
||||
unlink(`${RUN_DIR}/usage.json`);
|
||||
unlink(`${RUN_DIR}/events.json`);
|
||||
write_file(live.USAGE_RELOAD, `${time()}`, 0o600);
|
||||
return apply.apply();
|
||||
};
|
||||
|
||||
export function backup_delete(name) {
|
||||
unlink(backup_path(name));
|
||||
return true;
|
||||
};
|
||||
|
||||
export function backup_read(name) {
|
||||
return b64enc(readfile(backup_path(name)));
|
||||
};
|
||||
|
||||
export function backup_upload(data_b64) {
|
||||
let data = b64dec(data_b64 ?? '');
|
||||
if (!data || length(data) > 4 * 1024 * 1024)
|
||||
die(_('Upload is empty or too large.'));
|
||||
ensure_dir(RUN_DIR);
|
||||
let tmp = `${RUN_DIR}/upload.tar.gz`;
|
||||
write_file(tmp, data);
|
||||
let res;
|
||||
try {
|
||||
res = backup_restore(null, tmp);
|
||||
}
|
||||
catch (e) {
|
||||
unlink(tmp);
|
||||
die(e.message);
|
||||
}
|
||||
unlink(tmp);
|
||||
return res;
|
||||
};
|
||||
|
||||
/* ---------- export / import (JSON) ---------- */
|
||||
|
||||
export function export_json() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let sections = [];
|
||||
c.foreach('dawnline', null, (s) => {
|
||||
let o = { '.type': s['.type'], '.name': s['.name'] };
|
||||
for (let k, v in s)
|
||||
if (substr(k, 0, 1) != '.')
|
||||
o[k] = v;
|
||||
push(sections, o);
|
||||
});
|
||||
return { format: 'dawnline', version: VERSION, exported: time(), sections };
|
||||
};
|
||||
|
||||
/** An export as /etc/config/dawnline text; dies on anything that is not one. */
|
||||
function export_to_uci(data) {
|
||||
if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array')
|
||||
die(_('Not a Dawnline export.'));
|
||||
let types = { settings: true, server: true, person: true, device: true, service: true, circle: true };
|
||||
let esc = (x) => replace(`${x}`, "'", "'\\''");
|
||||
let lines = [];
|
||||
for (let s in data.sections) {
|
||||
if (type(s) != 'object' || !types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/))
|
||||
die(sprintf(_('Invalid section %s.'), s?.['.name']));
|
||||
push(lines, `config ${s['.type']} '${s['.name']}'`);
|
||||
for (let k, v in s) {
|
||||
if (substr(k, 0, 1) == '.')
|
||||
continue;
|
||||
if (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array'))
|
||||
die(sprintf(_('Invalid option %s.'), k));
|
||||
if (type(v) == 'array')
|
||||
for (let x in v) {
|
||||
if (type(x) != 'string')
|
||||
die(sprintf(_('Invalid option %s.'), k));
|
||||
push(lines, `\tlist ${k} '${esc(x)}'`);
|
||||
}
|
||||
else
|
||||
push(lines, `\toption ${k} '${esc(v)}'`);
|
||||
}
|
||||
push(lines, '');
|
||||
}
|
||||
return join('\n', lines);
|
||||
}
|
||||
|
||||
export function import_json(data) {
|
||||
let text = export_to_uci(data);
|
||||
let dir = scratch('import');
|
||||
try {
|
||||
write_file(`${dir}/dawnline`, text, 0o600);
|
||||
check_config_dir(dir);
|
||||
}
|
||||
catch (e) {
|
||||
system(`rm -rf ${q(dir)}`);
|
||||
die(e.message);
|
||||
}
|
||||
system(`rm -rf ${q(dir)}`);
|
||||
backup_create('pre-import');
|
||||
let l = lock('config');
|
||||
let ok = write_file('/etc/config/dawnline', text, 0o600);
|
||||
unlock(l);
|
||||
if (!ok)
|
||||
die(sprintf(_("Couldn't write %s. Is the flash full?"), '/etc/config/dawnline'));
|
||||
return apply.apply();
|
||||
};
|
||||
@@ -0,0 +1,158 @@
|
||||
// Dawnline — adding, changing, rotating and removing a person's devices: one
|
||||
// code path for the admin UI (rpcd) and the portal, with the config lock,
|
||||
// the runtime sync, the activity log and the "configuration issued" mark.
|
||||
//
|
||||
// opts = { by: 'admin' | 'portal', person?: the only person whose devices may
|
||||
// be touched (the portal), defer?: load new keys a moment later (the portal
|
||||
// page came through the device being rotated) }. The portal is held to the
|
||||
// device limit (dawnline.core) and cannot touch a device the admin turned off.
|
||||
|
||||
import { sh_bg } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as store from 'dawnline.store';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
/** AmneziaWG is on the router, so device keys can be made and loaded. */
|
||||
export function ready() {
|
||||
return awg.installed();
|
||||
};
|
||||
|
||||
/** Dies with the admin's wording when AmneziaWG is missing. */
|
||||
export function need_awg() {
|
||||
if (!awg.installed()) {
|
||||
let miss = awg.state().missing ?? [];
|
||||
die(length(miss) ? sprintf(_('AmneziaWG is not installed (%s): install it in Dawnline → Components.'), join(', ', miss))
|
||||
: _('AmneziaWG is not installed: install it in Dawnline → Components.'));
|
||||
}
|
||||
};
|
||||
|
||||
/** The device `id` as `opts` may touch it (inside a transaction's model). */
|
||||
function own(m, id, opts) {
|
||||
let d = m.devices[id];
|
||||
if (!d || (opts.person != null && d.person != opts.person))
|
||||
die(opts.person != null ? _('Device not found.') : _('Unknown device.'));
|
||||
if (opts.by == 'portal' && d.disabled)
|
||||
die(_('The admin has turned this device off.'));
|
||||
return d;
|
||||
}
|
||||
|
||||
/**
|
||||
* New device with fresh keys (or the browser's public key): { id, config }.
|
||||
* `opts.lan_bypass` true keeps its own local network outside the tunnel.
|
||||
*/
|
||||
export function add(person, name, kind, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind,
|
||||
{ by, keys: awg.new_keys(opts.public_key || null), lan_bypass: opts.lan_bypass === true }));
|
||||
let s = apply.sync();
|
||||
let m = core.load();
|
||||
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
|
||||
awg.mark_issued(m, id);
|
||||
return { id, config: awg.client_config(m, m.devices[id]), warning: s.warning };
|
||||
};
|
||||
|
||||
/**
|
||||
* Rename and/or turn a device off or on, or change how it connects (`ch` =
|
||||
* { name?, disabled?, mtu?, keepalive?, lan_bypass? }, see
|
||||
* core.set_device_link); only the admin turns devices off or changes the
|
||||
* rest. Returns the runtime sync ({} after a change of the link values alone:
|
||||
* they are in the device's configuration, nothing on the router changes).
|
||||
*/
|
||||
export function update(id, ch, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
if (ch.disabled != null && by != 'admin')
|
||||
die(_('Only the admin can turn devices off.'));
|
||||
let link = ch.mtu != null || ch.keepalive != null || ch.lan_bypass != null;
|
||||
if (link && by != 'admin')
|
||||
die(_('Only the admin can change how a device connects.'));
|
||||
let linked = [];
|
||||
let d0 = store.transact((c, m) => {
|
||||
let d = own(m, id, opts);
|
||||
let was = { ...d };
|
||||
if (ch.name != null && ch.name != d.name)
|
||||
core.rename_device(c, m, id, ch.name);
|
||||
if (ch.disabled != null) {
|
||||
if (ch.disabled)
|
||||
c.set(core.CONFIG, id, 'disabled', '1');
|
||||
else
|
||||
c.delete(core.CONFIG, id, 'disabled');
|
||||
}
|
||||
if (link)
|
||||
linked = core.set_device_link(c, m, id, ch);
|
||||
return was;
|
||||
});
|
||||
let r = ch.name != null || ch.disabled != null ? apply.sync() : {};
|
||||
if (ch.disabled != null && !!ch.disabled != !!d0.disabled)
|
||||
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: ch.disabled ? 'turned off' : 'turned on', by });
|
||||
else if (ch.name != null && ch.name != d0.name)
|
||||
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: `renamed from ${d0.name}`, by });
|
||||
// The option names, as person_changed lists a person's.
|
||||
if (length(linked))
|
||||
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: join(', ', linked), by });
|
||||
return r;
|
||||
};
|
||||
|
||||
/*
|
||||
* New keys for a device: returns its new configuration, marked as issued (it
|
||||
* goes to the set-up sheet; the device then waits for it as "Not set up yet",
|
||||
* not as "settings changed"). Only through reconnect: new keys always mean
|
||||
* setting the device up again.
|
||||
*/
|
||||
function rotate(id, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
store.transact((c, m) => {
|
||||
own(m, id, opts);
|
||||
core.rotate_device(c, m, id, awg.new_keys());
|
||||
});
|
||||
// The device a portal page came through would lose its tunnel before the
|
||||
// answer gets out: load the new key a moment after answering.
|
||||
let s = null;
|
||||
if (opts.defer)
|
||||
sh_bg('sleep 3; /usr/bin/dawnline sync');
|
||||
else
|
||||
s = apply.sync();
|
||||
let m = core.load();
|
||||
let d = m.devices[id];
|
||||
live.add_event({ type: 'device_keys', person: d.person, device: id, detail: d.name, by });
|
||||
awg.mark_issued(m, id);
|
||||
let cfg = awg.client_config(m, d);
|
||||
if (s?.warning)
|
||||
cfg.warning = s.warning;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a device up from scratch (a new phone, the app reinstalled, settings
|
||||
* the admin changed; the portal's Reconnect and the admin's New keys): new
|
||||
* keys, so the configuration it holds stops working with the sync, and it
|
||||
* counts as not set up until it connects with the new one. The usage keeps
|
||||
* the old keys' last handshake: awg.handshake_since hides it. Returns the new
|
||||
* configuration (with `warning` when the sync did not fully take).
|
||||
*/
|
||||
export function reconnect(id, opts) {
|
||||
opts ??= {};
|
||||
let cfg = rotate(id, opts);
|
||||
// A deferred sync (the page came through this device) lets the old keys live a few seconds more.
|
||||
awg.mark_reconnect(core.load(), id, time() + (opts.defer ? 5 : 0));
|
||||
return cfg;
|
||||
};
|
||||
|
||||
/** Remove a device. Returns the runtime sync. */
|
||||
export function remove(id, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
let d = store.transact((c, m) => {
|
||||
let d = own(m, id, opts);
|
||||
core.delete_device(c, m, id);
|
||||
return d;
|
||||
});
|
||||
let r = apply.sync();
|
||||
live.add_event({ type: 'device_removed', person: d.person, device: id, detail: d.name, dname: d.name, dkind: d.kind, by });
|
||||
return r;
|
||||
};
|
||||
@@ -0,0 +1,285 @@
|
||||
// Dawnline — fw4 and routing around it: each tunnel's zone, its forwardings
|
||||
// to home and WAN, the WAN rules for the tunnels and the portal (named
|
||||
// sections dawnline_*), what the watchdog checks about them, and the nft
|
||||
// table that keeps Dawnline's own answers out of proxies. Only sections
|
||||
// named dawnline_* are ever changed.
|
||||
|
||||
import { readfile, unlink } from 'fs';
|
||||
import { q, sh, sh_out, uniq, in_nets, uci_put, uci_section, ack_config, write_file, RUN_DIR } from 'dawnline.util';
|
||||
import { cursor } from 'uci';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as nft from 'dawnline.nft';
|
||||
import * as loop from 'dawnline.loop';
|
||||
|
||||
const LOOP_ZONE = 'dl_loop';
|
||||
/*
|
||||
* Our own answers leave by the main table: the portal's (TCP) and each
|
||||
* tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule to a
|
||||
* `local default` table) mark the router's own traffic to internet addresses
|
||||
* in an output route chain, which diverts replies to outside clients into lo.
|
||||
* A policy rule on the source port can't exempt them: the reroute after the
|
||||
* mark is set looks up without ports. So a later output route chain of our
|
||||
* own clears exactly those proxy marks on packets from our listening ports,
|
||||
* and the kernel routes them again by main. Forwarded traffic is not touched.
|
||||
*/
|
||||
const REPLY_TABLE = 'dawnline_reply';
|
||||
const REPLY_SIG = `${RUN_DIR}/reply.nft`;
|
||||
/** Older versions kept answers out of proxies with `ip rule` at this priority; it never matched. */
|
||||
const PREF_REPLY = 90;
|
||||
|
||||
/** With `dry`, only says whether the firewall config differs from what Dawnline wants. */
|
||||
export function sync(m, dry) {
|
||||
let c = cursor();
|
||||
c.load('firewall');
|
||||
let changed = false, want = {};
|
||||
|
||||
let sec = (name, stype, opts) => {
|
||||
want[name] = true;
|
||||
changed = uci_section(c, 'firewall', name, stype) || changed;
|
||||
for (let k, v in opts)
|
||||
changed = uci_put(c, 'firewall', name, k, v) || changed;
|
||||
};
|
||||
|
||||
let snap = net.snapshot(true);
|
||||
let portal_zone = null, want_loop = false;
|
||||
// Where tunnel DNS is sent (dawnline.nft): into the netns for home names
|
||||
// while any server runs "like a home device", and to the LAN's DNS for
|
||||
// everyone else. A server that does not forward to those zones on its own
|
||||
// gets a rule for port 53 alone.
|
||||
let any_loop = length(filter(values(m.servers), (s) => s.lan_like && length(core.tunnels(s)))) > 0;
|
||||
let lan_dns = loop.lan_dns();
|
||||
let lan_dns_zone = null;
|
||||
if (lan_dns)
|
||||
for (let dev, d in snap.devices)
|
||||
if (d.zone && in_nets(lan_dns, d.nets ?? []))
|
||||
lan_dns_zone ??= d.zone;
|
||||
for (let id, srv in m.servers) {
|
||||
if (!length(core.tunnels(srv)))
|
||||
continue;
|
||||
let z = `dawnline_${id}`;
|
||||
let sn = net.server_net(srv, snap);
|
||||
portal_zone ??= sn.wan.zone;
|
||||
if (!srv.lan_like && any_loop)
|
||||
sec(`${z}_loopdns`, 'rule', {
|
||||
name: `Dawnline-${srv.ifname}-names`, src: srv.ifname, dest: LOOP_ZONE,
|
||||
proto: 'tcp udp', dest_port: 53, target: 'ACCEPT',
|
||||
});
|
||||
if (lan_dns_zone && lan_dns_zone != srv.ifname && index(sn.zones, lan_dns_zone) < 0)
|
||||
sec(`${z}_landns`, 'rule', {
|
||||
name: `Dawnline-${srv.ifname}-dns`, src: srv.ifname, dest: lan_dns_zone, dest_ip: lan_dns,
|
||||
proto: 'tcp udp', dest_port: 53, target: 'ACCEPT',
|
||||
});
|
||||
sec(`${z}_zone`, 'zone', {
|
||||
// Forward within the zone (device to device) is decided by the inet dawnline table.
|
||||
name: srv.ifname, network: [ srv.ifname ],
|
||||
input: 'ACCEPT', output: 'ACCEPT', forward: 'ACCEPT',
|
||||
});
|
||||
// Access per person is enforced by the inet dawnline table; the zone
|
||||
// only needs to be allowed to reach each home-network zone and WAN.
|
||||
// The home network may open connections to the devices too (a router
|
||||
// or a NAS on the tunnel); their answers pass the table as established.
|
||||
for (let i, zone in sn.zones)
|
||||
if (zone != sn.wan.zone && zone != srv.ifname) {
|
||||
let sfx = i == 0 ? '' : `_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`;
|
||||
sec(`${z}_lan${sfx}`, 'forwarding', { src: srv.ifname, dest: zone });
|
||||
sec(`${z}_from_lan${sfx}`, 'forwarding', { src: zone, dest: srv.ifname });
|
||||
}
|
||||
sec(`${z}_wan`, 'forwarding', { src: srv.ifname, dest: sn.wan.zone });
|
||||
if (srv.lan_like) {
|
||||
sec(`${z}_loop`, 'forwarding', { src: srv.ifname, dest: LOOP_ZONE });
|
||||
want_loop = true;
|
||||
}
|
||||
sec(`${z}_port`, 'rule', {
|
||||
name: `Dawnline-${srv.ifname}`, src: sn.wan.zone, proto: 'udp',
|
||||
dest_port: srv.port, target: 'ACCEPT', enabled: srv.enabled ? null : '0',
|
||||
});
|
||||
}
|
||||
|
||||
// The link into the netns that re-enters the router from the LAN.
|
||||
if (want_loop) {
|
||||
sec('dawnline_loop', 'zone', {
|
||||
name: LOOP_ZONE, device: [ net.INTERNAL.transit ],
|
||||
input: 'REJECT', output: 'ACCEPT', forward: 'REJECT',
|
||||
});
|
||||
// The Home-only resolver in the netns reaches its upstream DNS this way.
|
||||
sec('dawnline_loop_wan', 'forwarding', { src: LOOP_ZONE, dest: portal_zone ?? 'wan' });
|
||||
}
|
||||
|
||||
// Never open SSH, DNS or the LuCI web server for the portal, whatever the settings say.
|
||||
let portal_port_ok = (p) => p >= 1 && p <= 65535 && index([ 22, 53, 80, 443 ], p) < 0;
|
||||
if (m.settings.portal_enabled && portal_port_ok(m.settings.portal_port)) {
|
||||
let wan = portal_zone ?? 'wan';
|
||||
sec('dawnline_portal', 'rule', {
|
||||
name: 'Dawnline-Portal', src: wan, proto: 'tcp',
|
||||
dest_port: m.settings.portal_port, target: 'ACCEPT',
|
||||
});
|
||||
// IP addresses in links: plain HTTP next to the HTTPS port, and 80 forwarded to it.
|
||||
if (core.portal_http(m) && portal_port_ok(core.portal_http_port(m))) {
|
||||
sec('dawnline_portal_http', 'rule', {
|
||||
name: 'Dawnline-Portal-HTTP', src: wan, proto: 'tcp',
|
||||
dest_port: core.portal_http_port(m), target: 'ACCEPT',
|
||||
});
|
||||
}
|
||||
// The portal keeps its own port: 80 and 443 stay with the LuCI web server.
|
||||
}
|
||||
|
||||
let stale = [];
|
||||
c.foreach('firewall', null, (s) => {
|
||||
if (substr(s['.name'], 0, 9) == 'dawnline_' && !want[s['.name']])
|
||||
push(stale, s['.name']);
|
||||
});
|
||||
for (let s in stale) {
|
||||
c.delete('firewall', s);
|
||||
changed = true;
|
||||
}
|
||||
if (dry)
|
||||
return changed;
|
||||
|
||||
if (changed) {
|
||||
c.commit('firewall');
|
||||
ack_config([ 'firewall' ]);
|
||||
system('fw4 -q reload');
|
||||
system("logger -t dawnline 'firewall updated'");
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
|
||||
/**
|
||||
* For the watchdog: what is wrong with Dawnline's firewall, or null.
|
||||
* 'off': fw4 is not running at all (not ours to start); 'changed': the config
|
||||
* lost or changed Dawnline's sections; 'not loaded': fw4 runs without them.
|
||||
*/
|
||||
export function drift(m) {
|
||||
let t = sh_out('nft -t list table inet fw4 2>/dev/null') ?? '';
|
||||
if (t == '')
|
||||
return 'off';
|
||||
if (sync(m, true))
|
||||
return 'changed';
|
||||
// Named rules show up in fw4's ruleset as comments.
|
||||
let names = [];
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.enabled && length(core.tunnels(srv)))
|
||||
push(names, `Dawnline-${srv.ifname}`);
|
||||
if (m.settings.portal_enabled)
|
||||
push(names, 'Dawnline-Portal');
|
||||
for (let n in names)
|
||||
if (index(t, `${n}"`) < 0)
|
||||
return 'not loaded';
|
||||
return null;
|
||||
};
|
||||
|
||||
const MARK_ALL = 0xffffffff;
|
||||
// "1000: from all fwmark 0x1 lookup 100", or "fwmark 0x1/0xff". A module
|
||||
// constant, compiled once, not for each rule.
|
||||
const MARK_RULE = /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/;
|
||||
|
||||
function hx(n) {
|
||||
return sprintf('0x%x', n);
|
||||
}
|
||||
|
||||
/**
|
||||
* Policy rules that send marked traffic into a table with `local default`,
|
||||
* the way transparent proxies capture the router's own traffic:
|
||||
* [{ pref, mark, mask, table }], one per mark and mask.
|
||||
*/
|
||||
export function proxy_diverts() {
|
||||
let out = [], seen = {};
|
||||
for (let fam in [ '-4', '-6' ])
|
||||
for (let line in split(sh_out(`ip ${fam} rule show 2>/dev/null`) ?? '', '\n')) {
|
||||
let mm = match(line, MARK_RULE);
|
||||
if (!mm || +mm[1] >= 32766)
|
||||
continue;
|
||||
let d = { pref: +mm[1], mark: hex(mm[2]), mask: mm[4] ? hex(mm[4]) : MARK_ALL, table: mm[5] };
|
||||
let key = `${d.mark}/${d.mask}`;
|
||||
if (seen[key] || !match(sh_out(`ip ${fam} route show table ${d.table} 2>/dev/null`) ?? '', /(^|\n)local default/))
|
||||
continue;
|
||||
seen[key] = true;
|
||||
push(out, d);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** A divert as `ip rule` shows it, for people: "pref 1000 fwmark 0x1 → table 100". */
|
||||
export function divert_str(d) {
|
||||
return `pref ${d.pref} fwmark ${hx(d.mark)}${d.mask == MARK_ALL ? '' : `/${hx(d.mask)}`} → table ${d.table}`;
|
||||
};
|
||||
|
||||
/** Ports Dawnline answers on from the outside: { tcp: [...], udp: [...] }. */
|
||||
function reply_ports(m) {
|
||||
let p = { tcp: [], udp: [] };
|
||||
let ok = (n) => n >= 1 && n <= 65535;
|
||||
if (m.settings.portal_enabled) {
|
||||
push(p.tcp, +m.settings.portal_port);
|
||||
if (core.portal_http(m))
|
||||
push(p.tcp, +core.portal_http_port(m));
|
||||
}
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key && srv.enabled)
|
||||
push(p.udp, +srv.port);
|
||||
return { tcp: uniq(filter(p.tcp, ok)), udp: uniq(filter(p.udp, ok)) };
|
||||
}
|
||||
|
||||
/** The reply table for these diverts, or '' when there is nothing to keep out of them. */
|
||||
function reply_script(m, diverts) {
|
||||
let p = reply_ports(m);
|
||||
if (!length(diverts) || !length(p.tcp) && !length(p.udp))
|
||||
return '';
|
||||
let t = [];
|
||||
push(t, `table inet ${REPLY_TABLE} {`);
|
||||
push(t, ' chain out {');
|
||||
// After the proxies' own output chains (they mark at mangle, -150).
|
||||
push(t, ' type route hook output priority filter + 10; policy accept;');
|
||||
for (let proto in [ 'tcp', 'udp' ]) {
|
||||
if (!length(p[proto]))
|
||||
continue;
|
||||
for (let d in diverts)
|
||||
// Only the divert's bits: other marks on the packet (multi-WAN) stay.
|
||||
push(t, ` ${proto} sport { ${join(', ', p[proto])} } ` + (d.mask == MARK_ALL
|
||||
? `meta mark ${hx(d.mark)} meta mark set 0x0`
|
||||
: `meta mark & ${hx(d.mask)} == ${hx(d.mark)} meta mark set meta mark & ${hx(~d.mask & MARK_ALL)}`));
|
||||
}
|
||||
push(t, ' }');
|
||||
push(t, '}');
|
||||
return join('\n', t) + '\n';
|
||||
}
|
||||
|
||||
function reply_loaded() {
|
||||
return system(`nft list table inet ${REPLY_TABLE} >/dev/null 2>&1`) == 0;
|
||||
}
|
||||
|
||||
/** Are the answers from our ports kept out of these diverts right now (watchdog)? */
|
||||
export function reply_ok(m, diverts) {
|
||||
let s = reply_script(m, diverts);
|
||||
return s == '' || (s == readfile(REPLY_SIG) && reply_loaded());
|
||||
};
|
||||
|
||||
/**
|
||||
* Keep the reply table in step with our ports and the proxies' diverts (apply
|
||||
* and every agent tick: a proxy may start after Dawnline). Cheap when nothing changed.
|
||||
*/
|
||||
export function sync_reply_routes(m) {
|
||||
// Rules of older versions ("90: from all iif lo ipproto udp sport 51820 lookup main", once without "iif lo").
|
||||
for (let fam in [ '-4', '-6' ])
|
||||
for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) {
|
||||
let mm = match(line, /(iif lo )?ipproto (tcp|udp) sport ([0-9]+) lookup main/);
|
||||
if (mm)
|
||||
sh(`ip ${fam} rule del priority ${PREF_REPLY}${mm[1] ? ' iif lo' : ''} ipproto ${mm[2]} sport ${mm[3]} lookup main 2>/dev/null`);
|
||||
}
|
||||
let s = reply_script(m, proxy_diverts());
|
||||
if (s == '') {
|
||||
if (reply_loaded())
|
||||
system(`nft delete table inet ${REPLY_TABLE} 2>/dev/null`);
|
||||
unlink(REPLY_SIG);
|
||||
return;
|
||||
}
|
||||
if (s == readfile(REPLY_SIG) && reply_loaded())
|
||||
return;
|
||||
let err = nft.load(`table inet ${REPLY_TABLE}\ndelete table inet ${REPLY_TABLE}\n${s}`);
|
||||
if (err) {
|
||||
unlink(REPLY_SIG);
|
||||
system(`logger -t dawnline -p user.err ${q('reply table: ' + err)}`);
|
||||
return;
|
||||
}
|
||||
write_file(REPLY_SIG, s, 0o644);
|
||||
};
|
||||
@@ -1,14 +1,21 @@
|
||||
// Dawnline — city-level locations for the admin map.
|
||||
//
|
||||
// Client addresses are looked up once with a third-party service (ipwho.is,
|
||||
// ipapi.co as fallback) and cached in DATA_DIR/geo.json. Only the agent
|
||||
// performs lookups, a few per minute at most; the UI reads the cache.
|
||||
// ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on
|
||||
// flash (DATA_DIR/geo.json) by flush() about hourly, like the usage
|
||||
// counters. Only the agent performs lookups, in a child process (the network
|
||||
// may take seconds; neither its watcher nor its tick waits for them) and
|
||||
// merges them into the cache itself; the UI reads the cache.
|
||||
|
||||
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR } from 'dawnline.util';
|
||||
import { stat } from 'fs';
|
||||
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util';
|
||||
|
||||
const CACHE = `${DATA_DIR}/geo.json`;
|
||||
const CACHE = `${RUN_DIR}/geo.json`;
|
||||
const SAVED = `${DATA_DIR}/geo.json`;
|
||||
const TTL = 30 * 86400;
|
||||
const RETRY = 86400;
|
||||
// Entries kept at least; addresses still shown are never pushed out (merge).
|
||||
const CAP = 500;
|
||||
|
||||
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
|
||||
const PRIVATE4 = map([ [ '0.0.0.0', 8 ], [ '10.0.0.0', 8 ], [ '100.64.0.0', 10 ], [ '127.0.0.0', 8 ], [ '169.254.0.0', 16 ],
|
||||
@@ -30,16 +37,30 @@ export function is_public(ip) {
|
||||
};
|
||||
|
||||
export function load() {
|
||||
return read_json(CACHE, null) ?? { ips: {}, home: null };
|
||||
return read_json(CACHE, null) ?? read_json(SAVED, null) ?? { ips: {}, home: null };
|
||||
};
|
||||
|
||||
/** The live copy (tmpfs); flush() puts it on flash. */
|
||||
export function save(cache) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(CACHE, cache, 0o600);
|
||||
};
|
||||
|
||||
/** Copy the live cache to flash when it is newer (the agent, about hourly and on a clean stop). */
|
||||
export function flush() {
|
||||
let live = stat(CACHE);
|
||||
if (!live || live.mtime <= (stat(SAVED)?.mtime ?? 0))
|
||||
return false;
|
||||
let c = read_json(CACHE, null);
|
||||
if (!c)
|
||||
return false;
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(SAVED, c, 0o600);
|
||||
return true;
|
||||
};
|
||||
|
||||
function fetch_json(url) {
|
||||
let out = sh_out(`uclient-fetch -q -T 8 -O - ${q(url)}`);
|
||||
let out = sh_out(`uclient-fetch -q -T 5 -O - ${q(url)}`);
|
||||
if (!out)
|
||||
return null;
|
||||
try {
|
||||
@@ -79,36 +100,69 @@ export function lookup(provider, ip) {
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve up to `max` addresses that are missing or stale. Returns true when
|
||||
* the cache changed (the caller saves it).
|
||||
* The public addresses of `ips` the cache does not know or knows from too
|
||||
* long ago (a failed lookup is retried after a day), once each and in order.
|
||||
* Returns an empty array when there is nothing to look up.
|
||||
*/
|
||||
export function resolve(settings, cache, ips, max) {
|
||||
let now = time(), changed = false, done = 0;
|
||||
export function stale(cache, ips, ts) {
|
||||
let now = ts ?? time(), out = [], seen = {};
|
||||
for (let ip in ips) {
|
||||
if (done >= max)
|
||||
break;
|
||||
if (!is_public(ip))
|
||||
if (seen[ip] || !is_public(ip))
|
||||
continue;
|
||||
seen[ip] = true;
|
||||
let c = cache.ips[ip];
|
||||
if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL)))
|
||||
continue;
|
||||
let r = lookup(settings.geo_provider, ip);
|
||||
done++;
|
||||
changed = true;
|
||||
if (r) {
|
||||
delete r.ip;
|
||||
r.ts = now;
|
||||
cache.ips[ip] = r;
|
||||
}
|
||||
else
|
||||
cache.ips[ip] = { fail: now };
|
||||
push(out, ip);
|
||||
}
|
||||
// Keep the cache bounded: drop the oldest entries beyond 500.
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* Look up at most `max` of `ips`, within `budget` seconds (each lookup may
|
||||
* wait on the network). Returns { ip: place, or false when the services had
|
||||
* nothing } for the ones tried. Network only, no cache: the agent runs it in
|
||||
* a child process and merges the result itself.
|
||||
*/
|
||||
export function lookup_all(provider, ips, max, budget) {
|
||||
let started = time(), out = {}, done = 0;
|
||||
for (let ip in ips) {
|
||||
if (done >= max || (budget != null && time() - started >= budget))
|
||||
break;
|
||||
let r = lookup(provider, ip);
|
||||
done++;
|
||||
if (r)
|
||||
delete r.ip;
|
||||
out[ip] = r ?? false;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* Put lookup_all() results into the cache. Returns true when the cache
|
||||
* changed (the caller saves it). `shown` is what is still on the map: the
|
||||
* cache is kept bounded by dropping other entries only, oldest first, so a
|
||||
* lookup is never repeated for an address that is still on the map.
|
||||
*/
|
||||
export function merge(cache, found, shown, ts) {
|
||||
let now = ts ?? time(), changed = false;
|
||||
for (let ip, r in found) {
|
||||
if (!is_public(ip))
|
||||
continue;
|
||||
cache.ips[ip] = r ? { ...r, ts: now } : { fail: now };
|
||||
changed = true;
|
||||
}
|
||||
let keep = {};
|
||||
for (let ip in shown)
|
||||
keep[ip] = true;
|
||||
let all = keys(cache.ips);
|
||||
if (length(all) > 500) {
|
||||
all = sort(all, (a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
|
||||
for (let i = 0; i < length(all) - 500; i++)
|
||||
delete cache.ips[all[i]];
|
||||
if (length(all) > CAP) {
|
||||
let other = sort(filter(all, (ip) => !keep[ip]),
|
||||
(a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
|
||||
for (let i = 0; i < length(all) - CAP && i < length(other); i++) {
|
||||
delete cache.ips[other[i]];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
@@ -130,6 +184,13 @@ export function place(cache, ip) {
|
||||
return (c && !c.fail) ? c : null;
|
||||
};
|
||||
|
||||
/** "City · ISP" for the activity log; null for no place. */
|
||||
export function label(pl) {
|
||||
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
|
||||
};
|
||||
|
||||
export function clear() {
|
||||
save({ ips: {}, home: null });
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(SAVED, { ips: {}, home: null }, 0o600);
|
||||
};
|
||||
@@ -0,0 +1,227 @@
|
||||
// Dawnline — GitHub for the updater and the Components tab: API calls with a
|
||||
// short cache, releases (with each asset's sha256), the changes between two
|
||||
// tags, and verified downloads.
|
||||
//
|
||||
// Trust: the API is only ever asked directly (TLS to api.github.com). Files
|
||||
// may come through a mirror when GitHub is unreachable, but only when their
|
||||
// sha256 is known from the API, and a file is kept only if it matches.
|
||||
|
||||
import { stat, popen, access } from 'fs';
|
||||
import { q, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
/** Prefixes that fetch github.com files when GitHub itself is unreachable. */
|
||||
export const MIRRORS = [ 'https://ghfast.top/', 'https://gh-proxy.com/', 'https://ghproxy.net/' ];
|
||||
|
||||
function run(cmd) {
|
||||
let p = popen(cmd + ' 2>&1', 'r');
|
||||
if (!p)
|
||||
return { code: 127, out: '' };
|
||||
let out = p.read('all') ?? '';
|
||||
return { code: p.close(), out };
|
||||
}
|
||||
|
||||
function have_curl() {
|
||||
return access('/usr/bin/curl', 'x');
|
||||
}
|
||||
|
||||
/**
|
||||
* GET a URL: { status, body } (status 0 when there was no answer). curl gives
|
||||
* the HTTP status, so a 403 rate limit is told apart from a dead network.
|
||||
*/
|
||||
function get(url, timeout) {
|
||||
timeout ??= 12;
|
||||
if (have_curl()) {
|
||||
let r = run(`curl -sSL --connect-timeout 6 --max-time ${+timeout} -H 'Accept: application/vnd.github+json' -A Dawnline -w '\\n%{http_code}' ${q(url)}`);
|
||||
// The body, then the status on the last line (-w).
|
||||
let i = rindex(r.out, '\n');
|
||||
let code = i < 0 ? '' : substr(r.out, i + 1);
|
||||
return match(code, /^[0-9][0-9][0-9]$/) ? { status: +code, body: substr(r.out, 0, i) } : { status: 0, body: '' };
|
||||
}
|
||||
let r = run(`uclient-fetch -q -T ${+timeout} -O - ${q(url)}`);
|
||||
return { status: r.code == 0 ? 200 : 0, body: r.code == 0 ? r.out : '' };
|
||||
}
|
||||
|
||||
/** JSON from the GitHub API, or null when GitHub did not answer; dies on a rate limit or another API error. */
|
||||
function api_json(url) {
|
||||
let r = get(url);
|
||||
if (r.status == 0)
|
||||
return null;
|
||||
let j = null;
|
||||
try {
|
||||
j = json(r.body);
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
if (r.status == 403 || r.status == 429 || (type(j) == 'object' && match(j.message ?? '', /rate limit/i)))
|
||||
die(_('GitHub API rate limit reached: try again in an hour.'));
|
||||
if (r.status == 404)
|
||||
return null;
|
||||
if (r.status >= 400)
|
||||
die(sprintf(_('GitHub: %s'), j?.message ?? `HTTP ${r.status}`));
|
||||
return j;
|
||||
}
|
||||
|
||||
function cached(key, ttl, fn) {
|
||||
let path = `${RUN_DIR}/gh-${replace(key, /[^A-Za-z0-9_.-]/g, '_')}.json`;
|
||||
let c = read_json(path, null);
|
||||
if (c && time() - (c.at ?? 0) < ttl)
|
||||
return c.data;
|
||||
let data = fn();
|
||||
if (data != null) {
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(path, { at: time(), data });
|
||||
}
|
||||
return data ?? c?.data;
|
||||
}
|
||||
|
||||
/* ---------- releases ---------- */
|
||||
|
||||
function slim(x) {
|
||||
let digests = {};
|
||||
for (let a in x.assets ?? [])
|
||||
if (match(a.digest ?? '', /^sha256:[0-9a-f]{64}$/))
|
||||
digests[a.name] = substr(a.digest, 7);
|
||||
return {
|
||||
tag: x.tag_name, name: x.name ?? x.tag_name, published: x.published_at ?? null,
|
||||
prerelease: !!x.prerelease, url: x.html_url ?? null, body: substr(x.body ?? '', 0, 12000),
|
||||
assets: map(x.assets ?? [], (a) => a.name), digests,
|
||||
};
|
||||
}
|
||||
|
||||
/** Releases of a repository, newest first, five per page (drafts skipped). */
|
||||
export function releases(rp, page) {
|
||||
page = page ?? 1;
|
||||
return cached(`rel-${rp}-${page}`, 600, () => {
|
||||
let j = api_json(`https://api.github.com/repos/${rp}/releases?per_page=5&page=${+page}`);
|
||||
return type(j) == 'array' ? map(filter(j, (x) => !x.draft), slim) : null;
|
||||
}) ?? [];
|
||||
};
|
||||
|
||||
/** One release by tag (notes, assets and their sha256), or null. */
|
||||
export function release(rp, tag) {
|
||||
return cached(`tag-${rp}-${tag}`, 600, () => {
|
||||
let j = api_json(`https://api.github.com/repos/${rp}/releases/tags/${tag}`);
|
||||
return type(j) == 'object' && j.tag_name ? slim(j) : null;
|
||||
});
|
||||
};
|
||||
|
||||
/** The sha256 GitHub publishes for a release file, or null (unknown: no mirrors for it). */
|
||||
export function asset_sha256(rp, tag, name) {
|
||||
try {
|
||||
return release(rp, tag)?.digests?.[name] ?? null;
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/** The latest stable release; the /releases/latest redirect when the API is out of reach. */
|
||||
export function latest(rp) {
|
||||
let r = null;
|
||||
try {
|
||||
r = cached(`latest-${rp}`, 300, () => {
|
||||
let j = api_json(`https://api.github.com/repos/${rp}/releases/latest`);
|
||||
return type(j) == 'object' && j.tag_name ? slim(j) : null;
|
||||
});
|
||||
}
|
||||
catch (e) {}
|
||||
if (r)
|
||||
return r;
|
||||
if (have_curl()) {
|
||||
let o = run(`curl -sI --connect-timeout 15 --max-time 30 -o /dev/null -w '%{redirect_url}' ${q('https://github.com/' + rp + '/releases/latest')}`);
|
||||
let m = match(trim(o.out), /\/releases\/tag\/([^\/?#]+)$/);
|
||||
if (m)
|
||||
return { tag: m[1], name: m[1], published: null, prerelease: false, url: `https://github.com/${rp}/releases/tag/${m[1]}`, body: '', assets: [], digests: {} };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/* ---------- what changed ---------- */
|
||||
|
||||
/**
|
||||
* What changed in a commit message, as points: release commits ("Dawnline
|
||||
* 0.3.1") list their changes as "- " lines in the body; other commits are
|
||||
* their title. Wrapped points are joined back into one line.
|
||||
*/
|
||||
export function points(msg) {
|
||||
let lines = split(msg ?? '', '\n');
|
||||
let title = trim(lines[0] ?? '');
|
||||
if (match(title, /^Merge /))
|
||||
return [];
|
||||
let out = [], cur = null;
|
||||
for (let i = 1; i < length(lines); i++) {
|
||||
let m = match(lines[i], /^\s*[-*]\s+(.*)$/);
|
||||
if (m) {
|
||||
if (cur != null)
|
||||
push(out, cur);
|
||||
cur = trim(m[1]);
|
||||
}
|
||||
else if (cur != null && match(lines[i], /^\s+\S/))
|
||||
cur += ' ' + trim(lines[i]);
|
||||
else if (cur != null) {
|
||||
push(out, cur);
|
||||
cur = null;
|
||||
}
|
||||
}
|
||||
if (cur != null)
|
||||
push(out, cur);
|
||||
if (!length(out) && !match(title, /^(Dawnline )?v?[0-9]+\.[0-9]+(\.[0-9]+)?$/) && title != '')
|
||||
push(out, title);
|
||||
return out;
|
||||
};
|
||||
|
||||
/** The changes from one tag to another, newest first: commit by commit, or the release's own commit. */
|
||||
export function changes(rp, base, head) {
|
||||
return cached(`changes-${rp}-${base}-${head}`, 600, () => {
|
||||
let out = [];
|
||||
let j = base ? api_json(`https://api.github.com/repos/${rp}/compare/${base}...${head}`) : null;
|
||||
if (type(j?.commits) == 'array') {
|
||||
for (let i = length(j.commits) - 1; i >= 0; i--)
|
||||
for (let p in points(j.commits[i]?.commit?.message))
|
||||
push(out, p);
|
||||
return slice(out, 0, 20);
|
||||
}
|
||||
let c = api_json(`https://api.github.com/repos/${rp}/commits/${head}`);
|
||||
return c?.commit ? slice(points(c.commit.message), 0, 20) : null;
|
||||
}) ?? [];
|
||||
};
|
||||
|
||||
/* ---------- downloads ---------- */
|
||||
|
||||
export function sha256(path) {
|
||||
return match(run(`sha256sum ${q(path)}`).out, /^([0-9a-f]{64})/)?.[1];
|
||||
};
|
||||
|
||||
/**
|
||||
* Download to a file. o: { sha256, mirrors, log }. Direct first; mirrors
|
||||
* only when the sha256 is known (from the API) and mirrors are allowed. A
|
||||
* file that does not match the sha256 is thrown away and the next source is
|
||||
* tried. Returns the URL that worked, or null.
|
||||
*/
|
||||
export function download(url, dest, o) {
|
||||
o ??= {};
|
||||
let want = o.sha256 ? lc(o.sha256) : null;
|
||||
let tries = [ url ];
|
||||
if (want && o.mirrors && match(url, /^https:\/\/(github\.com|raw\.githubusercontent\.com)\//))
|
||||
for (let m in MIRRORS)
|
||||
push(tries, m + url);
|
||||
for (let i, u in tries) {
|
||||
let host = replace(u, /^https:\/\/([^\/]+)\/.*$/, '$1');
|
||||
if (i > 0)
|
||||
o.log?.(sprintf(_('Trying mirror %s'), host));
|
||||
let r = have_curl()
|
||||
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 1 -o ${q(dest)} ${q(u)}`)
|
||||
: run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(u)}`);
|
||||
if (r.code == 0 && (stat(dest)?.size ?? 0) > 0) {
|
||||
if (!want || sha256(dest) == want)
|
||||
return u;
|
||||
o.log?.(sprintf(_("Warning: %s sent a file that does not match GitHub's sha256, discarded"), host));
|
||||
}
|
||||
system(`rm -f ${q(dest)}`);
|
||||
if (i == 0 && length(tries) > 1)
|
||||
o.log?.(_('GitHub did not answer, trying mirrors'));
|
||||
}
|
||||
return null;
|
||||
};
|
||||
@@ -0,0 +1,758 @@
|
||||
// Dawnline — Health: what the router has and lacks (packages, listeners,
|
||||
// networks), the checks shown on Diagnostics → Health, and their fixes.
|
||||
// The checks' texts are in the language of the call (dawnline.i18n).
|
||||
|
||||
import { readfile, stat, lsdir } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { _, N_ } from 'dawnline.i18n';
|
||||
import { q, sh, sh_out, parse_cidr, cidr_overlaps, ip2int, in_cidr, file_exists, cloudflare_ip } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as fw from 'dawnline.fw';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
import * as lookup from 'dawnline.lookup';
|
||||
import * as pc from 'dawnline.portalcert';
|
||||
|
||||
/* ---------- what the router has ---------- */
|
||||
|
||||
/**
|
||||
* Packages a feature needs that are missing, by feature: https (the portal: openssl-util and any
|
||||
* TLS module for uhttpd), acme (Let's Encrypt certificates), home (the home-like link), awg
|
||||
* (AmneziaWG: the tools with netifd's protocol script, and the kernel module). Checked by
|
||||
* files, so it is cheap enough for every page load.
|
||||
*/
|
||||
export function needs() {
|
||||
let tls = false;
|
||||
for (let d in [ '/lib', '/usr/lib' ])
|
||||
for (let f in lsdir(d) ?? [])
|
||||
if (substr(f, 0, 16) == 'libustream-ssl.s')
|
||||
tls = true;
|
||||
let kver = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||
let kmod = (name) => stat(`/sys/module/${name}`) != null || file_exists(`/lib/modules/${kver}/${name}.ko`);
|
||||
let miss = (list) => map(filter(list, (x) => !x[0]), (x) => x[1]);
|
||||
return {
|
||||
https: miss([ [ file_exists('/usr/bin/openssl'), 'openssl-util' ], [ tls, 'libustream-openssl' ] ]),
|
||||
acme: miss([ [ file_exists('/usr/lib/acme/client/acme.sh'), 'acme' ], [ file_exists('/usr/lib/acme/client/dnsapi/dns_cf.sh'), 'acme-acmesh-dnsapi' ],
|
||||
[ file_exists('/www/luci-static/resources/view/acme.js'), 'luci-app-acme' ] ]),
|
||||
home: miss([ [ file_exists('/usr/libexec/ip-full'), 'ip-full' ], [ kmod('veth'), 'kmod-veth' ] ]),
|
||||
// amneziawg-tools ships both the awg tool and netifd's protocol script.
|
||||
awg: miss([ [ file_exists('/usr/bin/awg') && file_exists('/lib/netifd/proto/amneziawg.sh'), 'amneziawg-tools' ],
|
||||
[ kmod('amneziawg'), 'kmod-amneziawg' ] ]),
|
||||
};
|
||||
};
|
||||
|
||||
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
|
||||
// A module constant, compiled once: a literal in the loop would be compiled
|
||||
// again for every socket (0.12 ms each on the WR3000P, some 90 sockets a call).
|
||||
const UDP_UNCONNECTED = /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /;
|
||||
|
||||
/** UDP ports an unconnected socket is bound to (IPv4 and IPv6): nothing else can listen there. */
|
||||
export function udp_bound() {
|
||||
let out = {};
|
||||
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
|
||||
for (let line in split(readfile(f) ?? '', '\n')) {
|
||||
let m = match(line, UDP_UNCONNECTED);
|
||||
if (m)
|
||||
out[hex(m[1])] = true;
|
||||
}
|
||||
return map(keys(out), (k) => +k);
|
||||
};
|
||||
|
||||
// netstat's columns and the port of "0.0.0.0:53" / ":::53". Module constants,
|
||||
// compiled once, not for each socket.
|
||||
const BLANKS = /[ \t]+/, PORT_SUFFIX = /:([0-9]+)$/;
|
||||
|
||||
/**
|
||||
* Programs on 'tcp' or 'udp' ports, our portal left out: { port: "dnsmasq" }.
|
||||
* Kernel sockets (a tunnel's) have no name.
|
||||
*/
|
||||
function port_programs(proto) {
|
||||
let out = {};
|
||||
for (let line in split(sh_out(`netstat -ln${proto == 'tcp' ? 't' : 'u'}p 2>/dev/null`) ?? '', '\n')) {
|
||||
let f = split(trim(line), BLANKS);
|
||||
if (f[0] != proto && f[0] != `${proto}6`)
|
||||
continue;
|
||||
let m = match(f[3] ?? '', PORT_SUFFIX);
|
||||
let owner = split(f[length(f) - 1], '/');
|
||||
if (!m || !owner[1] || out[m[1]])
|
||||
continue;
|
||||
// Our own portal runs as a dedicated uhttpd instance.
|
||||
if (index(readfile(`/proc/${+owner[0]}/cmdline`) ?? '', '/usr/share/dawnline/portal') >= 0)
|
||||
continue;
|
||||
out[m[1]] = owner[1];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function udp_port_programs() {
|
||||
return port_programs('udp');
|
||||
};
|
||||
|
||||
export function tcp_port_programs() {
|
||||
return port_programs('tcp');
|
||||
};
|
||||
|
||||
export function udp_listening(port) {
|
||||
return index(udp_bound(), +port) >= 0;
|
||||
};
|
||||
|
||||
export function tcp_listening(port) {
|
||||
let hex = sprintf(':%04X ', port);
|
||||
for (let f in [ '/proc/net/tcp', '/proc/net/tcp6' ])
|
||||
for (let line in split(readfile(f) ?? '', '\n'))
|
||||
// state 0A = LISTEN
|
||||
if (index(line, hex) > 0 && match(line, / 0A /))
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
/** Processes other than our portal listening on a TCP port: [ "name" ]. */
|
||||
export function tcp_port_owners(port) {
|
||||
let out = sh_out(`netstat -lntp 2>/dev/null | awk '$4 ~ /:${+port}$/ {print $7}'`) ?? '';
|
||||
let owners = [];
|
||||
for (let o in split(out, '\n')) {
|
||||
let name = split(o, '/')[1];
|
||||
if (!name || index(owners, name) >= 0)
|
||||
continue;
|
||||
// Our own portal runs as a dedicated uhttpd instance.
|
||||
let pid = +split(o, '/')[0];
|
||||
let cmd = readfile(`/proc/${pid}/cmdline`) ?? '';
|
||||
if (index(cmd, '/usr/share/dawnline/portal') >= 0)
|
||||
continue;
|
||||
push(owners, name);
|
||||
}
|
||||
return owners;
|
||||
};
|
||||
|
||||
export function service_running(name, instance) {
|
||||
let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`);
|
||||
if (!s)
|
||||
return false;
|
||||
try {
|
||||
return !!json(s)?.[name]?.instances?.[instance]?.running;
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** IPv4 networks of netifd interfaces: [{ iface, cidr }], without the given server's tunnel. */
|
||||
function other_subnets(srv_id) {
|
||||
let out = [];
|
||||
let st = sh_out('ubus call network.interface dump 2>/dev/null');
|
||||
let d = null;
|
||||
try {
|
||||
d = st ? json(st) : null;
|
||||
}
|
||||
catch (e) {
|
||||
d = null;
|
||||
}
|
||||
let ours = {};
|
||||
for (let id, s in core.load().servers)
|
||||
ours[s.ifname] = id;
|
||||
for (let i in d?.interface ?? []) {
|
||||
if (srv_id != null && ours[i.interface] == srv_id)
|
||||
continue;
|
||||
if (srv_id === false && ours[i.interface] != null)
|
||||
continue;
|
||||
for (let a in i['ipv4-address'] ?? [])
|
||||
push(out, { iface: i.interface, cidr: `${a.address}/${a.mask}` });
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Subnets in use on the router except the given server's (null: all of them). */
|
||||
/** The router's IPv4 networks, Dawnline's tunnels included: [{ iface, cidr }]. */
|
||||
export function networks() {
|
||||
return other_subnets(null);
|
||||
};
|
||||
|
||||
export function used_subnets(except_srv) {
|
||||
return map(other_subnets(except_srv), (x) => x.cidr);
|
||||
};
|
||||
|
||||
/** Subnets of interfaces that are not Dawnline tunnels (an imported config is checked against these). */
|
||||
export function foreign_subnets() {
|
||||
return used_subnets(false);
|
||||
};
|
||||
|
||||
/* ---------- checks ---------- */
|
||||
|
||||
/*
|
||||
* Checks are named for the healthy state ("Clock is set"); a failed one also
|
||||
* gets the problem in words for notices ("Clock isn't set"), passed with it.
|
||||
* A server's checks carry its name after both (` (Home)`, with several servers).
|
||||
*/
|
||||
function check(id, title, status, detail, fix, problem) {
|
||||
let bad = status == 'warn' || status == 'error';
|
||||
return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? title) : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers from our ports and the proxies that would swallow them (fw.sync_reply_routes):
|
||||
* { ok, diverts: ["pref 1000 fwmark 0x1 → table 100"] }.
|
||||
*/
|
||||
function replies(m) {
|
||||
let d = fw.proxy_diverts();
|
||||
return { ok: fw.reply_ok(m, d), diverts: map(d, fw.divert_str) };
|
||||
}
|
||||
|
||||
function reply_check(id, title, problem, proto, port, r) {
|
||||
let via = join(', ', r.diverts);
|
||||
let from = `${uc(proto)} ${port}`;
|
||||
return check(id, title, r.ok ? 'ok' : 'error',
|
||||
!r.ok ? sprintf(_('Answers from %s are swallowed by a proxy on the router (%s): clients get no reply.'), from, via)
|
||||
: length(r.diverts) ? sprintf(_('Answers from %s go straight out. A proxy on the router diverts its own traffic (%s); these answers skip it.'), from, via)
|
||||
: sprintf(_('Answers from %s go straight out.'), from),
|
||||
r.ok ? null : 'apply', problem);
|
||||
}
|
||||
|
||||
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
|
||||
|
||||
/** What kind of IPv4 the WAN has: public, cgnat (100.64/10), private (behind another router), or none. */
|
||||
export function wan_kind(wan) {
|
||||
let wc = wan ? ip2int(wan) : null;
|
||||
if (wc == null)
|
||||
return 'none';
|
||||
if (in_cidr(wc, PRIVATE[0]))
|
||||
return 'cgnat';
|
||||
return length(filter(PRIVATE, (c) => in_cidr(wc, c))) ? 'private' : 'public';
|
||||
};
|
||||
|
||||
const HEX = '0123456789abcdef';
|
||||
|
||||
// An IPv6 address as its 32 hex digits, so two spellings of one address
|
||||
// compare equal (2001:DB8::1, 2001:db8:0::1, as typed or as a tool prints
|
||||
// it); null when it is none. No regex: the router's addresses and a name's
|
||||
// AAAA records go through it on every look.
|
||||
function ip6_full(s) {
|
||||
if (type(s) != 'string')
|
||||
return null;
|
||||
let halves = split(lc(s), '::');
|
||||
if (length(halves) > 2)
|
||||
return null;
|
||||
let head = halves[0] != '' ? split(halves[0], ':') : [];
|
||||
let tail = length(halves) == 2 && halves[1] != '' ? split(halves[1], ':') : [];
|
||||
let gap = 8 - length(head) - length(tail);
|
||||
if (length(halves) == 2 ? gap < 1 : gap != 0)
|
||||
return null;
|
||||
let groups = [ ...head ];
|
||||
for (let i = 0; i < gap; i++)
|
||||
push(groups, '0');
|
||||
push(groups, ...tail);
|
||||
let out = '';
|
||||
for (let g in groups) {
|
||||
if (length(g) < 1 || length(g) > 4 || ltrim(g, HEX) != '')
|
||||
return null;
|
||||
out += substr(`0000${g}`, length(g));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The router's public IPv6 addresses in `ip -6 -j addr show scope global`
|
||||
* output (`links`), on any interface: a DDNS client may publish the LAN's
|
||||
* address from the delegated prefix, which reaches the router too. Unique
|
||||
* local addresses (fc00::/7: OpenWrt gives the LAN one even without IPv6
|
||||
* from the ISP) and failed duplicates do not count: nothing reaches them from
|
||||
* outside. [] when there is none.
|
||||
*/
|
||||
export function own_ipv6(links) {
|
||||
let out = [];
|
||||
for (let l in (type(links) == 'array' ? links : []))
|
||||
for (let a in l?.addr_info ?? []) {
|
||||
let k = ip6_full(a?.local);
|
||||
if (k && a.family == 'inet6' && !a.dadfailed && substr(k, 0, 2) != 'fc' && substr(k, 0, 2) != 'fd')
|
||||
push(out, a.local);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// The router's public IPv6 addresses (own_ipv6), or null when `ip` could not tell.
|
||||
function router_ipv6() {
|
||||
let out = sh_out('ip -6 -j addr show scope global');
|
||||
if (out == null)
|
||||
return null;
|
||||
try {
|
||||
let links = json(out || '[]');
|
||||
return type(links) == 'array' ? own_ipv6(links) : null;
|
||||
}
|
||||
catch (e) {
|
||||
// No JSON (an `ip` without -j): unknown, so the AAAA records get no verdict.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// What the facts are made from, read on the router.
|
||||
function endpoint_reads(srv, host) {
|
||||
let ips = host ? lookup.resolve(host) : [];
|
||||
// The router's IPv6 only when the name has some to compare with.
|
||||
return {
|
||||
ips, wan: srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan'),
|
||||
router6: length(filter(ips, (a) => ip2int(a) == null)) ? router_ipv6() : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What a public address points at, for Health and the "as you type" check on
|
||||
* the server page: { host, ips, ips4, ips6, wan, kind (wan_kind), cloudflare,
|
||||
* here (an IPv4 of it is this router's WAN), v6_only, router6 (the router's
|
||||
* public IPv6 addresses, own_ipv6; null when unknown, or not read because the
|
||||
* name has no IPv6), foreign6 (its IPv6 addresses that are none of those, all
|
||||
* of them when the router has none; null while router6 is), here6 (it has
|
||||
* IPv6 addresses and each is one of the router's) }. `reads` (a test's)
|
||||
* stands for what is read on the router: { ips, wan, router6 }.
|
||||
*/
|
||||
export function endpoint_facts(srv, host, reads) {
|
||||
let r = reads ?? endpoint_reads(srv, host);
|
||||
let ips = r.ips ?? [], wan = r.wan ?? null;
|
||||
let ips4 = filter(ips, (a) => ip2int(a) != null), ips6 = filter(ips, (a) => ip2int(a) == null);
|
||||
let own = r.router6 != null ? map(r.router6, ip6_full) : null;
|
||||
let foreign6 = own != null ? filter(ips6, (a) => index(own, ip6_full(a)) < 0) : null;
|
||||
return {
|
||||
host, ips, ips4, ips6, wan, kind: wan_kind(wan),
|
||||
cloudflare: length(filter(ips, (a) => cloudflare_ip(a))) > 0,
|
||||
here: wan != null && index(ips4, wan) >= 0,
|
||||
v6_only: !length(ips4) && length(ips6) > 0,
|
||||
router6: r.router6 ?? null, foreign6,
|
||||
here6: foreign6 != null && length(ips6) > 0 && !length(foreign6),
|
||||
};
|
||||
};
|
||||
|
||||
/*
|
||||
* The name's IPv6 addresses that do not reach this router from outside, in
|
||||
* words, or null (each is a public one of the router, or those are unknown).
|
||||
* A name with IPv4 too: devices that prefer IPv6 take these and fail, the
|
||||
* others connect.
|
||||
*/
|
||||
function aaaa_words(f) {
|
||||
let bad = f.foreign6 ?? [], n = length(bad);
|
||||
if (!n)
|
||||
return null;
|
||||
if (!length(f.router6))
|
||||
return sprintf(N_(n, '%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router.',
|
||||
'%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router.'),
|
||||
f.host, join(', ', bad));
|
||||
return sprintf(N_(n, '%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
|
||||
'%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records.'),
|
||||
f.host, join(', ', bad));
|
||||
}
|
||||
|
||||
// An IPv6-only name none of whose addresses is a public one of the router: no device connects. Null otherwise.
|
||||
function v6_only_unreached(f) {
|
||||
let n = length(f.foreign6 ?? []);
|
||||
if (!n || n < length(f.ips6))
|
||||
return null;
|
||||
if (!length(f.router6))
|
||||
return sprintf(_('%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router.'),
|
||||
f.host, join(', ', f.ips6));
|
||||
return sprintf(N_(n, '%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS.',
|
||||
'%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS.'),
|
||||
f.host, join(', ', f.ips6));
|
||||
}
|
||||
|
||||
/**
|
||||
* The facts in words, in the language of the call: { status: ok|warn|error, text }
|
||||
* (text a whole sentence). `proto_note` names what must get through ("UDP 4500").
|
||||
*/
|
||||
export function endpoint_words(f, proto_note) {
|
||||
if (!f.host)
|
||||
return { status: 'error', text: _('No public address: devices will not know where to connect.') };
|
||||
if (!length(f.ips))
|
||||
return { status: 'error', text: sprintf(_('%s does not resolve.'), f.host) };
|
||||
if (f.cloudflare)
|
||||
return { status: 'error', text: sprintf(_("%s → %s (Cloudflare). %s reaches the router only if this name is DNS-only there, or use the router's IP."),
|
||||
f.host, join(', ', f.ips), proto_note) };
|
||||
let v6 = aaaa_words(f);
|
||||
if (f.v6_only) {
|
||||
let none = v6_only_unreached(f);
|
||||
if (none != null || v6 != null)
|
||||
return { status: 'warn', text: none ?? v6 };
|
||||
return { status: f.kind == 'public' ? 'warn' : 'ok', text: f.kind == 'public'
|
||||
? sprintf(_("%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."), f.host, join(', ', f.ips6), f.wan)
|
||||
: sprintf(_('%s → %s: IPv6 only, so only devices with IPv6 connect.'), f.host, join(', ', f.ips6)) };
|
||||
}
|
||||
let v4 = null;
|
||||
if (f.kind == 'cgnat' || f.kind == 'private')
|
||||
v4 = f.kind == 'cgnat'
|
||||
? sprintf(_('The WAN address %s is CGNAT (shared by the ISP): %s cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.'), f.wan, proto_note)
|
||||
: sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note);
|
||||
else if (f.wan && !f.here)
|
||||
v4 = sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan);
|
||||
// Two separate facts, each a sentence of its own: the IPv4 one first.
|
||||
if (v4 != null || v6 != null)
|
||||
return { status: 'warn', text: join(' ', filter([ v4, v6 ], (x) => x != null)) };
|
||||
// Without the router's WAN address only the facts: names and addresses, no words.
|
||||
return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, join(', ', [ f.wan, ...(f.here6 ? f.ips6 : []) ]))
|
||||
: `${f.host} → ${join(', ', f.ips)}` };
|
||||
};
|
||||
|
||||
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
|
||||
function endpoint_check(id, title, problem, srv, host, proto_note) {
|
||||
let w = endpoint_words(endpoint_facts(srv, host), proto_note);
|
||||
return check(id, title, w.status, w.text, null, problem);
|
||||
}
|
||||
|
||||
// "1000: from all fwmark 0x1 lookup 100". A module constant, compiled once, not for each rule.
|
||||
const MARK_RULE = /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/;
|
||||
|
||||
/**
|
||||
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
|
||||
* Dawnline's (pref < 5205) whose table has a default route of its own sends
|
||||
* marked tunnel traffic straight out, past "like a home device". Reported,
|
||||
* since those marks belong to that package. [] when none.
|
||||
*/
|
||||
function policy_routing() {
|
||||
let out = [];
|
||||
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
|
||||
let mm = match(line, MARK_RULE);
|
||||
if (!mm || +mm[1] >= 5205)
|
||||
continue;
|
||||
let routes = sh_out(`ip -4 route show table ${q(mm[4])} 2>/dev/null`) ?? '';
|
||||
let def = match(routes, /(^|\n)default [^\n]*/)?.[0] ?? '';
|
||||
if (def == '' || match(def, /local default/) || index(def, `dev ${net.INTERNAL.transit}`) >= 0)
|
||||
continue;
|
||||
push(out, `pref ${mm[1]} fwmark 0x${mm[2]} → table ${mm[4]}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function no_proto() {
|
||||
return _("netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).");
|
||||
}
|
||||
|
||||
/** Free space on the overlay in KB (null when unknown). */
|
||||
function overlay_free_kb() {
|
||||
let out = sh('df -Pk /overlay 2>/dev/null || df -Pk / 2>/dev/null').out;
|
||||
let m = match(out ?? '', /\n\S+\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s/);
|
||||
return m ? +m[1] : null;
|
||||
}
|
||||
|
||||
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
|
||||
function awg_check() {
|
||||
let st = awg.load();
|
||||
let title = _('AmneziaWG installed');
|
||||
let missing = st.missing ?? [];
|
||||
if (length(missing)) {
|
||||
// The module was built for the kernel of the firmware it was installed on.
|
||||
let kc = builds.kernel_changed();
|
||||
if (kc && index(missing, 'kmod-amneziawg') >= 0)
|
||||
return check('awg', title, 'error',
|
||||
sprintf(_('The firmware changed (kernel %s → %s): the AmneziaWG build installed for it is gone. Install the build for this firmware.'), kc.was, kc.now),
|
||||
'install:awg', _('AmneziaWG needs a build for the new firmware'));
|
||||
return check('awg', title, 'error', sprintf(N_(length(missing), '%s is missing.', '%s are missing.'), join(', ', missing)), 'install:awg',
|
||||
_('AmneziaWG isn’t installed'));
|
||||
}
|
||||
if (!st.loaded) {
|
||||
// load() tried it: the second modprobe only repeats why.
|
||||
let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out);
|
||||
return check('awg', title, 'error',
|
||||
why ? sprintf(_("The kernel module doesn't load: %s Reinstall a build for this kernel in Components."), why)
|
||||
: _("The kernel module doesn't load. Reinstall a build for this kernel in Components."),
|
||||
'updates', _('AmneziaWG’s kernel module doesn’t load'));
|
||||
}
|
||||
if (!st.handler)
|
||||
return check('awg', title, 'error', no_proto(), 'netrestart', _('The network doesn’t know AmneziaWG yet'));
|
||||
// The install could not swap the loaded module: the old one runs until the next boot (dawnline.awg_builds).
|
||||
if (builds.waits_for_reboot())
|
||||
return check('awg', title, 'warn', _('The AmneziaWG update is installed and starts after a reboot.'), null,
|
||||
_('The AmneziaWG update waits for a reboot'));
|
||||
return check('awg', title, 'ok', _('Kernel module, awg tool and the netifd protocol are present.'));
|
||||
}
|
||||
|
||||
/**
|
||||
* The /24s home routers come with out of the box. A home network on one of
|
||||
* them is very likely the same as the network a person connects from, and
|
||||
* home access then takes those addresses into the tunnel: their own printer or
|
||||
* TV is out of reach while connected, LAN Bypass or not.
|
||||
*/
|
||||
const COMMON_HOME = [
|
||||
'192.168.0.0/24', '192.168.1.0/24', '192.168.2.0/24', '192.168.3.0/24', '192.168.8.0/24', '192.168.10.0/24',
|
||||
'192.168.31.0/24', '192.168.50.0/24', '192.168.88.0/24', '192.168.100.0/24', '192.168.178.0/24',
|
||||
'10.0.0.0/24', '10.1.1.0/24',
|
||||
];
|
||||
|
||||
/** The home networks in `nets` that overlap a common out-of-the-box subnet. */
|
||||
export function common_home(nets) {
|
||||
return filter(nets ?? [], (n) => {
|
||||
let a = parse_cidr(n);
|
||||
return a && length(filter(COMMON_HOME, (c) => cidr_overlaps(a, parse_cidr(c))));
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the server's home networks are on a common subnet, while anyone on
|
||||
* it has home access (otherwise nothing of home goes into the tunnel). A
|
||||
* warning on Health only: advice, not a fault, so no notice elsewhere.
|
||||
*/
|
||||
function home_check(m, id, srv, label) {
|
||||
let reach = filter(values(m.people), (p) => p.server == id && (p.access == 'lan' || p.access == 'both'));
|
||||
let nets = net.server_net(srv).nets;
|
||||
if (!length(reach) || !length(nets))
|
||||
return null;
|
||||
let bad = common_home(nets);
|
||||
let c = check(`homenet_${id}`, _('Home network addresses') + label, length(bad) ? 'warn' : 'ok',
|
||||
length(bad)
|
||||
? sprintf(_('%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24.'), join(', ', bad))
|
||||
: sprintf(_('%s is not a common home subnet: the networks people connect from rarely use the same addresses.'), join(', ', nets)),
|
||||
null);
|
||||
c.problem = null;
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Checks of a server's AmneziaWG tunnel. */
|
||||
function awg_checks(m, id, srv, label, fwc, dmp, rep) {
|
||||
let out = [];
|
||||
let st = live.iface_status(srv.ifname);
|
||||
let up = !!st?.up;
|
||||
let codes = map(st?.errors ?? [], (e) => e.code);
|
||||
let running = _('AmneziaWG running') + label, down = _('AmneziaWG is down') + label;
|
||||
if (!up && index(codes, 'INVALID_PROTO') >= 0)
|
||||
push(out, check(`up_${id}`, running, 'error', no_proto(), 'netrestart', down));
|
||||
else
|
||||
push(out, check(`up_${id}`, running, up ? 'ok' : 'error',
|
||||
up ? sprintf(_('%s is up, listening on UDP %d.'), srv.ifname, srv.port) :
|
||||
!st ? sprintf(_('%s does not exist.'), srv.ifname) :
|
||||
length(codes) ? sprintf(_('%s is down: %s.'), srv.ifname, join(', ', codes)) : sprintf(_('%s is down.'), srv.ifname),
|
||||
up ? null : (st ? 'ifup:' + srv.ifname : 'apply'), down));
|
||||
// The devices the sync loads, by the same choice the agent compares with every minute.
|
||||
if (up && dmp.reads[srv.ifname] == 'error')
|
||||
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, 'warn',
|
||||
_('The tunnel could not be read, so its devices could not be checked.'), null,
|
||||
_('The devices in AmneziaWG could not be checked') + label));
|
||||
else if (up) {
|
||||
let devs = awg.tunnel_devices(m, id, apply.states_for(m, core.load_usage()));
|
||||
let diff = awg.peer_diff(devs, dmp, srv.ifname);
|
||||
let expected = length(devs), missing = diff.missing, extra = diff.extra, actual = diff.loaded;
|
||||
let same = !missing && !extra;
|
||||
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, same ? 'ok' : 'warn',
|
||||
same ? sprintf(N_(actual, '%d device is loaded in the tunnel.', '%d devices are loaded in the tunnel.'), actual) :
|
||||
extra ? sprintf(N_(expected, '%d of %d device missing, %d loaded that should not be.', '%d of %d devices missing, %d loaded that should not be.'),
|
||||
missing, expected, extra)
|
||||
: sprintf(N_(expected, '%d of %d device missing.', '%d of %d devices missing.'), missing, expected),
|
||||
same ? null : 'sync', _('Not every device is loaded into AmneziaWG') + label));
|
||||
}
|
||||
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
|
||||
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
|
||||
push(out, check(`fw_${id}`, _('AmneziaWG firewall') + label, rule && zone ? 'ok' : 'error',
|
||||
rule && zone ? sprintf(_('Zone %s and the WAN rule for UDP %d exist.'), srv.ifname, srv.port) : _('Firewall zone or WAN rule is missing.'),
|
||||
rule && zone ? null : 'apply', _('AmneziaWG firewall rules are missing') + label));
|
||||
push(out, reply_check(`reply_${id}`, _('AmneziaWG answers reach devices') + label, _('AmneziaWG answers may not reach devices') + label,
|
||||
'udp', srv.port, rep));
|
||||
// Port collisions with other tunnels.
|
||||
let clash = [];
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
nc.foreach('network', 'interface', (s) => {
|
||||
if (s['.name'] != srv.ifname && (s.proto == 'amneziawg' || s.proto == 'wireguard') && +s.listen_port == srv.port)
|
||||
push(clash, s['.name']);
|
||||
});
|
||||
if (length(clash))
|
||||
push(out, check(`port_${id}`, _('AmneziaWG port is free') + label, 'error', sprintf(_('UDP %d is also used by %s.'), srv.port, join(', ', clash)),
|
||||
null, _('AmneziaWG port is taken') + label));
|
||||
let overlaps = [];
|
||||
let sc = parse_cidr(srv.subnet);
|
||||
for (let o in other_subnets(id)) {
|
||||
let oc = parse_cidr(o.cidr);
|
||||
if (sc && oc && cidr_overlaps(sc, oc))
|
||||
push(overlaps, `${o.iface} (${o.cidr})`);
|
||||
}
|
||||
push(out, check(`subnet_${id}`, _('AmneziaWG subnet is unique') + label, length(overlaps) ? 'error' : 'ok',
|
||||
length(overlaps) ? sprintf(_('%s overlaps %s.'), srv.subnet, join(', ', overlaps)) : sprintf(_('%s does not overlap other networks.'), srv.subnet),
|
||||
null, _('AmneziaWG subnet overlaps another network') + label));
|
||||
let home = home_check(m, id, srv, label);
|
||||
if (home)
|
||||
push(out, home);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The portal's checks: listening, its address, answers, plain HTTP and the certificate. */
|
||||
function portal_checks(m, need, rep) {
|
||||
let out = [];
|
||||
let s = m.settings;
|
||||
let portal = _('Personal portal'), portal_bad = _('Personal portal isn’t working');
|
||||
if (length(need.https))
|
||||
return [ check('portal', portal, 'error', sprintf(_("HTTPS isn't available on this router: install %s."), join(', ', need.https)), 'install:https', portal_bad) ];
|
||||
let owners = tcp_port_owners(s.portal_port);
|
||||
let listening = tcp_listening(s.portal_port);
|
||||
if (length(owners))
|
||||
push(out, check('portal', portal, 'error',
|
||||
sprintf(_('TCP %d is already used by %s. Choose another port in Settings.'), s.portal_port, join(', ', owners)), null, portal_bad));
|
||||
else
|
||||
push(out, check('portal', portal, listening ? 'ok' : 'error',
|
||||
listening ? sprintf(_('Listening on TCP %d.'), s.portal_port) : sprintf(_('Nothing listens on TCP %d.'), s.portal_port),
|
||||
listening ? null : 'restart', portal_bad));
|
||||
if (!s.portal_host)
|
||||
push(out, check('portal_host', _('Portal address'), 'error', _('Set the public hostname in Settings so links can be generated.'),
|
||||
null, _('Portal address isn’t set')));
|
||||
else {
|
||||
let ips = lookup.resolve(s.portal_host), wan = lookup.router_wan(m);
|
||||
let cf = filter(ips, (x) => cloudflare_ip(x));
|
||||
let h = s.portal_host;
|
||||
push(out, check('portal_dns', _('Portal address points here'), !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok',
|
||||
!length(ips) ? sprintf(_('%s does not resolve.'), h) :
|
||||
length(cf) ? sprintf(_('%s goes through Cloudflare; in Russia such connections often stall after ~16 KB.'), h) :
|
||||
wan && index(ips, wan) < 0 ? sprintf(_('%s points at %s, not this router (%s).'), h, join(', ', ips), wan) :
|
||||
wan ? sprintf(_('%s → %s (this router).'), h, join(', ', ips)) : `${h} → ${join(', ', ips)}.`,
|
||||
null, _('Portal address doesn’t point here')));
|
||||
}
|
||||
push(out, reply_check('portal_reply', _('Portal answers reach visitors'), _('Portal answers may not reach visitors'), 'tcp', s.portal_port, rep));
|
||||
if (core.portal_http(m)) {
|
||||
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
|
||||
push(out, check('portal_http', _('Plain HTTP links'), 'warn',
|
||||
sprintf(_('Links on %s use plain HTTP: the link and the VPN keys in configurations travel unencrypted.'), join(', ', ipl)),
|
||||
null, _('Portal links use plain HTTP')));
|
||||
}
|
||||
if (ip2int(s.portal_host) != null) {
|
||||
push(out, check('cert', _('Portal certificate'), 'skip', _('The main address is an IP: its links use plain HTTP.')));
|
||||
return out;
|
||||
}
|
||||
let cert = pc.portal_cert(s);
|
||||
let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0;
|
||||
let sans = cert.self_signed ? [] : pc.cert_names(cert.cert);
|
||||
let covers = !s.portal_host || cert.self_signed || length(filter(sans, (n) => pc.name_covers(n, s.portal_host))) > 0;
|
||||
push(out, check('cert', _('Portal certificate'), cert.self_signed || !ok || !covers ? 'warn' : 'ok',
|
||||
cert.self_signed ? (length(need.acme) ? _('Using a self-signed certificate: browsers will show a warning. ACME can get a free Let’s Encrypt one.')
|
||||
: _('Using a self-signed certificate: browsers will show a warning.')) :
|
||||
!covers ? sprintf(_('%s does not cover %s (it has %s): browsers will warn.'), cert.cert, s.portal_host, join(', ', sans)) :
|
||||
ok ? sprintf(_('%s covers %s and is valid for more than 14 days.'), cert.cert, s.portal_host) : sprintf(_('%s expires within 14 days.'), cert.cert),
|
||||
null, _('Portal certificate needs attention')));
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix,
|
||||
* problem (a failed check in words, else null) }, the texts in the language of the call.
|
||||
* `fix` names an action accepted by fix(), or one the UI handles itself
|
||||
* (install:<feature>, updates).
|
||||
*/
|
||||
export function health(m) {
|
||||
m ??= core.load();
|
||||
let rep = replies(m);
|
||||
let out = [];
|
||||
let dmp = live.dump(m);
|
||||
let need = needs();
|
||||
|
||||
if (length(m.servers))
|
||||
push(out, awg_check());
|
||||
let y = localtime().year;
|
||||
push(out, check('clock', _('Clock is set'), y >= 2025 ? 'ok' : 'error',
|
||||
y >= 2025 ? _('End dates and quotas use the router clock.') : _('The router clock looks wrong; end dates will misbehave. Check NTP.'),
|
||||
null, _('Clock isn’t set')));
|
||||
|
||||
let agent = service_running('dawnline', 'agent');
|
||||
push(out, check('agent', _('Background agent running'), agent ? 'ok' : 'error',
|
||||
_('Counts traffic and enforces end dates and quotas.'), agent ? null : 'restart', _('Background agent isn’t running')));
|
||||
|
||||
// A full overlay fails every config write on the router, Dawnline's and
|
||||
// OpenWrt's own; backups and history are what Dawnline adds to it.
|
||||
let free = overlay_free_kb();
|
||||
if (free != null)
|
||||
push(out, check('flash', _('Free space on the router'), free < 512 ? 'error' : free < 2048 ? 'warn' : 'ok',
|
||||
free < 2048 ? sprintf(_('%s MB free: settings may stop saving. Remove old backups (Settings → Backups) or shorten the history.'), int(free / 1024 * 10) / 10)
|
||||
: sprintf(_('%d MB free on the overlay.'), int(free / 1024)),
|
||||
null, _('The router is running out of flash')));
|
||||
|
||||
if (!length(m.servers)) {
|
||||
push(out, check('server', _('Server configured'), 'warn', _('Run the setup wizard on the Server tab.'), null, _('No server yet')));
|
||||
return out;
|
||||
}
|
||||
|
||||
let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0;
|
||||
push(out, check('nft', _('Access rules loaded'), nft_ok ? 'ok' : 'error',
|
||||
nft_ok ? _('Table inet dawnline enforces who may reach LAN and the internet.')
|
||||
: _('Table inet dawnline is missing: no device is loaded into the tunnels until it is back.'),
|
||||
nft_ok ? null : 'apply', _('Access rules aren’t loaded')));
|
||||
|
||||
if (length(filter(values(m.servers), (s) => s.lan_like && s.enabled))) {
|
||||
let pr = policy_routing();
|
||||
push(out, check('policy', _('Internet like a home device not bypassed'), length(pr) ? 'warn' : 'ok',
|
||||
length(pr) ? sprintf(_("Policy routing on the router (%s) sends marked traffic straight out, past the home-device path: tunnel traffic it matches skips your LAN's proxies and filters."), join('; ', pr))
|
||||
: _('No other policy routing ahead of the tunnel rules.'),
|
||||
null, _('Other policy routing bypasses the home-device path')));
|
||||
}
|
||||
|
||||
// A device the sync has to leave out (a merged import, a hand-edited config).
|
||||
// Its sentences (core.model_errors), how many more, then what it means.
|
||||
let data = core.model_errors(m);
|
||||
push(out, check('data', _('People and devices consistent'), length(data) ? 'error' : 'ok',
|
||||
length(data) ? join(' ', filter([ join(' ', slice(data, 0, 4)), length(data) > 4 ? sprintf(_('(%d more)'), length(data) - 4) : null,
|
||||
_('Such devices are left out of the tunnels: fix or remove them.') ], (x) => x))
|
||||
: _('Every device has a key and an address of its own inside its server.'),
|
||||
null, _('People and devices are inconsistent')));
|
||||
|
||||
let fwc = cursor();
|
||||
fwc.load('firewall');
|
||||
|
||||
for (let id, srv in m.servers) {
|
||||
let label = length(m.servers) > 1 ? ` (${srv.name})` : '';
|
||||
if (!srv.enabled) {
|
||||
push(out, check(`srv_${id}`, _('Server') + label, 'skip', _('Server is disabled.')));
|
||||
continue;
|
||||
}
|
||||
push(out, ...awg_checks(m, id, srv, label, fwc, dmp, rep));
|
||||
push(out, endpoint_check(`ep_${id}`, _('Public address') + label, _('Public address needs attention') + label,
|
||||
srv, core.endpoint_host(m, srv), `UDP ${srv.port}`));
|
||||
|
||||
if (srv.lan_like) {
|
||||
let ls = loop.status();
|
||||
let nh = need.home;
|
||||
push(out, check(`home_${id}`, _('Internet like a home device') + label, ls.active && ls.bridged ? 'ok' : 'warn',
|
||||
ls.active && ls.bridged ? sprintf(_('Traffic enters %s as %s, so it is handled like any device on your LAN.'), ls.dev, ls.address) :
|
||||
length(nh) ? sprintf(_('Needs %s. Internet traffic leaves through WAN directly until then.'), join(', ', nh)) :
|
||||
ls.active ? sprintf(_('The link is up but not attached to %s.'), ls.dev) :
|
||||
// loop.status()'s own sentence, then what it means.
|
||||
`${ls.error ?? _('Not set up.')} ${_('Internet traffic leaves through WAN directly.')}`,
|
||||
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply', _('Internet like a home device isn’t working') + label));
|
||||
}
|
||||
}
|
||||
|
||||
// While every server is off the resolver only idles on loopback: nothing to check.
|
||||
if (length(filter(values(m.servers), (x) => x.enabled && x.private_key))) {
|
||||
let rt = loop.resolver_target();
|
||||
let conf = stat(loop.RESOLVER.conf);
|
||||
let running = conf != null && loop.resolver_running();
|
||||
// A new config (a server turned on, the home link up) restarts it: give it a few seconds.
|
||||
let restarting = !running && conf != null && time() - conf.mtime < 10;
|
||||
let ok = running || restarting;
|
||||
push(out, check('resolver', _('DNS for Home-only devices'), ok ? 'ok' : 'warn',
|
||||
restarting ? _('Restarting with the new settings.') :
|
||||
ok ? (rt.mode == 'ns' ? sprintf(_('Plain resolver running next to the LAN (%s).'), rt.address) : sprintf(_('Plain resolver on port %d.'), rt.port))
|
||||
: _('The resolver is not running; Home-only devices cannot resolve names.'),
|
||||
ok ? null : 'apply', _('DNS for Home-only devices isn’t working')));
|
||||
}
|
||||
|
||||
if (m.settings.portal_enabled)
|
||||
push(out, ...portal_checks(m, need, rep));
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Run a fix named by a check. */
|
||||
export function fix(id) {
|
||||
if (id == 'apply')
|
||||
return apply.apply();
|
||||
if (id == 'sync')
|
||||
return apply.sync();
|
||||
if (id == 'restart')
|
||||
return { code: system('/etc/init.d/dawnline restart >/dev/null 2>&1') };
|
||||
// netifd learns protocol handlers (amneziawg) only when it starts. In the
|
||||
// background: the answer goes out before the network blinks.
|
||||
if (id == 'netrestart') {
|
||||
system('( sleep 1; /etc/init.d/network restart ) >/dev/null 2>&1 </dev/null &');
|
||||
return { ok: true, background: true };
|
||||
}
|
||||
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
|
||||
if (m) {
|
||||
// Only Dawnline's own tunnels: never another interface of the router.
|
||||
let mine = filter(values(core.load().servers), (s) => s.ifname == m[1] && s.private_key);
|
||||
if (!length(mine))
|
||||
die(sprintf(_("%s is not one of Dawnline's tunnels."), m[1]));
|
||||
system(`ifup ${q(m[1])}`);
|
||||
return { ok: true };
|
||||
}
|
||||
die(_('Unknown fix.'));
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
// Dawnline — the backend's messages in the admin's language: what die()
|
||||
// reports, the health checks, the updater's phases. Text is English in the
|
||||
// code, wrapped in _() and N_() (web/i18n/extract.ts collects them into the
|
||||
// luci-i18n-dawnline-<lang> catalog with the admin UI's strings), with
|
||||
// placeholders filled by sprintf() after the lookup:
|
||||
//
|
||||
// die(sprintf(_('Download failed: %s'), asset));
|
||||
//
|
||||
// Translated through LuCI's own catalog reader (luci.core, as LuCI's pages
|
||||
// are) in the language use() set: the admin page's, sent with every RPC call
|
||||
// (rpcd/ucode/luci.dawnline) and handed to the updater. With no language,
|
||||
// no Dawnline translation installed for it, or no luci-base (the unit tests'
|
||||
// rootfs), the English as written. The portal sets none: its page translates
|
||||
// the messages it gets with its own catalog.
|
||||
|
||||
import { stat } from 'fs';
|
||||
|
||||
const DIR = '/usr/lib/lua/luci/i18n';
|
||||
|
||||
// A C module, loaded at run time: luci-base may be missing, and a static import would not compile then.
|
||||
let lmo = null;
|
||||
try {
|
||||
lmo = require('luci.core');
|
||||
}
|
||||
catch (e) {
|
||||
lmo = null;
|
||||
}
|
||||
|
||||
let active = null;
|
||||
|
||||
/**
|
||||
* Speak `lang` from now on ("ru"; null or "en" for English). Only a language
|
||||
* with a Dawnline catalog: LuCI's others alone would translate a few words.
|
||||
*/
|
||||
export function use(lang) {
|
||||
active = null;
|
||||
if (!lmo || type(lang) != 'string' || lang == 'en' || !match(lang, /^[a-z][a-z][a-z]?([_-][A-Za-z][A-Za-z][A-Za-z]?[A-Za-z]?)?$/))
|
||||
return;
|
||||
lang = lc(replace(lang, '_', '-'));
|
||||
if (!stat(`${DIR}/dawnline.${lang}.lmo`))
|
||||
return;
|
||||
if (lmo.load_catalog(lang, DIR) && lmo.change_catalog(lang))
|
||||
active = lang;
|
||||
};
|
||||
|
||||
/** The language use() set, when its catalog is in use; null for English. */
|
||||
export function current() {
|
||||
return active;
|
||||
};
|
||||
|
||||
/** `msg` in the language use() set (the English when the catalog has no translation). */
|
||||
export function _(msg) {
|
||||
return (active ? lmo.translate(msg) : null) ?? msg;
|
||||
};
|
||||
|
||||
/** `one` or `many` for n, by the language's plural rules (Russian has three forms). */
|
||||
export function N_(n, one, many) {
|
||||
return (active ? lmo.ntranslate(n, one, many) : null) ?? (n == 1 ? one : many);
|
||||
};
|
||||
|
||||
/**
|
||||
* A service log line's words, as written: the log is kept in English (the
|
||||
* agent that writes most of it has no language) and read later in any.
|
||||
* Marking them collects them into the catalog and into the admin page's list
|
||||
* of log templates, which puts each line into the reader's language when it
|
||||
* is shown (web/src/admin/events/logwords.ts): sprintf(L_('updated · %s → %s'), a, b).
|
||||
* Keep a line's English as it was: old lines match it too.
|
||||
*/
|
||||
export function L_(s) {
|
||||
return s;
|
||||
};
|
||||
@@ -0,0 +1,433 @@
|
||||
// Dawnline — how each device's link behaves, from the counters the agent's
|
||||
// watcher reads every second (dawnline.awg.dump): a device that knocks but
|
||||
// never finishes connecting, one whose configuration is in use on two devices,
|
||||
// one whose traffic the router drops, one whose connection keeps breaking.
|
||||
//
|
||||
// The agent keeps one history per device in memory (fresh(), observe(): a few
|
||||
// events of the last HISTORY seconds, not one entry per tick), classifies it
|
||||
// (classify(), pure) and shows a state only once it held HOLD seconds
|
||||
// (settle()). It writes what is shown to dawnline.live.LINK on a change; the
|
||||
// read side (live.dump's `link`, view.device_view) is dawnline.live's, so the
|
||||
// portal never loads this module. Who is online stays live.PRESENCE's.
|
||||
//
|
||||
// The same history tells the set-up sheet, at once and without HOLD, what a
|
||||
// device that is being set up does right now (setup_state(), setup()): it
|
||||
// knocks without finishing, data flows, or it connected but nothing it sends
|
||||
// comes through. The agent writes that to dawnline.live.SETUP on a change.
|
||||
//
|
||||
// What the counters mean (kmod 3.1, receive.c and send.c):
|
||||
// * an accepted handshake initiation adds exactly INITIATION bytes to the
|
||||
// peer's rx: the S1 prefix and any trailer are cut off and the header
|
||||
// protection is undone in place before update_rx_stats(skb->len). The
|
||||
// router answers it; its own handshake time moves only when the first
|
||||
// packet under the new keys arrives.
|
||||
// * a keepalive adds KEEPALIVE plus its content padding; a handshake
|
||||
// response (the router initiated) RESPONSE; data 32 + its padded length.
|
||||
// Plain data is a multiple of 16, so 148, 296 and 444 never are data.
|
||||
// * a data packet the router then drops (its source is not the device's
|
||||
// address: an old configuration after renumbering; this is what moves
|
||||
// the interface's rx_frame_errors) adds nothing to rx, but the router
|
||||
// still answers it with a keepalive within KeepaliveTimeout (about 10 s).
|
||||
|
||||
/** Seconds of events kept per device. */
|
||||
export const HISTORY = 600;
|
||||
/** A state is shown once it held this long (a flapping mobile link passes). */
|
||||
export const HOLD = 180;
|
||||
/** A device is classified at least this often when nothing happened (its spans age). */
|
||||
export const CHECK_EVERY = 15;
|
||||
|
||||
/** Bytes an accepted initiation adds to rx (sizeof(struct message_handshake_initiation)). */
|
||||
export const INITIATION = 148;
|
||||
/** Bytes a handshake response adds to rx (the router initiated). */
|
||||
export const RESPONSE = 92;
|
||||
/** Bytes an empty data packet adds to rx, before content padding. */
|
||||
export const KEEPALIVE = 32;
|
||||
// Random trailers without content padding: a keepalive grows up to a full packet.
|
||||
const TRAILER_MAX = 1500;
|
||||
// Initiations a device sends at most in one second (retries are 5 s apart).
|
||||
const KNOCKS_PER_TICK = 3;
|
||||
|
||||
/** trying: at least TRY_KNOCKS accepted initiations within TRY_SPAN seconds while not online. */
|
||||
export const TRY_SPAN = 120;
|
||||
export const TRY_KNOCKS = 3;
|
||||
/*
|
||||
* Churning: at least CHURN_COUNT handshakes within CHURN_SPAN seconds, with
|
||||
* CHURN_COUNT - 1 of the gaps under CHURN_GAP seconds. A device that is
|
||||
* there renews its keys every 100-120 s (RekeyAfterTime), more only when
|
||||
* its packets get nothing back (KeepaliveTimeout + RekeyTimeout, ~15 s).
|
||||
*/
|
||||
export const CHURN_SPAN = 300;
|
||||
export const CHURN_COUNT = 4;
|
||||
export const CHURN_GAP = 45;
|
||||
/** shared: while churning, the endpoint (ip:port) went back to an earlier one this often. */
|
||||
export const SHARE_RETURNS = 2;
|
||||
/*
|
||||
* dropped: online with a handshake within DROP_HS seconds, nothing but
|
||||
* handshakes and keepalives received for DROP_SPAN seconds, and the router
|
||||
* sent something at least DROP_ANSWERS times in that span with nothing
|
||||
* coming in (its keepalives answering packets it dropped), under DROP_TX
|
||||
* bytes in all (a real download is far more).
|
||||
*/
|
||||
export const DROP_SPAN = 180;
|
||||
export const DROP_HS = 240;
|
||||
export const DROP_ANSWERS = 6;
|
||||
export const DROP_TX = 65536;
|
||||
|
||||
/** Every state classify() can give. */
|
||||
export const STATES = [ 'trying', 'shared', 'dropped', 'unstable' ];
|
||||
|
||||
/*
|
||||
* The set-up sheet's trying: at least SETUP_KNOCKS accepted initiations
|
||||
* within SETUP_SPAN seconds, none of them followed by a handshake. A device
|
||||
* retries every 5 s, so it shows with the second (5-6 s in) and goes about
|
||||
* 15 s after the last.
|
||||
*/
|
||||
export const SETUP_SPAN = 20;
|
||||
export const SETUP_KNOCKS = 2;
|
||||
/*
|
||||
* nodata: online for SETUP_QUIET seconds since the handshake its session
|
||||
* began with, nothing but handshakes and keepalives in since, and the router
|
||||
* answered at least once with nothing coming in (a keepalive for data it
|
||||
* dropped, about 10 s after it: an old address in the configuration). An
|
||||
* idle device gets no answers, so it never shows.
|
||||
*/
|
||||
export const SETUP_QUIET = 15;
|
||||
|
||||
// Per list, the newest entries kept (a device whose endpoint flips every second).
|
||||
const KEEP = 64;
|
||||
|
||||
function keep(list, entry) {
|
||||
push(list, entry);
|
||||
if (length(list) > KEEP)
|
||||
shift(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* A new, empty history for a device first seen at `now`. Fields: rx, tx
|
||||
* (the counters last read, null before the first read), hs (the newest
|
||||
* handshake), ep (the endpoint), data (when rx last carried data), hsev
|
||||
* (handshake times), epev ([ ts, ip:port, the one before ] endpoint
|
||||
* changes), knocks (times
|
||||
* of accepted initiations), ans ([ ts, bytes ] the router sent with nothing
|
||||
* received), state/since (what is shown), pend (a state waiting for HOLD),
|
||||
* raw (the last classification), checked (when it was made); for the set-up
|
||||
* sheet (setup()): on (online at the last read), sess (the handshake its
|
||||
* online stretch began with, 0 while away), setup ({ state, since } or null)
|
||||
* and due (when setup_state() may change with time alone, 0 for never).
|
||||
*/
|
||||
export function fresh(now) {
|
||||
return {
|
||||
start: now, rx: null, tx: null, hs: 0, ep: null, data: 0,
|
||||
hsev: [], epev: [], knocks: [], ans: [],
|
||||
state: null, since: 0, pend: null, raw: null, checked: 0,
|
||||
on: false, sess: 0, setup: null, due: 0,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* The largest rx a keepalive adds for a server's disguise: KEEPALIVE plus
|
||||
* the top of its ContentPaddingAddition, or a full packet with random
|
||||
* trailers and no content padding (the apps get the server's values).
|
||||
*/
|
||||
export function keepalive_max(srv) {
|
||||
let o = srv?.obf ?? {};
|
||||
let cpa = split(`${o.content_padding_addition ?? ''}`, '-');
|
||||
let hi = +(cpa[length(cpa) - 1]);
|
||||
if (o.content_padding_addition != null && o.content_padding_addition != '' && hi > 0)
|
||||
return KEEPALIVE + hi;
|
||||
if (o.random_trailers == 'on' || o.random_trailers == '1')
|
||||
return KEEPALIVE + TRAILER_MAX;
|
||||
return KEEPALIVE;
|
||||
};
|
||||
|
||||
/** keepalive_max() for each device's server: { device id: bytes }. */
|
||||
export function keepalive_sizes(m) {
|
||||
let out = {};
|
||||
for (let id, d in m.devices)
|
||||
out[id] = keepalive_max(m.servers[m.people[d.person]?.server]);
|
||||
return out;
|
||||
};
|
||||
|
||||
/** An rx increment made of accepted initiations only. */
|
||||
export function knock(drx) {
|
||||
return drx > 0 && drx % INITIATION == 0 && drx <= KNOCKS_PER_TICK * INITIATION;
|
||||
};
|
||||
|
||||
/**
|
||||
* An rx increment that carried no data: nothing, or one keepalive of up to
|
||||
* `ka` bytes (keepalive_max); in the second a handshake completed (`shook`)
|
||||
* also the handshake messages that came with it. Outside that second a
|
||||
* handshake message is never counted in: with a padded keepalive their
|
||||
* sums would cover every small packet (a DNS query, an ACK) up to some
|
||||
* 670 bytes, and a device with light traffic would look like one whose
|
||||
* data never comes through.
|
||||
*/
|
||||
export function bare(drx, ka, shook) {
|
||||
if (drx <= 0)
|
||||
return true;
|
||||
if (!shook)
|
||||
return drx >= KEEPALIVE && drx <= ka;
|
||||
if (drx > KNOCKS_PER_TICK * INITIATION + RESPONSE + ka)
|
||||
return false;
|
||||
for (let k = 0; k <= KNOCKS_PER_TICK; k++)
|
||||
for (let r = 0; r <= 1; r++) {
|
||||
let rest = drx - k * INITIATION - r * RESPONSE;
|
||||
if (rest == 0 || (rest >= KEEPALIVE && rest <= ka))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fold one read of the device's peer ({ endpoint, handshake, rx, tx } from
|
||||
* awg.dump) at `now` into its history `h`; `ka` is its keepalive_max().
|
||||
* Returns true when something worth classifying again happened (a
|
||||
* handshake, a new endpoint, a knock, an answer, data after a quiet span).
|
||||
* Counters that went down (the peer re-added, its tunnel set up again)
|
||||
* start a new baseline.
|
||||
*/
|
||||
export function observe(h, peer, now, ka) {
|
||||
let changed = false;
|
||||
let shook = peer.handshake > h.hs;
|
||||
if (shook) {
|
||||
keep(h.hsev, peer.handshake);
|
||||
h.hs = peer.handshake;
|
||||
changed = true;
|
||||
}
|
||||
if (peer.endpoint != h.ep) {
|
||||
if (h.ep != null && peer.endpoint != '') {
|
||||
keep(h.epev, [ now, peer.endpoint, h.ep ]);
|
||||
changed = true;
|
||||
}
|
||||
h.ep = peer.endpoint;
|
||||
}
|
||||
if (h.rx == null || peer.rx < h.rx || peer.tx < h.tx) {
|
||||
h.rx = peer.rx;
|
||||
h.tx = peer.tx;
|
||||
return changed;
|
||||
}
|
||||
let drx = peer.rx - h.rx, dtx = peer.tx - h.tx;
|
||||
h.rx = peer.rx;
|
||||
h.tx = peer.tx;
|
||||
if (drx > 0) {
|
||||
if (!shook && knock(drx)) {
|
||||
keep(h.knocks, now);
|
||||
changed = true;
|
||||
}
|
||||
else if (!bare(drx, ka, shook)) {
|
||||
if (now - h.data >= DROP_SPAN)
|
||||
changed = true;
|
||||
h.data = now;
|
||||
}
|
||||
}
|
||||
else if (dtx > 0) {
|
||||
keep(h.ans, [ now, dtx ]);
|
||||
changed = true;
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
|
||||
/** The device's peer is not in its tunnel: the next read starts a new baseline. */
|
||||
export function gone(h) {
|
||||
h.rx = null;
|
||||
h.tx = null;
|
||||
};
|
||||
|
||||
/** Forget events older than HISTORY seconds. */
|
||||
export function prune(h, now) {
|
||||
let cut = now - HISTORY;
|
||||
h.hsev = filter(h.hsev, (t) => t > cut);
|
||||
h.knocks = filter(h.knocks, (t) => t > cut);
|
||||
h.epev = filter(h.epev, (e) => e[0] > cut);
|
||||
h.ans = filter(h.ans, (e) => e[0] > cut);
|
||||
};
|
||||
|
||||
/** Endpoint changes within the span that went back to an endpoint seen before in it (A → B → A → B: 2). */
|
||||
function returns(h, now) {
|
||||
let seen = null, n = 0;
|
||||
for (let e in h.epev)
|
||||
if (now - e[0] < CHURN_SPAN) {
|
||||
if (seen == null) {
|
||||
seen = {};
|
||||
seen[e[2]] = true;
|
||||
}
|
||||
if (seen[e[1]])
|
||||
n++;
|
||||
seen[e[1]] = true;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function churning(h, now) {
|
||||
let hs = filter(h.hsev, (t) => now - t < CHURN_SPAN);
|
||||
if (length(hs) < CHURN_COUNT)
|
||||
return false;
|
||||
let short = 0;
|
||||
for (let i = 1; i < length(hs); i++)
|
||||
if (hs[i] - hs[i - 1] < CHURN_GAP)
|
||||
short++;
|
||||
return short >= CHURN_COUNT - 1;
|
||||
}
|
||||
|
||||
function dropped(h, now) {
|
||||
if (now - h.start < DROP_SPAN || now - h.data < DROP_SPAN || !(h.hs > 0 && now - h.hs < DROP_HS))
|
||||
return false;
|
||||
let n = 0, bytes = 0;
|
||||
for (let a in h.ans)
|
||||
if (now - a[0] < DROP_SPAN) {
|
||||
n++;
|
||||
bytes += a[1];
|
||||
}
|
||||
return n >= DROP_ANSWERS && bytes < DROP_TX;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the history says about the device at `now` (`on`: it is online, as
|
||||
* the watcher decides it): null (nothing wrong, or nothing to tell), or
|
||||
* 'trying' not online, but its initiations reach the router and are
|
||||
* answered, and it never finishes connecting (the network
|
||||
* may block it, or its configuration is out of date: a
|
||||
* stale preshared key looks the same)
|
||||
* 'shared' connecting over and over from two or more alternating
|
||||
* endpoints (ip:port): one configuration on two devices
|
||||
* 'unstable' connecting over and over from one place: the connection
|
||||
* keeps breaking
|
||||
* 'dropped' connected, but nothing it sends gets through: the router
|
||||
* drops it (an old address in its configuration)
|
||||
*/
|
||||
export function classify(h, now, on) {
|
||||
if (!on) {
|
||||
let n = 0;
|
||||
for (let t in h.knocks)
|
||||
if (now - t < TRY_SPAN)
|
||||
n++;
|
||||
return n >= TRY_KNOCKS ? 'trying' : null;
|
||||
}
|
||||
if (churning(h, now))
|
||||
return returns(h, now) >= SHARE_RETURNS ? 'shared' : 'unstable';
|
||||
return dropped(h, now) ? 'dropped' : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Turn a classification into what is shown (h.state, h.since): a state, or
|
||||
* a change of state, shows once classify() gave it for HOLD seconds (since
|
||||
* = when it began); nothing wrong shows at once when the device is online
|
||||
* (it works), else after HOLD as well. Returns the change, { from, to }
|
||||
* (either may be null), or null when what is shown stays.
|
||||
*/
|
||||
export function settle(h, raw, now, on) {
|
||||
if (raw == h.state) {
|
||||
h.pend = null;
|
||||
return null;
|
||||
}
|
||||
let since = now;
|
||||
if (raw != null || !on) {
|
||||
if (h.pend == null || h.pend.state != raw) {
|
||||
h.pend = { state: raw, since: now };
|
||||
return null;
|
||||
}
|
||||
if (now - h.pend.since < HOLD)
|
||||
return null;
|
||||
since = h.pend.since;
|
||||
}
|
||||
let from = h.state;
|
||||
h.state = raw;
|
||||
h.since = raw != null ? since : 0;
|
||||
h.pend = null;
|
||||
return { from, to: raw };
|
||||
};
|
||||
|
||||
/**
|
||||
* What the device's link does at `now` for the set-up sheet (pure; `on`: it
|
||||
* is online, as the watcher decides it): { state, due }. state is
|
||||
* 'trying' its initiations reach the router and are answered, and no
|
||||
* handshake follows (SETUP_KNOCKS within SETUP_SPAN): the
|
||||
* network blocks the answers, or the configuration is not this
|
||||
* device's any more
|
||||
* 'flowing' online, and data came in during this session (since h.sess)
|
||||
* 'nodata' online for SETUP_QUIET seconds, nothing but handshakes and
|
||||
* keepalives came in, and the router answered packets it
|
||||
* dropped: an old address in the configuration
|
||||
* null none of these (waiting, idle, or away)
|
||||
* due: when the state may change with time alone (a knock ages out, the
|
||||
* quiet span ends), 0 for never: anything else comes with a read.
|
||||
*/
|
||||
export function setup_state(h, now, on) {
|
||||
let n = 0;
|
||||
for (let i = length(h.knocks) - 1; i >= 0; i--) {
|
||||
let t = h.knocks[i];
|
||||
if (t <= h.hs || now - t >= SETUP_SPAN)
|
||||
break;
|
||||
if (++n == SETUP_KNOCKS)
|
||||
return { state: 'trying', due: t + SETUP_SPAN };
|
||||
}
|
||||
if (!on || !h.sess)
|
||||
return { state: null, due: 0 };
|
||||
if (h.data >= h.sess)
|
||||
return { state: 'flowing', due: 0 };
|
||||
if (now - h.sess < SETUP_QUIET)
|
||||
return { state: null, due: h.sess + SETUP_QUIET };
|
||||
let a = h.ans[length(h.ans) - 1];
|
||||
return { state: a != null && a[0] >= h.sess ? 'nodata' : null, due: 0 };
|
||||
};
|
||||
|
||||
/**
|
||||
* Bring h.setup to setup_state() after a read at `now` (`moved`: what
|
||||
* observe() returned). Most reads cost a few compares: the state is worked
|
||||
* out again only when something happened, the device came or went, data
|
||||
* came in while it is not 'flowing', or its `due` time came. Returns true
|
||||
* when h.setup changed ({ state, since: when it began } or null).
|
||||
*/
|
||||
export function setup(h, now, on, moved) {
|
||||
// A session begins with the handshake that brought the device online.
|
||||
if (!on)
|
||||
h.sess = 0;
|
||||
else if (!h.sess)
|
||||
h.sess = h.hs;
|
||||
let came = on != h.on;
|
||||
h.on = on;
|
||||
let cur = h.setup?.state;
|
||||
if (!moved && !came && !(h.due && now >= h.due) && !(h.data == now && cur != 'flowing'))
|
||||
return false;
|
||||
let s = setup_state(h, now, on);
|
||||
h.due = s.due;
|
||||
if (s.state == cur)
|
||||
return false;
|
||||
h.setup = s.state != null ? { state: s.state, since: now } : null;
|
||||
return true;
|
||||
};
|
||||
|
||||
/** setup() of every device: { device id: { state, since } }, devices with none left out. */
|
||||
export function setups(hist) {
|
||||
let out = {};
|
||||
for (let id, h in hist)
|
||||
if (h.setup != null)
|
||||
out[id] = h.setup;
|
||||
return out;
|
||||
};
|
||||
|
||||
/** What is shown for every device: { device id: { state, since } }, devices with nothing to show left out. */
|
||||
export function shown(hist) {
|
||||
let out = {};
|
||||
for (let id, h in hist)
|
||||
if (h.state != null)
|
||||
out[id] = { state: h.state, since: h.since };
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* The activity event for a change settle() made, or null: device_failing
|
||||
* (detail: the new state) when a state shows, device_recovered (detail:
|
||||
* the state it had) when it clears while the device is online. One that
|
||||
* clears while the device is away (it stopped trying, it was paused) logs
|
||||
* nothing: nobody saw it work.
|
||||
*/
|
||||
export function event_for(change, dev, on) {
|
||||
if (!change)
|
||||
return null;
|
||||
if (change.to != null)
|
||||
return { type: 'device_failing', person: dev.person, device: dev.id, detail: change.to };
|
||||
if (on && change.from != null)
|
||||
return { type: 'device_recovered', person: dev.person, device: dev.id, detail: change.from };
|
||||
return null;
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
// Dawnline — live data: peer status from `awg show all dump`, traffic
|
||||
// Dawnline — live data: peer status from the tunnels (dawnline.awg), traffic
|
||||
// accounting and the connection/event log.
|
||||
//
|
||||
// Counters live in RUN_DIR (tmpfs) and are flushed to DATA_DIR at most once
|
||||
@@ -7,34 +7,42 @@
|
||||
import { readfile, stat, unlink } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import {
|
||||
q, sh, sh_out, sh_bg, ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, uniq,
|
||||
RUN_DIR, DATA_DIR
|
||||
ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, day_key_ago, uniq,
|
||||
iface_status as util_iface_status, RUN_DIR, DATA_DIR
|
||||
} from 'dawnline.util';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as schema from 'dawnline.schema';
|
||||
|
||||
export const ONLINE_WINDOW = 300;
|
||||
const KEEP_DAYS = 62;
|
||||
const KEEP_MONTHS = 24;
|
||||
const KEEP_EVENTS = 2000;
|
||||
// Online while the WireGuard session lives: it is dropped 180 s after its
|
||||
// handshake, and a device that is there renews it every 2 min (a little slack
|
||||
// for a renewal that needs a retry). One that left goes offline 1-3 min later.
|
||||
// The shortest window: a device whose keep-alive is longer gets more
|
||||
// (online_window), or it would flap between its handshakes.
|
||||
export const ONLINE_WINDOW = 190;
|
||||
/** A restore put other counters on flash: the agent reloads from there (dawnline.backup writes it). */
|
||||
export const USAGE_RELOAD = `${RUN_DIR}/usage.reload`;
|
||||
|
||||
/* ---------- retention policy ---------- */
|
||||
|
||||
/** Event type → log category (what Settings lets you switch off or clear). */
|
||||
export const CATEGORY = {
|
||||
connect: 'connections', disconnect: 'connections', roam: 'connections',
|
||||
device_added: 'devices', device_removed: 'devices', devices_removed: 'devices',
|
||||
// People and their devices: one category (devices used to have their own).
|
||||
device_added: 'people', device_removed: 'people', devices_removed: 'people',
|
||||
device_changed: 'people', device_keys: 'people', link_changed: 'people',
|
||||
person_added: 'people', person_removed: 'people', person_changed: 'people',
|
||||
paused: 'people', resumed: 'people', paused_all: 'people', resumed_all: 'people',
|
||||
paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people',
|
||||
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
|
||||
// A device's link (dawnline.link): failing in a named way, and working again.
|
||||
device_failing: 'problems', device_recovered: 'problems',
|
||||
};
|
||||
export const CATEGORIES = [ 'connections', 'devices', 'people', 'problems' ];
|
||||
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
|
||||
|
||||
export function category_of(type) {
|
||||
return CATEGORY[type] ?? 'problems';
|
||||
};
|
||||
|
||||
function int_or(v, d) {
|
||||
return (v == null || v == '' || match(`${v}`, /[^0-9]/)) ? d : +v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log and history retention from /etc/config/dawnline (read fresh, the
|
||||
@@ -55,14 +63,15 @@ export function policy(s) {
|
||||
cats = (s.log_connections == '0') ? filter(CATEGORIES, (x) => x != 'connections') : CATEGORIES;
|
||||
else if (type(cats) != 'array')
|
||||
cats = split(cats, /[ ,]+/);
|
||||
cats = filter(cats, (x) => index(CATEGORIES, x) >= 0);
|
||||
cats = uniq(filter(map(cats, (x) => x == 'devices' ? 'people' : x), (x) => index(CATEGORIES, x) >= 0));
|
||||
// Defaults and ranges come from dawnline.schema, like every other setting.
|
||||
return {
|
||||
keep_days: int_or(s.log_keep_days, 30),
|
||||
max: min(max(int_or(s.log_max, KEEP_EVENTS), 100), 20000),
|
||||
keep_days: schema.get(s, 'log_keep_days'),
|
||||
max: schema.get(s, 'log_max'),
|
||||
categories: cats,
|
||||
persist: index([ '10min', 'hourly', 'off' ], s.log_persist) >= 0 ? s.log_persist : 'hourly',
|
||||
usage_days: min(max(int_or(s.usage_keep_days, KEEP_DAYS), 7), 1830),
|
||||
usage_months: min(max(int_or(s.usage_keep_months, KEEP_MONTHS), 1), 120),
|
||||
persist: schema.get(s, 'log_persist'),
|
||||
usage_days: schema.get(s, 'usage_keep_days'),
|
||||
usage_months: schema.get(s, 'usage_keep_months'),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -77,39 +86,121 @@ function trim_events(ev, pol) {
|
||||
return ev;
|
||||
}
|
||||
|
||||
/* ---------- awg dump ---------- */
|
||||
/* ---------- live peers ---------- */
|
||||
|
||||
/* ---------- presence (the agent's watcher) ---------- */
|
||||
|
||||
/**
|
||||
* Parse `awg show all dump`. Returns { ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
|
||||
* Interface lines have many fields (AmneziaWG adds obfuscation values); peer
|
||||
* lines always have 9.
|
||||
* Written by the agent's watcher on every change: { online: { device id: bool },
|
||||
* endpoint: { device id: ip }, rev, people: { person id: rev } }. `rev` moves on
|
||||
* any connect, disconnect, roam or logged change; `people` per person (the portal).
|
||||
*/
|
||||
export function dump() {
|
||||
let r = sh('awg show all dump');
|
||||
let out = { ifaces: {}, peers: {} };
|
||||
if (r.code != 0)
|
||||
return out;
|
||||
for (let line in split(r.out, '\n')) {
|
||||
let f = split(line, '\t');
|
||||
if (length(f) == 9) {
|
||||
let ep = f[3] == '(none)' ? '' : f[3];
|
||||
out.peers[f[1]] = {
|
||||
ifname: f[0],
|
||||
endpoint: ep,
|
||||
handshake: +f[5],
|
||||
rx: +f[6],
|
||||
tx: +f[7],
|
||||
};
|
||||
}
|
||||
else if (length(f) >= 5) {
|
||||
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
|
||||
}
|
||||
export const PRESENCE = `${RUN_DIR}/presence.json`;
|
||||
// The agent's heartbeat (dawnline.watchdog.BEAT): its presence counts while it runs.
|
||||
const BEAT = `${RUN_DIR}/agent.beat`;
|
||||
const BEAT_STALE = 180;
|
||||
|
||||
/** The agent runs (its heartbeat is fresh): what its watcher wrote counts. */
|
||||
function agent_running() {
|
||||
let beat = +(read_json(BEAT, 0) ?? 0);
|
||||
return beat > 0 && time() - beat <= BEAT_STALE;
|
||||
}
|
||||
|
||||
/** What the watcher sees, or null when the agent isn't running. */
|
||||
export function presence() {
|
||||
return agent_running() ? read_json(PRESENCE, null) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Written by the agent's watcher when what it shows changes (dawnline.link):
|
||||
* { device id: { state: 'trying' | 'shared' | 'dropped' | 'unstable', since } },
|
||||
* only devices whose link fails in one of these ways (link.classify()).
|
||||
*/
|
||||
export const LINK = `${RUN_DIR}/link.json`;
|
||||
|
||||
/**
|
||||
* Written by the agent's watcher when it changes (dawnline.link.setup, at
|
||||
* once, without LINK's hold): what each device's link does right now, for the
|
||||
* set-up sheet: { device id: { state: 'trying' | 'flowing' | 'nodata', since } },
|
||||
* devices with none of these left out.
|
||||
*/
|
||||
export const SETUP = `${RUN_DIR}/setup.json`;
|
||||
|
||||
/**
|
||||
* The interfaces of the servers that run: enabled, with keys and an
|
||||
* interface that is Dawnline's (core.tunnels: never another tunnel that
|
||||
* took the name); with `sid`, only that server's. What dawnline.awg.dump()
|
||||
* reads; an empty list when none.
|
||||
*/
|
||||
export function tunnel_ifnames(m, sid) {
|
||||
let out = [];
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.enabled && (sid == null || id == sid))
|
||||
for (let t in core.tunnels(srv))
|
||||
push(out, t.ifname);
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* How long after its last handshake a device still counts as online, in
|
||||
* seconds: ONLINE_WINDOW, or 30 s more than an idle device with its
|
||||
* keep-alive goes between handshakes (awg.idle_handshake) when that is
|
||||
* longer. A device that sends nothing renews its session only with its
|
||||
* keep-alive: with one of about 95-120 s, or over 160 s, the fixed window
|
||||
* would see it leave and come back between two handshakes. Keep-alive off:
|
||||
* ONLINE_WINDOW.
|
||||
*/
|
||||
export function online_window(srv, dev) {
|
||||
let h = srv ? awg.idle_handshake(srv, dev) : null;
|
||||
return h != null ? max(ONLINE_WINDOW, h + 30) : ONLINE_WINDOW;
|
||||
};
|
||||
|
||||
/** online_window() of every device (with `sid`, of that server's): { device id: seconds }. */
|
||||
export function online_windows(m, sid) {
|
||||
let out = {};
|
||||
for (let id, d in m.devices) {
|
||||
let s = m.people[d.person]?.server;
|
||||
if (sid == null || s == sid)
|
||||
out[id] = online_window(m.servers[s], d);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* Dawnline's tunnels as dawnline.awg.dump() reads them (only those, each on
|
||||
* its own: { ok, reads, ifaces, peers: { public key: { ifname, endpoint,
|
||||
* handshake, rx, tx } } }), plus `presence`, the agent watcher's, `windows`,
|
||||
* each device's online_window() (online() without the agent), `link`, the
|
||||
* watcher's LINK ({} without the agent: its states would be stale), and
|
||||
* `setup`, its SETUP (null without the agent: nobody tells data from a bare
|
||||
* handshake then, view.device_view goes by the handshake). With `sid` only
|
||||
* that server's tunnel is read (one person's page needs no other: one `awg`
|
||||
* process, not one per server).
|
||||
*/
|
||||
export function dump(m, sid) {
|
||||
let d = awg.dump(tunnel_ifnames(m, sid));
|
||||
let up = agent_running();
|
||||
d.presence = up ? read_json(PRESENCE, null) : null;
|
||||
d.windows = online_windows(m, sid);
|
||||
d.link = up ? (read_json(LINK, null) ?? {}) : {};
|
||||
d.setup = up ? (read_json(SETUP, null) ?? {}) : null;
|
||||
return d;
|
||||
};
|
||||
|
||||
/** A device is online: as the agent's watcher says, or (without the agent) by a recent handshake. */
|
||||
export function online(dmp, id, peer) {
|
||||
let p = dmp?.presence?.online;
|
||||
if (p)
|
||||
return !!(peer && p[id]);
|
||||
return !!(peer && peer.handshake > 0 && time() - peer.handshake < (dmp?.windows?.[id] ?? ONLINE_WINDOW));
|
||||
};
|
||||
|
||||
// "203.0.113.7:41821", "[2001:db8::1]:41821". A module constant, compiled once:
|
||||
// the agent's watcher asks for every device, every second.
|
||||
const ENDPOINT = /^\[?([^\]]+)\]?:[0-9]+$/;
|
||||
|
||||
export function endpoint_ip(ep) {
|
||||
let m = match(ep ?? '', /^\[?([^\]]+?)\]?:[0-9]+$/);
|
||||
let m = match(ep ?? '', ENDPOINT);
|
||||
return m ? m[1] : ep;
|
||||
};
|
||||
|
||||
@@ -119,8 +210,16 @@ function empty_usage() {
|
||||
return { devices: {}, people: {}, updated: 0, flushed: 0 };
|
||||
}
|
||||
|
||||
export function load_usage() {
|
||||
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
|
||||
/**
|
||||
* The usage counters: the live copy in RUN_DIR, else what flash holds. With
|
||||
* `from_flash` only flash counts (a restore put new counters there, and the
|
||||
* watcher may have written the old live ones again since).
|
||||
*/
|
||||
export function load_usage(from_flash) {
|
||||
let u = (from_flash ? null : read_json(`${RUN_DIR}/usage.json`, null)) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
|
||||
// Per-app counters of earlier test builds are not kept.
|
||||
delete u.clients;
|
||||
return u;
|
||||
};
|
||||
|
||||
function add(bucket, key, rx, tx) {
|
||||
@@ -180,33 +279,46 @@ export function reset_usage(usage, m, scope, id) {
|
||||
for (let did in m.people[id]?.devices ?? [])
|
||||
wipe(usage.devices[did]);
|
||||
}
|
||||
else if (scope == 'device') {
|
||||
else if (scope == 'device')
|
||||
wipe(usage.devices[id]);
|
||||
}
|
||||
};
|
||||
|
||||
function offline(rec) {
|
||||
return { online: false, handshake: rec?.handshake ?? 0, endpoint: rec?.endpoint ?? '', present: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold the current kernel counters into `usage`. Counters restart from zero
|
||||
* when a peer is re-added or the interface restarts; a drop is treated as a
|
||||
* reset. Returns the per-device live view keyed by device id.
|
||||
* when a peer is re-added or its tunnel is set up again; a drop is treated
|
||||
* as a reset, and so is a new link (each record keeps the interface index
|
||||
* its counters were read on: new counters that already passed the old ones
|
||||
* would be counted short). Returns the per-device live view keyed by device id.
|
||||
*
|
||||
* A device missing from the dump had its counters reset only when its tunnel
|
||||
* was read or is down (dawnline.awg.dump's `reads`): one the tool couldn't
|
||||
* read says nothing, and forgetting the last counters there would count them
|
||||
* again on the next good read.
|
||||
*/
|
||||
export function collect(m, usage, d) {
|
||||
d ??= dump();
|
||||
d ??= dump(m);
|
||||
let ts = time();
|
||||
let live = {};
|
||||
let by_key = {};
|
||||
for (let id, dev in m.devices)
|
||||
by_key[dev.public_key] = id;
|
||||
|
||||
for (let id, dev in m.devices) {
|
||||
let rec = usage.devices[id] ??= { raw: [ 0, 0 ] };
|
||||
let peer = d.peers[dev.public_key];
|
||||
if (!peer) {
|
||||
rec.raw = [ 0, 0 ];
|
||||
live[id] = { online: false, handshake: rec.handshake ?? 0, endpoint: rec.endpoint ?? '', present: false };
|
||||
let ifname = m.servers[m.people[dev.person]?.server]?.ifname;
|
||||
if (d.reads[ifname] != 'error')
|
||||
rec.raw = [ 0, 0 ];
|
||||
live[id] = offline(rec);
|
||||
continue;
|
||||
}
|
||||
let raw = rec.raw ?? [ 0, 0 ];
|
||||
let link = d.ifaces[peer.ifname]?.ifindex;
|
||||
if (link != null && rec.ifindex != null && link != rec.ifindex)
|
||||
raw = [ 0, 0 ];
|
||||
if (link != null)
|
||||
rec.ifindex = link;
|
||||
let drx = peer.rx >= raw[0] ? peer.rx - raw[0] : peer.rx;
|
||||
let dtx = peer.tx >= raw[1] ? peer.tx - raw[1] : peer.tx;
|
||||
rec.raw = [ peer.rx, peer.tx ];
|
||||
@@ -227,7 +339,7 @@ export function collect(m, usage, d) {
|
||||
delete rec.ips[ips[i]];
|
||||
}
|
||||
live[id] = {
|
||||
online: peer.handshake > 0 && ts - peer.handshake < ONLINE_WINDOW,
|
||||
online: peer.handshake > 0 && ts - peer.handshake < online_window(m.servers[m.people[dev.person]?.server], dev),
|
||||
handshake: peer.handshake || rec.handshake || 0,
|
||||
endpoint: endpoint_ip(peer.endpoint) || rec.endpoint || '',
|
||||
present: true,
|
||||
@@ -258,9 +370,8 @@ export function save_usage(usage, persist) {
|
||||
/** Sum of [rx, tx] over the last `days` days for a usage record. */
|
||||
export function recent(rec, days) {
|
||||
let out = [ 0, 0 ];
|
||||
let ts = time();
|
||||
for (let i = 0; i < days; i++) {
|
||||
let v = rec?.days?.[day_key(ts - i * 86400)];
|
||||
let v = rec?.days?.[day_key_ago(i)];
|
||||
if (v) {
|
||||
out[0] += v[0];
|
||||
out[1] += v[1];
|
||||
@@ -276,9 +387,8 @@ export function month(rec) {
|
||||
/** Daily series for the last `days` days: [{ day, rx, tx }]. */
|
||||
export function series(recs, days) {
|
||||
let out = [];
|
||||
let ts = time();
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
let k = day_key(ts - i * 86400);
|
||||
let k = day_key_ago(i);
|
||||
let rx = 0, tx = 0;
|
||||
for (let r in recs) {
|
||||
let v = r?.days?.[k];
|
||||
@@ -298,17 +408,33 @@ export function load_events() {
|
||||
return read_json(`${RUN_DIR}/events.json`, null) ?? read_json(`${DATA_DIR}/events.json`, []);
|
||||
};
|
||||
|
||||
/*
|
||||
* Names as they are now (pname, dname, dkind), so the log still reads well
|
||||
* once the person or device is gone. Callers that delete first pass them.
|
||||
*/
|
||||
function with_names(e, c) {
|
||||
if (e.person && !e.pname)
|
||||
e.pname = c.get('dawnline', e.person, 'name');
|
||||
if (e.device && !e.dname)
|
||||
e.dname = c.get('dawnline', e.device, 'name');
|
||||
if (e.device && !e.dkind)
|
||||
e.dkind = c.get('dawnline', e.device, 'kind');
|
||||
return e;
|
||||
}
|
||||
|
||||
export function add_events(list, pol) {
|
||||
pol ??= policy();
|
||||
list = filter(list ?? [], (e) => index(pol.categories, category_of(e.type)) >= 0);
|
||||
if (!length(list))
|
||||
return;
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let l = lock('events');
|
||||
let ev = load_events();
|
||||
let ts = time();
|
||||
for (let e in list) {
|
||||
e.ts ??= ts;
|
||||
push(ev, e);
|
||||
push(ev, with_names(e, c));
|
||||
}
|
||||
ev = trim_events(ev, pol);
|
||||
ensure_dir(RUN_DIR);
|
||||
@@ -320,7 +446,10 @@ export function add_event(e) {
|
||||
add_events([ e ]);
|
||||
};
|
||||
|
||||
/** Like add_event, but folds into the previous event of the same kind and person within `window` s. */
|
||||
/**
|
||||
* Like add_event, but folds into the previous event of the same kind, person
|
||||
* and device (when it has one) within `window` s.
|
||||
*/
|
||||
export function add_event_merged(e, window) {
|
||||
let pol = policy();
|
||||
if (index(pol.categories, category_of(e.type)) < 0)
|
||||
@@ -329,14 +458,16 @@ export function add_event_merged(e, window) {
|
||||
let ev = load_events();
|
||||
let last = ev[length(ev) - 1];
|
||||
let ts = time();
|
||||
if (last && last.type == e.type && last.person == e.person && ts - last.ts < (window ?? 120)) {
|
||||
if (last && last.type == e.type && last.person == e.person && last.device == e.device && ts - last.ts < (window ?? 120)) {
|
||||
let parts = uniq([ ...split(last.detail ?? '', ', '), ...split(e.detail ?? '', ', ') ]);
|
||||
last.detail = join(', ', filter(parts, (x) => x != ''));
|
||||
last.ts = ts;
|
||||
}
|
||||
else {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
e.ts = ts;
|
||||
push(ev, e);
|
||||
push(ev, with_names(e, c));
|
||||
}
|
||||
ev = trim_events(ev, pol);
|
||||
ensure_dir(RUN_DIR);
|
||||
@@ -344,6 +475,35 @@ export function add_event_merged(e, window) {
|
||||
unlock(l);
|
||||
};
|
||||
|
||||
/**
|
||||
* Places for connections logged before their address was located (the
|
||||
* lookup finishes after the event): connect events since `since` from an
|
||||
* address in `where` ({ ip: "City · ISP" }) that have no place yet get it.
|
||||
* Returns true when `ev` changed.
|
||||
*/
|
||||
export function fill_places(ev, where, since) {
|
||||
let changed = false;
|
||||
for (let i = length(ev) - 1; i >= 0 && ev[i].ts >= since; i--) {
|
||||
let e = ev[i];
|
||||
if (e.type == 'connect' && !e.where && where[e.detail]) {
|
||||
e.where = where[e.detail];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
|
||||
/** fill_places() on the live log, written only when something changed. */
|
||||
export function set_places(where, since) {
|
||||
let l = lock('events');
|
||||
let ev = load_events();
|
||||
if (fill_places(ev, where, since)) {
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/events.json`, ev, 0o600);
|
||||
}
|
||||
unlock(l);
|
||||
};
|
||||
|
||||
/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */
|
||||
export function persist_events(pol) {
|
||||
pol ??= policy();
|
||||
@@ -352,6 +512,10 @@ export function persist_events(pol) {
|
||||
unlink(`${DATA_DIR}/events.json`);
|
||||
return;
|
||||
}
|
||||
// Only when something was logged since the last copy: flash is written rarely.
|
||||
let live_st = stat(`${RUN_DIR}/events.json`);
|
||||
if (!live_st || live_st.mtime <= (stat(`${DATA_DIR}/events.json`)?.mtime ?? 0))
|
||||
return;
|
||||
let ev = read_json(`${RUN_DIR}/events.json`, null);
|
||||
if (ev != null) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
@@ -389,17 +553,7 @@ export function clear_events(f) {
|
||||
/* ---------- health ---------- */
|
||||
|
||||
export function iface_status(ifname) {
|
||||
if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/))
|
||||
return null;
|
||||
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
|
||||
if (!s)
|
||||
return null;
|
||||
try {
|
||||
return json(s);
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
return util_iface_status(ifname);
|
||||
};
|
||||
|
||||
export function uptime() {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// Dawnline — where names point and the router's public address, for Health
|
||||
// and the portal settings. Lookups are cached in RUN_DIR for a few minutes
|
||||
// and made in parallel with a short timeout: rpcd answers one call at a
|
||||
// time, so a slow DNS server must not hold up the whole admin UI.
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { q, sh, ensure_dir, read_json, write_json, ip2int, is_ip6, rand_hex, RUN_DIR } from 'dawnline.util';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as net from 'dawnline.net';
|
||||
|
||||
const CACHE = `${RUN_DIR}/resolve.json`;
|
||||
// Answers are kept 5 minutes, failures 1 minute.
|
||||
const TTL = 300;
|
||||
const TTL_FAIL = 60;
|
||||
const TIMEOUT = 2;
|
||||
const MAX_NAMES = 16;
|
||||
// Public resolvers first: local DNS often rewrites the router's own name to
|
||||
// its LAN address (split horizon).
|
||||
const SERVERS = [ '1.1.1.1', '8.8.8.8', '127.0.0.1' ];
|
||||
|
||||
function valid_name(h) {
|
||||
return type(h) == 'string' && length(h) <= 253 && match(h, /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$/) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Addresses of each name, IPv4 and IPv6: { host: [ ip, … ] } (empty when it
|
||||
* does not resolve). IP addresses map to themselves. Every uncached name is
|
||||
* asked of every server at once, A and AAAA; the first server (in SERVERS
|
||||
* order) that answers wins.
|
||||
*/
|
||||
export function resolve_all(hosts) {
|
||||
let out = {}, now = time(), todo = [];
|
||||
let cache = read_json(CACHE, {});
|
||||
for (let h in hosts) {
|
||||
if (h == null || out[h] != null)
|
||||
continue;
|
||||
if (ip2int(h) != null || is_ip6(h)) {
|
||||
out[h] = [ h ];
|
||||
continue;
|
||||
}
|
||||
let c = cache[h];
|
||||
if (c && now - c.ts < (length(c.ips) ? TTL : TTL_FAIL))
|
||||
out[h] = c.ips;
|
||||
else if (valid_name(h) && length(todo) < MAX_NAMES) {
|
||||
out[h] = [];
|
||||
push(todo, h);
|
||||
}
|
||||
else
|
||||
out[h] = [];
|
||||
}
|
||||
if (!length(todo))
|
||||
return out;
|
||||
|
||||
ensure_dir(RUN_DIR);
|
||||
let dir = `${RUN_DIR}/resolve.${rand_hex(4)}`;
|
||||
let cmds = [];
|
||||
for (let i = 0; i < length(todo); i++)
|
||||
for (let j = 0; j < length(SERVERS); j++)
|
||||
for (let t in [ 'a', 'aaaa' ])
|
||||
// nslookup's own timeout: some firmware builds BusyBox without `timeout`.
|
||||
push(cmds, `( nslookup -type=${t} -timeout=${TIMEOUT} -retry=1 ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j}.${t} ) &`);
|
||||
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
|
||||
for (let i = 0; i < length(todo); i++) {
|
||||
let ips = [];
|
||||
for (let j = 0; j < length(SERVERS) && !length(ips); j++)
|
||||
for (let t in [ 'a', 'aaaa' ]) {
|
||||
let r = readfile(`${dir}/${i}.${j}.${t}`) ?? '';
|
||||
push(ips, ...filter(split(trim(r), '\n'), (x) => ip2int(x) != null || is_ip6(x)));
|
||||
}
|
||||
out[todo[i]] = ips;
|
||||
cache[todo[i]] = { ts: now, ips };
|
||||
}
|
||||
system(`rm -rf ${dir}`);
|
||||
// Only what is still fresh is kept.
|
||||
for (let h, c in cache)
|
||||
if (now - c.ts >= TTL)
|
||||
delete cache[h];
|
||||
write_json(CACHE, cache, 0o644);
|
||||
return out;
|
||||
};
|
||||
|
||||
/** IPv4 addresses of one name (see resolve_all). */
|
||||
export function resolve(host) {
|
||||
return resolve_all([ host ])[host] ?? [];
|
||||
};
|
||||
|
||||
/** The IPv4 address of a netifd interface (a zone name for older configs). */
|
||||
export function wan_ipv4(zone) {
|
||||
let st = live.iface_status(zone == 'wan' ? 'wan' : zone);
|
||||
return st?.['ipv4-address']?.[0]?.address;
|
||||
};
|
||||
|
||||
/** The router's public IPv4 (the first server's WAN, else the wan interface). */
|
||||
export function router_wan(m) {
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key) {
|
||||
let a = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
|
||||
if (a)
|
||||
return a;
|
||||
}
|
||||
return wan_ipv4('wan');
|
||||
};
|
||||
@@ -7,41 +7,57 @@
|
||||
// └── NAT to a LAN address ┘
|
||||
//
|
||||
// The netns is one more device on the LAN bridge with its own address (picked
|
||||
// from the LAN subnet above the DHCP pool). Replies come back the same way.
|
||||
// from the LAN subnet above the DHCP pool) and its own MAC (hashed from the
|
||||
// bridge's), the same each time it is created: the router's neighbour table
|
||||
// knows the address by that MAC, so a netns created again keeps its address
|
||||
// instead of seeing it held by another device. Replies come back the same way.
|
||||
// Home-network destinations keep their direct route; per-person access is
|
||||
// still enforced on dawn0 before any of this (table inet dawnline).
|
||||
//
|
||||
// Clients also use the netns address as DNS: it forwards to the DNS the LAN
|
||||
// gets from DHCP, from the LAN side, so DNS interception applies as well.
|
||||
//
|
||||
// Separately, people with Home-only access get a plain resolver (real
|
||||
// addresses from the WAN's DNS, home names from the LAN DNS): their internet
|
||||
// does not use the tunnel, so fake-IP answers would break it. While the netns
|
||||
// exists the resolver runs inside it and sends its upstream queries back out
|
||||
// through the transit link as forwarded traffic — not as the router's own
|
||||
// traffic and not from the LAN — so tools that capture either leave it alone.
|
||||
// The netns forwards and NATs every packet a second time (conntrack, the
|
||||
// forward hook): about 40% more CPU per packet on an MT7981. A flowtable on
|
||||
// its two links (dlx1, dll1) lets established TCP and UDP flows skip that
|
||||
// work. The netns holds no access rules: who may reach what is judged on the
|
||||
// tunnel interfaces in the root namespace, which no flowtable here touches.
|
||||
// Without kernel flowtables (kmod-nft-offload) the loop runs as before,
|
||||
// slower, and logs it once.
|
||||
//
|
||||
// Separately, people with Home-only access get a plain resolver
|
||||
// (dawnline.resolver). While the netns exists it runs inside it and sends its
|
||||
// upstream queries back out through the transit link as forwarded traffic —
|
||||
// not as the router's own traffic and not from the LAN — so tools that
|
||||
// capture either leave it alone. This module says where it runs.
|
||||
//
|
||||
// Everything is derived from the router at run time; nothing assumes a
|
||||
// particular subnet or tool. If the LAN is not a bridge or setup fails, the
|
||||
// direct path stays and status() says why.
|
||||
// direct path stays and status() says why (kept as a code in loop.json, which
|
||||
// apply and the agent write with no language; error_text() makes the words).
|
||||
|
||||
import { readfile, writefile, readlink, stat, unlink } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { sh, sh_out, q, ip2int, int2ip, ensure_dir, read_json, write_json, uniq, RUN_DIR } from 'dawnline.util';
|
||||
import {
|
||||
sh, sh_out, q, ip2int, int2ip, parse_cidr, cidr_any, ensure_dir, read_json, write_json, slog, RUN_DIR
|
||||
} from 'dawnline.util';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as resolver from 'dawnline.resolver';
|
||||
import { _, L_ } from 'dawnline.i18n';
|
||||
|
||||
export const NS = 'dawnline';
|
||||
const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.lan, LAN_NS = 'dll1';
|
||||
const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
|
||||
const RESOLVER_PORT = 5354;
|
||||
export const RESOLVER_CONF = '/var/etc/dawnline-dns.conf';
|
||||
const RESOLVER_RESOLV = '/var/etc/dawnline-dns.resolv';
|
||||
const RESOLVER_PID = '/var/run/dawnline-dns.pid';
|
||||
export const RESOLVER_CONF = resolver.CONF;
|
||||
const STATE = `${RUN_DIR}/loop.json`;
|
||||
const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ];
|
||||
const NS_RULES = '/var/etc/dawnline-ns.nft';
|
||||
|
||||
function log(msg) {
|
||||
system(`logger -t dawnline ${q(msg)}`);
|
||||
const WHO = L_('Internet like a home device');
|
||||
|
||||
function log(msg, level, detail) {
|
||||
slog('dawnline', level ?? 'info', msg, detail, WHO);
|
||||
}
|
||||
|
||||
function run(cmds) {
|
||||
@@ -58,17 +74,6 @@ function exists(dev) {
|
||||
return stat(`/sys/class/net/${dev}`) != null;
|
||||
}
|
||||
|
||||
function cidr_of(a) {
|
||||
let m = match(a ?? '', /^([0-9.]+)\/([0-9]+)$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = +m[2];
|
||||
if (ip == null || prefix < 8 || prefix > 30)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
return { ip, prefix, size, net: ip - ip % size };
|
||||
}
|
||||
|
||||
/* ---------- facts about the LAN ---------- */
|
||||
|
||||
/** DHCP pool, static leases and the DNS handed to LAN clients, for one netifd interface. */
|
||||
@@ -113,39 +118,64 @@ function used_addresses(dev) {
|
||||
return used;
|
||||
}
|
||||
|
||||
/** The MAC the netns's LAN link has now; null without the link. */
|
||||
function our_mac() {
|
||||
return sh_out(`ip -n ${NS} -j link show ${LAN_NS} 2>/dev/null | jsonfilter -e '@[0].address'`);
|
||||
}
|
||||
|
||||
/** 32-bit FNV-1a of a string, continuing from `h`. */
|
||||
function fnv1a(s, h) {
|
||||
for (let i = 0; i < length(s); i++)
|
||||
h = ((h ^ ord(s, i)) * 16777619) & 0xffffffff;
|
||||
return h;
|
||||
}
|
||||
|
||||
/**
|
||||
* A LAN address for the netns: keep the saved one while it is valid and not
|
||||
* taken by someone else, otherwise the highest free host above the DHCP pool
|
||||
* (then below it), skipping static leases and anything that answers.
|
||||
* The MAC for the netns's LAN link, from the bridge's MAC: a locally
|
||||
* administered unicast address hashed from it, so it is the same every time
|
||||
* and differs between routers. Not the bridge's MAC with a bit flipped: radios
|
||||
* and ports often get those.
|
||||
*/
|
||||
function pick_address(lan, facts, saved, dev) {
|
||||
export function lan_mac(bridge) {
|
||||
let s = lc(trim(bridge ?? ''));
|
||||
let h1 = fnv1a(`dawnline lan ${s}`, 0x811c9dc5), h2 = fnv1a(s, h1);
|
||||
let b = [ ((h1 >> 24) & 0xfc) | 0x02, (h1 >> 16) & 0xff, (h1 >> 8) & 0xff, h1 & 0xff, (h2 >> 24) & 0xff, (h2 >> 16) & 0xff ];
|
||||
return join(':', map(b, (x) => sprintf('%02x', x)));
|
||||
};
|
||||
|
||||
/**
|
||||
* True when the netns may use a LAN address (a number): a host of the
|
||||
* network, not the router's, not a static lease, outside the DHCP pool and
|
||||
* not held by another device in `used` (address → MAC, or true without one).
|
||||
* An entry with one of the MACs in `mine` is the netns itself, also from
|
||||
* before it was created again.
|
||||
*/
|
||||
export function address_free(ip, lan, facts, used, mine) {
|
||||
if (ip <= lan.net || ip >= lan.net + lan.size - 1 || ip == lan.ip || index(facts.statics, ip) >= 0)
|
||||
return false;
|
||||
if (facts.pool && ip >= facts.pool[0] && ip <= facts.pool[1])
|
||||
return false;
|
||||
let u = used[int2ip(ip)];
|
||||
return u == null || index(mine, u) >= 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* A LAN address for the netns: keep the saved one while it is free (see
|
||||
* address_free; `mine` are the netns's MACs), otherwise the highest free host
|
||||
* above the DHCP pool (then below it) that does not answer.
|
||||
*/
|
||||
function pick_address(lan, facts, saved, dev, mine) {
|
||||
let used = used_addresses(dev);
|
||||
let mine = our_mac();
|
||||
let taken = (ip) => {
|
||||
let s = int2ip(ip);
|
||||
if (ip == lan.ip || index(facts.statics, ip) >= 0)
|
||||
return true;
|
||||
if (facts.pool && ip >= facts.pool[0] && ip <= facts.pool[1])
|
||||
return true;
|
||||
let u = used[s];
|
||||
return u != null && !(mine && u == mine);
|
||||
};
|
||||
let sv = ip2int(saved ?? '');
|
||||
if (sv != null && sv > lan.net && sv < lan.net + lan.size - 1 && !taken(sv))
|
||||
if (sv != null && address_free(sv, lan, facts, used, mine))
|
||||
return int2ip(sv);
|
||||
for (let ip = lan.net + lan.size - 2; ip > lan.net; ip--) {
|
||||
if (taken(ip))
|
||||
if (!address_free(ip, lan, facts, used, mine))
|
||||
continue;
|
||||
// Last check: nobody answers on it.
|
||||
sh(`ping -c 1 -W 1 -I ${q(dev)} ${int2ip(ip)}`);
|
||||
let again = used_addresses(dev)[int2ip(ip)];
|
||||
if (again != null && !(mine && again == mine))
|
||||
continue;
|
||||
return int2ip(ip);
|
||||
if (address_free(ip, lan, facts, used_addresses(dev), mine))
|
||||
return int2ip(ip);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -158,12 +188,8 @@ function pick_transit(saved) {
|
||||
push(busy, n);
|
||||
let free = (base) => {
|
||||
for (let b in busy) {
|
||||
let c = match(b, /^([0-9.]+)(\/([0-9]+))?$/);
|
||||
if (!c)
|
||||
continue;
|
||||
let ip = ip2int(c[1]), size = 1 << (32 - (c[3] != null ? +c[3] : 32));
|
||||
let bn = ip - ip % size;
|
||||
if (base < bn + size && bn < base + 4)
|
||||
let c = cidr_any(b);
|
||||
if (c && base < c.net + c.size && c.net < base + 4)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -193,6 +219,57 @@ function pick_table(saved) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ---------- why it is off ---------- */
|
||||
|
||||
/*
|
||||
* The reasons plan() and ensure() give, kept in loop.json:
|
||||
* { code: 'no_lan' } no LAN detected
|
||||
* { code: 'not_bridge', dev } the LAN is not a bridge
|
||||
* { code: 'no_ipv4', dev } the LAN has no IPv4 address
|
||||
* { code: 'no_address', net } no free address on the LAN's network
|
||||
* { code: 'no_transit' } no free link-local range for the internal link
|
||||
* { code: 'no_table' } no free routing table
|
||||
* { code: 'setup', detail } a command failed (detail: it and what it said)
|
||||
*/
|
||||
|
||||
/** A reason from plan() for the service log: English, like every log line. */
|
||||
function error_note(e) {
|
||||
if (e.code == 'no_lan')
|
||||
return L_('No LAN detected.');
|
||||
if (e.code == 'not_bridge')
|
||||
return sprintf(L_('%s is not a bridge, so Dawnline cannot join the LAN as a device.'), e.dev);
|
||||
if (e.code == 'no_ipv4')
|
||||
return sprintf(L_('%s has no IPv4 address.'), e.dev);
|
||||
if (e.code == 'no_address')
|
||||
return sprintf(L_('No free address on %s.'), e.net);
|
||||
if (e.code == 'no_transit')
|
||||
return L_('No free link-local range for the internal link.');
|
||||
return L_('No free routing table.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Why "like a home device" is off (a reason above), as a sentence in the
|
||||
* reader's language. Null for none; the English of a loop.json written by an
|
||||
* older version as it is.
|
||||
*/
|
||||
export function error_text(e) {
|
||||
if (type(e) != 'object')
|
||||
return e ?? null;
|
||||
if (e.code == 'no_lan')
|
||||
return _('No LAN detected.');
|
||||
if (e.code == 'not_bridge')
|
||||
return sprintf(_('%s is not a bridge, so Dawnline cannot join the LAN as a device.'), e.dev);
|
||||
if (e.code == 'no_ipv4')
|
||||
return sprintf(_('%s has no IPv4 address.'), e.dev);
|
||||
if (e.code == 'no_address')
|
||||
return sprintf(_('No free address on %s.'), e.net);
|
||||
if (e.code == 'no_transit')
|
||||
return _('No free link-local range for the internal link.');
|
||||
if (e.code == 'no_table')
|
||||
return _('No free routing table.');
|
||||
return sprintf(_('Setup failed: %s'), e.detail);
|
||||
};
|
||||
|
||||
/* ---------- plan ---------- */
|
||||
|
||||
function settings() {
|
||||
@@ -201,14 +278,19 @@ function settings() {
|
||||
return c.get_all('dawnline', 'settings') ?? {};
|
||||
}
|
||||
|
||||
/** Servers that want "like a home device" (default on). */
|
||||
/** Servers that want "like a home device" (default on) and run a core. */
|
||||
function wanted(m) {
|
||||
return filter(values(m.servers), (s) => s.private_key && s.enabled && s.lan_like);
|
||||
return filter(values(m.servers), (s) => length(core.tunnels(s)) && s.enabled && s.lan_like);
|
||||
}
|
||||
|
||||
/** Every server's interface, for rules. */
|
||||
function all_ifnames(m) {
|
||||
return map(values(m.servers), (s) => s.ifname);
|
||||
}
|
||||
|
||||
/**
|
||||
* What should exist, or { error } when it cannot. Pure apart from reading
|
||||
* router state (and one ping per candidate address).
|
||||
* What should exist, or { error } (a reason, see error_text) when it cannot.
|
||||
* Pure apart from reading router state (and one ping per candidate address).
|
||||
*/
|
||||
export function plan(m) {
|
||||
let srvs = wanted(m);
|
||||
@@ -218,33 +300,37 @@ export function plan(m) {
|
||||
let dev = snap.lan;
|
||||
let d = snap.devices[dev];
|
||||
if (!dev || !d)
|
||||
return { error: 'No LAN detected.' };
|
||||
return { error: { code: 'no_lan' } };
|
||||
if (d.kind != 'bridge')
|
||||
return { error: `${dev} is not a bridge, so Dawnline cannot join the LAN as a device.` };
|
||||
let lan = cidr_of(d.addrs[0]);
|
||||
return { error: { code: 'not_bridge', dev } };
|
||||
let lan = parse_cidr(d.addrs[0]);
|
||||
if (!lan)
|
||||
return { error: `${dev} has no IPv4 address.` };
|
||||
return { error: { code: 'no_ipv4', dev } };
|
||||
let facts = dhcp_facts(d.logical, lan);
|
||||
let st = settings();
|
||||
let addr = pick_address(lan, facts, st.lan_address, dev);
|
||||
let mac = lan_mac(readfile(`/sys/class/net/${dev}/address`));
|
||||
// The netns's MACs: the one it gets, and the one it has (a random one from an older version).
|
||||
let addr = pick_address(lan, facts, st.lan_address, dev, [ mac, our_mac() ]);
|
||||
if (!addr)
|
||||
return { error: `No free address on ${int2ip(lan.net)}/${lan.prefix}.` };
|
||||
return { error: { code: 'no_address', net: `${int2ip(lan.net)}/${lan.prefix}` } };
|
||||
let last = read_json(STATE, {});
|
||||
let tx = pick_transit(last?.transit);
|
||||
if (tx == null)
|
||||
return { error: 'No free link-local range for the internal link.' };
|
||||
return { error: { code: 'no_transit' } };
|
||||
let table = pick_table(last?.plan?.table);
|
||||
if (table == null)
|
||||
return { error: 'No free routing table.' };
|
||||
return { error: { code: 'no_table' } };
|
||||
let servers = [];
|
||||
for (let srv in srvs) {
|
||||
let sn = net.server_net(srv, snap);
|
||||
push(servers, { ifname: srv.ifname, subnet: srv.subnet, direct: net.collapse([ srv.subnet, ...sn.nets ]) });
|
||||
for (let t in core.tunnels(srv))
|
||||
push(servers, { ifname: t.ifname, subnet: t.subnet, direct: net.collapse([ t.subnet, ...sn.nets ]) });
|
||||
}
|
||||
return {
|
||||
dev,
|
||||
gateway: int2ip(lan.ip),
|
||||
address: addr,
|
||||
mac,
|
||||
prefix: lan.prefix,
|
||||
dns: facts.dns ?? int2ip(lan.ip),
|
||||
transit: tx,
|
||||
@@ -257,10 +343,20 @@ export function plan(m) {
|
||||
|
||||
/* ---------- apply ---------- */
|
||||
|
||||
function ns_rules(p) {
|
||||
/**
|
||||
* The netns's nft script as text (nothing is loaded). With `fast`, a
|
||||
* flowtable on the netns's own two links takes established TCP and UDP flows
|
||||
* past conntrack and the forward hook here. Only dlx1 and dll1: the root
|
||||
* namespace's links (dawn0, dlx0) stay out, the guard there sees every packet.
|
||||
*/
|
||||
export function ns_rules(p, fast) {
|
||||
return `table inet dawnline
|
||||
delete table inet dawnline
|
||||
table inet dawnline {
|
||||
table inet dawnline {${fast ? `
|
||||
flowtable ft {
|
||||
hook ingress priority 0;
|
||||
devices = { "${TX_NS}", "${LAN_NS}" };
|
||||
}` : ''}
|
||||
chain nat_pre {
|
||||
type nat hook prerouting priority dstnat; policy accept;
|
||||
iifname "${TX_NS}" ip daddr ${p.address} meta l4proto { tcp, udp } th dport 53 dnat ip to ${p.dns}:53
|
||||
@@ -270,7 +366,8 @@ table inet dawnline {
|
||||
oifname "${LAN_NS}" masquerade
|
||||
}
|
||||
chain filter_forward {
|
||||
type filter hook forward priority filter; policy drop;
|
||||
type filter hook forward priority filter; policy drop;${fast ? `
|
||||
ct state established meta l4proto { tcp, udp } flow add @ft` : ''}
|
||||
ct state established,related accept
|
||||
iifname "${TX_NS}" oifname "${LAN_NS}" accept
|
||||
}
|
||||
@@ -283,14 +380,47 @@ table inet dawnline {
|
||||
}
|
||||
}
|
||||
`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Load the netns's rules, with the flowtable when the kernel takes it, else
|
||||
* without (the loop works either way). { fast, slow, err }: slow is why the
|
||||
* flowtable failed, err why the rules without it failed too.
|
||||
*/
|
||||
function load_ns_rules(p) {
|
||||
ensure_dir('/var/etc');
|
||||
let load = (fast) => {
|
||||
writefile(NS_RULES, ns_rules(p, fast));
|
||||
return run([ `ip netns exec ${NS} nft -f ${NS_RULES}` ])[0];
|
||||
};
|
||||
let slow = load(true);
|
||||
return slow ? { fast: false, slow, err: load(false) } : { fast: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* The policy rules plan `p` wants (pure), in order: [{ pref, iif, to, table }]
|
||||
* (to null: all). Per server interface: DNS to the netns address through the
|
||||
* netns, home networks and the tunnel network by main, the rest into the netns.
|
||||
*/
|
||||
export function rules(p) {
|
||||
let out = [];
|
||||
let rule = (pref, iif, to, table) => push(out, { pref, iif, to, table });
|
||||
for (let s in p?.servers ?? []) {
|
||||
rule(PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}`);
|
||||
for (let n in s.direct)
|
||||
rule(PREF_MAIN, s.ifname, n, 'main');
|
||||
rule(PREF_LOOP, s.ifname, null, `${p.table}`);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */
|
||||
function current_rules(ifnames) {
|
||||
let out = [];
|
||||
try {
|
||||
// Ours, plus ours left behind by a removed tunnel (its interface is gone).
|
||||
for (let r in json(sh_out('ip -j -4 rule show') || '[]') ?? [])
|
||||
if (r.priority >= 5200 && r.priority < 5300 && r.iif && index(ifnames, r.iif) >= 0)
|
||||
if (r.priority >= 5200 && r.priority < 5300 && r.iif && (index(ifnames, r.iif) >= 0 || 'iif_detached' in r))
|
||||
push(out, r);
|
||||
}
|
||||
catch (e) {}
|
||||
@@ -298,53 +428,89 @@ function current_rules(ifnames) {
|
||||
}
|
||||
|
||||
|
||||
function rule_key(pref, iif, to, table) {
|
||||
return `${pref} ${iif} ${to ?? 'all'} ${table}`;
|
||||
// A rule of ours with a source (none of rules() has one) is told apart, so it is removed.
|
||||
function rule_key(pref, from, iif, to, table) {
|
||||
// `ip -j rule` shows a /32 source or destination without its length.
|
||||
let full = (n) => n && index(n, '/') < 0 ? `${n}/32` : n;
|
||||
return `${pref} ${full(from) ?? 'all'} ${iif} ${full(to) ?? 'all'} ${table}`;
|
||||
}
|
||||
|
||||
function sync_rules(p, ifnames) {
|
||||
let want = [];
|
||||
for (let s in p?.servers ?? []) {
|
||||
push(want, [ PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}` ]);
|
||||
for (let n in s.direct)
|
||||
push(want, [ PREF_MAIN, s.ifname, n, 'main' ]);
|
||||
push(want, [ PREF_LOOP, s.ifname, null, `${p.table}` ]);
|
||||
/**
|
||||
* A source or destination as `ip -j rule` has it ("10.9.0.2", or with its
|
||||
* length), or null for all: a rule without a source shows `"src": "all"`
|
||||
* (iproute2 prints "from all"), one without a destination no `dst`.
|
||||
*/
|
||||
function rule_net(addr, len) {
|
||||
return addr && addr != 'all' ? `${addr}${len != null ? '/' + len : ''}` : null;
|
||||
}
|
||||
|
||||
/** The command that removes one of current_rules(). */
|
||||
function rule_del(r) {
|
||||
let from = rule_net(r.src, r.srclen), to = rule_net(r.dst, r.dstlen);
|
||||
return `ip -4 rule del priority ${r.priority}${from ? ' from ' + from : ''} iif ${q(r.iif)}${to ? ' to ' + to : ''} lookup ${r.table}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The commands that turn rules `current` (ours, as `ip -j -4 rule show`
|
||||
* prints them) into rules(p) (pure): the missing ones added first, then the
|
||||
* ones no longer wanted removed, so a device's traffic never falls between
|
||||
* two rules while others change. [] when they are as wanted.
|
||||
*/
|
||||
export function rule_cmds(p, current) {
|
||||
let have = {}, want = {}, cmds = [], twice = [];
|
||||
for (let r in current) {
|
||||
let k = rule_key(r.priority, rule_net(r.src, r.srclen), r.iif, rule_net(r.dst, r.dstlen), r.table);
|
||||
if (have[k])
|
||||
push(twice, rule_del(r));
|
||||
have[k] = r;
|
||||
}
|
||||
let have = map(current_rules(ifnames), (r) => rule_key(r.priority, r.iif, r.dst ? `${r.dst}${r.dstlen != null ? '/' + r.dstlen : ''}` : null, r.table));
|
||||
let wantk = map(want, (w) => rule_key(w[0], w[1], w[2] ?? null, w[3]));
|
||||
if (join('\n', sort(have)) == join('\n', sort(wantk)))
|
||||
return [];
|
||||
let cmds = [];
|
||||
for (let r in current_rules(ifnames))
|
||||
push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`);
|
||||
for (let w in want)
|
||||
push(cmds, `ip -4 rule add priority ${w[0]} iif ${q(w[1])}${w[2] ? ' to ' + w[2] : ''} lookup ${w[3]}`);
|
||||
for (let w in rules(p)) {
|
||||
let k = rule_key(w.pref, null, w.iif, w.to, w.table);
|
||||
if (!have[k] && !want[k])
|
||||
push(cmds, `ip -4 rule add priority ${w.pref} iif ${q(w.iif)}${w.to ? ' to ' + w.to : ''} lookup ${w.table}`);
|
||||
want[k] = true;
|
||||
}
|
||||
for (let k, r in have)
|
||||
if (!want[k])
|
||||
push(cmds, rule_del(r));
|
||||
// The same rule twice (one deletion removes one of them).
|
||||
push(cmds, ...twice);
|
||||
return cmds;
|
||||
};
|
||||
|
||||
function sync_rules(p, ifnames) {
|
||||
return rule_cmds(p, current_rules(ifnames));
|
||||
}
|
||||
|
||||
function tunnel_ifnames() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let out = [];
|
||||
c.foreach('dawnline', 'server', (s) => push(out, s.ifname ?? s['.name']));
|
||||
c.foreach('dawnline', 'server', (s) => {
|
||||
push(out, s.ifname ?? s['.name']);
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Remove the netns, links and rules. */
|
||||
/** Remove the netns, links and rules, and the router's neighbour entry for the netns. */
|
||||
export function remove(ifnames) {
|
||||
ifnames ??= tunnel_ifnames();
|
||||
let cmds = [];
|
||||
for (let r in current_rules(ifnames))
|
||||
push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`);
|
||||
let t = read_json(STATE, {})?.plan?.table;
|
||||
if (t)
|
||||
push(cmds, `ip -4 route flush table ${t}`);
|
||||
let last = read_json(STATE, {})?.plan;
|
||||
// Read while the link is there: the entry is ours when it carries the netns's MAC.
|
||||
let held = last?.dev ? used_addresses(last.dev)[last.address] : null;
|
||||
let stale = type(held) == 'string' && index([ last.mac, our_mac() ], held) >= 0;
|
||||
let cmds = map(current_rules(ifnames), rule_del);
|
||||
if (last?.table)
|
||||
push(cmds, `ip -4 route flush table ${last.table}`);
|
||||
if (exists(TX_ROOT))
|
||||
push(cmds, `ip link del ${TX_ROOT}`);
|
||||
if (exists(LAN_ROOT))
|
||||
push(cmds, `ip link del ${LAN_ROOT}`);
|
||||
if (stat(`/var/run/netns/${NS}`))
|
||||
push(cmds, `ip netns del ${NS}`);
|
||||
// Left there, it would hold the address for a MAC nobody has.
|
||||
if (stale)
|
||||
push(cmds, `ip -4 neigh del ${q(last.address)} dev ${q(last.dev)}`);
|
||||
run(cmds);
|
||||
unlink(STATE);
|
||||
};
|
||||
@@ -354,15 +520,17 @@ export function remove(ifnames) {
|
||||
* last applied plan and only checks that links, bridge port and rules exist.
|
||||
*/
|
||||
export function ensure(m, force) {
|
||||
let ifnames = map(values(m.servers), (s) => s.ifname);
|
||||
let ifnames = all_ifnames(m);
|
||||
let p = plan(m);
|
||||
if (p.off || p.error) {
|
||||
if (stat(STATE) || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames)))
|
||||
// Read before remove(), which deletes it: the error is logged once, not every tick.
|
||||
let was = read_json(STATE, {});
|
||||
if (was.plan || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames)))
|
||||
remove(ifnames);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(STATE, { error: p.error, off: !!p.off }, 0o644);
|
||||
if (p.error)
|
||||
log(`like-home routing off: ${p.error}`);
|
||||
if (p.error && sprintf('%J', p.error) != sprintf('%J', was.error))
|
||||
log(L_('is off'), 'error', error_note(p.error));
|
||||
return p;
|
||||
}
|
||||
let last = read_json(STATE, {});
|
||||
@@ -373,13 +541,18 @@ export function ensure(m, force) {
|
||||
if (same && healthy && !length(rules))
|
||||
return p;
|
||||
|
||||
// A link made by an older version has a random MAC (its plan had none, so
|
||||
// this runs once after an update): it gets the stable one.
|
||||
let remac = exists(LAN_ROOT) && our_mac() != p.mac;
|
||||
let cmds = [];
|
||||
if (!stat(`/var/run/netns/${NS}`))
|
||||
push(cmds, `ip netns add ${NS}`);
|
||||
if (!exists(TX_ROOT))
|
||||
push(cmds, `ip link add ${TX_ROOT} type veth peer name ${TX_NS} netns ${NS}`);
|
||||
if (!exists(LAN_ROOT))
|
||||
push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} netns ${NS}`);
|
||||
push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} address ${p.mac} netns ${NS}`);
|
||||
if (remac)
|
||||
push(cmds, `ip -n ${NS} link set ${LAN_NS} down`, `ip -n ${NS} link set ${LAN_NS} address ${p.mac}`);
|
||||
let errs = run(cmds);
|
||||
cmds = [
|
||||
`ip addr flush dev ${TX_ROOT}`,
|
||||
@@ -403,34 +576,53 @@ export function ensure(m, force) {
|
||||
];
|
||||
for (let s in p.servers)
|
||||
push(cmds, `ip -n ${NS} route replace ${q(s.subnet)} via ${q(p.tx_root)} dev ${TX_NS}`);
|
||||
ensure_dir('/var/etc');
|
||||
writefile('/var/etc/dawnline-ns.nft', ns_rules(p));
|
||||
push(cmds, `ip netns exec ${NS} nft -f /var/etc/dawnline-ns.nft`);
|
||||
// The router knows the address by the old MAC: ask again now, not when the entry expires.
|
||||
if (remac)
|
||||
push(cmds, `ip -4 neigh flush to ${p.address} dev ${q(p.dev)}`);
|
||||
push(errs, ...run(cmds));
|
||||
let ft = load_ns_rules(p);
|
||||
if (ft.err)
|
||||
push(errs, ft.err);
|
||||
push(errs, ...run(sync_rules(p, ifnames)));
|
||||
|
||||
if (length(errs)) {
|
||||
log(`like-home routing failed, using the direct path: ${errs[0]}`);
|
||||
let why = { code: 'setup', detail: errs[0] };
|
||||
if (sprintf('%J', read_json(STATE, {}).error) != sprintf('%J', why))
|
||||
log(L_('failed - internet goes out directly for now'), 'error', errs[0]);
|
||||
remove(ifnames);
|
||||
write_json(STATE, { error: `Setup failed: ${errs[0]}` }, 0o644);
|
||||
return { error: errs[0] };
|
||||
}
|
||||
// Keep the chosen LAN address stable across restarts.
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
if (c.get('dawnline', 'settings', 'lan_address') != p.address) {
|
||||
c.set('dawnline', 'settings', 'settings');
|
||||
c.set('dawnline', 'settings', 'lan_address', p.address);
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
write_json(STATE, { error: why }, 0o644);
|
||||
return { error: why };
|
||||
}
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
|
||||
log(`like-home routing: ${p.dev} as ${p.address}`);
|
||||
write_json(STATE, { applied: time(), plan: p, transit: p.transit, fast: ft.fast }, 0o644);
|
||||
if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
|
||||
log(sprintf(L_('is on · traffic enters %s as %s'), p.dev, p.address), 'up');
|
||||
else if (!healthy)
|
||||
log(sprintf(L_('was broken - set up again (%s as %s)'), p.dev, p.address), 'repair');
|
||||
// Once, not again on every apply while the module is still missing.
|
||||
if (!ft.fast && last.fast !== false)
|
||||
log(L_('runs without its fast path'), 'info', join('\n', [
|
||||
L_('Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline.'),
|
||||
ft.slow,
|
||||
]));
|
||||
return p;
|
||||
};
|
||||
|
||||
/** Last applied state for views and health checks. */
|
||||
/**
|
||||
* Keep the chosen LAN address stable across restarts (settings.lan_address).
|
||||
* Called by dawnline.apply once its own lock is released: the config lock is
|
||||
* never taken inside it.
|
||||
*/
|
||||
export function remember(p) {
|
||||
if (!p?.address || settings().lan_address == p.address)
|
||||
return;
|
||||
store.transact((c, m) => {
|
||||
c.set('dawnline', 'settings', 'settings');
|
||||
c.set('dawnline', 'settings', 'lan_address', p.address);
|
||||
});
|
||||
};
|
||||
|
||||
/** Last applied state for views and health checks; `error` says why it is off (error_text). */
|
||||
export function status() {
|
||||
let s = read_json(STATE, {});
|
||||
if (s.plan)
|
||||
@@ -439,7 +631,7 @@ export function status() {
|
||||
dev: s.plan.dev, address: s.plan.address, dns: s.plan.dns, gateway: s.plan.gateway, transit: s.plan.tx_ns,
|
||||
bridged: replace(readlink(`/sys/class/net/${LAN_ROOT}/master`) ?? '', /^.*\//, '') == s.plan.dev,
|
||||
};
|
||||
return { active: false, off: !!s.off, error: s.error };
|
||||
return { active: false, off: !!s.off, error: error_text(s.error) };
|
||||
};
|
||||
|
||||
/** The DNS address tunnel clients should use while the loop is up. */
|
||||
@@ -450,33 +642,6 @@ export function client_dns() {
|
||||
|
||||
/* ---------- plain resolver for Home-only clients ---------- */
|
||||
|
||||
function wan_dns() {
|
||||
let out = [];
|
||||
let snap = net.snapshot();
|
||||
let wan = snap.devices[snap.wan]?.logical;
|
||||
for (let name in uniq([ wan, 'wan', 'wan6' ])) {
|
||||
if (!name)
|
||||
continue;
|
||||
try {
|
||||
let st = json(sh_out(`ubus call network.interface.${name} status 2>/dev/null`) || 'null');
|
||||
for (let a in st?.['dns-server'] ?? [])
|
||||
if (match(a, /^[0-9.]+$/))
|
||||
push(out, a);
|
||||
}
|
||||
catch (e) {}
|
||||
}
|
||||
return length(out) ? uniq(out) : FALLBACK_DNS;
|
||||
}
|
||||
|
||||
/** Local domain of the LAN DNS (dnsmasq `domain`, else the Dawnline hostname domain). */
|
||||
function lan_domain(m) {
|
||||
let c = cursor();
|
||||
c.load('dhcp');
|
||||
let d = null;
|
||||
c.foreach('dhcp', 'dnsmasq', (s) => { d ??= s.domain; });
|
||||
return uniq(filter([ d, m.settings.domain ], (x) => x));
|
||||
}
|
||||
|
||||
/** The DNS your LAN gets from DHCP (option 6), else the router on the LAN. */
|
||||
export function lan_dns() {
|
||||
let st = status();
|
||||
@@ -485,7 +650,10 @@ export function lan_dns() {
|
||||
let snap = net.snapshot();
|
||||
let d = snap.devices[snap.lan];
|
||||
let a = d?.addrs?.[0];
|
||||
return a ? (dhcp_facts(d.logical, cidr_of(a))?.dns ?? split(a, '/')[0]) : null;
|
||||
if (!a)
|
||||
return null;
|
||||
let lan = parse_cidr(a);
|
||||
return (lan ? dhcp_facts(d.logical, lan).dns : null) ?? split(a, '/')[0];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -494,62 +662,17 @@ export function lan_dns() {
|
||||
*/
|
||||
export function resolver_target() {
|
||||
let st = status();
|
||||
return st.active && st.transit ? { mode: 'ns', address: st.transit, port: 53 } : { mode: 'root', port: RESOLVER_PORT };
|
||||
return st.active && st.transit ? { mode: 'ns', address: st.transit, port: 53 } : { mode: 'root', port: resolver.PORT };
|
||||
};
|
||||
|
||||
/**
|
||||
* Write the resolver config; returns true when it changed (the running
|
||||
* instance is then restarted by procd's respawn after a kill). The first line
|
||||
* tells /usr/libexec/dawnline/resolver where to run it.
|
||||
*/
|
||||
/** Write the resolver config where it should run now; true when it changed (see dawnline.resolver). */
|
||||
export function sync_resolver(m) {
|
||||
ensure_dir('/var/etc');
|
||||
let ifs = map(filter(values(m.servers), (s) => s.private_key), (s) => s.ifname);
|
||||
let target = resolver_target();
|
||||
let lan = lan_dns();
|
||||
let lines = [
|
||||
`# mode=${target.mode}`,
|
||||
'# Generated by Dawnline: plain DNS for Home-only tunnel clients.',
|
||||
`port=${target.port}`,
|
||||
'no-hosts',
|
||||
'bogus-priv',
|
||||
'cache-size=1000',
|
||||
`pid-file=${RESOLVER_PID}`,
|
||||
'user=dnsmasq',
|
||||
'group=dnsmasq',
|
||||
];
|
||||
if (target.mode == 'ns') {
|
||||
push(lines, `listen-address=${target.address}`, 'bind-interfaces', 'no-resolv');
|
||||
// Upstream from the transit address: forwarded through the router to the WAN.
|
||||
for (let a in wan_dns())
|
||||
push(lines, `server=${a}@${target.address}`);
|
||||
}
|
||||
else {
|
||||
push(lines, 'bind-dynamic', ...map(ifs, (i) => `interface=${i}`), `resolv-file=${RESOLVER_RESOLV}`);
|
||||
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
|
||||
if ((readfile(RESOLVER_RESOLV) ?? '') != resolv) {
|
||||
writefile(RESOLVER_RESOLV, resolv);
|
||||
system(`chmod 644 ${RESOLVER_RESOLV}`);
|
||||
}
|
||||
}
|
||||
if (lan)
|
||||
for (let d in lan_domain(m))
|
||||
push(lines, `server=/${d}/${lan}`);
|
||||
let conf = join('\n', lines) + '\n';
|
||||
if ((readfile(RESOLVER_CONF) ?? '') == conf)
|
||||
return false;
|
||||
writefile(RESOLVER_CONF, conf);
|
||||
system(`chmod 644 ${RESOLVER_CONF}`);
|
||||
let pid = trim(readfile(RESOLVER_PID) ?? '');
|
||||
if (match(pid, /^[0-9]+$/))
|
||||
system(`kill ${pid} 2>/dev/null`);
|
||||
return true;
|
||||
return resolver.sync(m, resolver_target(), lan_dns());
|
||||
};
|
||||
|
||||
/** True when the resolver process is alive. */
|
||||
export function resolver_running() {
|
||||
let pid = trim(readfile(RESOLVER_PID) ?? '');
|
||||
return match(pid, /^[0-9]+$/) != null && stat(`/proc/${pid}`) != null;
|
||||
return resolver.running();
|
||||
};
|
||||
|
||||
export const RESOLVER = { port: RESOLVER_PORT, conf: RESOLVER_CONF };
|
||||
export const RESOLVER = { port: resolver.PORT, conf: resolver.CONF };
|
||||
@@ -0,0 +1,149 @@
|
||||
// Dawnline — the live meter (the Overview's Speed now): each server's
|
||||
// throughput, one point a second over the last two minutes.
|
||||
//
|
||||
// The meter RPC (dawnline.rpc.status) calls want() and read(); the agent's
|
||||
// watcher makes a point from every read it already does (sample(), point())
|
||||
// and keeps the last two minutes in memory (keep()) whether anyone looks or
|
||||
// not, so a look gets them all at once. It writes them to FILE (save()) only
|
||||
// while WANT is younger than WANT_FOR seconds: the first second of a look,
|
||||
// then with each new point. When WANT goes stale it removes FILE: with nobody
|
||||
// looking the watcher pays a little arithmetic and one stat() a second, and
|
||||
// writes nothing. FILE holds server ids and byte rates only, no keys, names
|
||||
// or personal codes. Who is online and the per-minute rates are not here
|
||||
// (dawnline.live, the agent's tick).
|
||||
//
|
||||
// Bytes are the peers' counters (dawnline.awg.dump): tx includes the
|
||||
// disguise (S prefixes, padding, junk), rx the packets as they were
|
||||
// received without their prefix, so both are close to what is on the wire.
|
||||
|
||||
import { writefile, stat, unlink } from 'fs';
|
||||
import { read_json, write_file, ensure_dir, RUN_DIR } from 'dawnline.util';
|
||||
|
||||
/** Touched by every meter RPC: the watcher samples while it is fresh. */
|
||||
export const WANT = `${RUN_DIR}/meter.want`;
|
||||
/** The points, written by the watcher each second while WANT is fresh. */
|
||||
export const FILE = `${RUN_DIR}/meter.json`;
|
||||
/** Seconds after the last meter RPC the watcher keeps sampling. */
|
||||
export const WANT_FOR = 10;
|
||||
/** Points kept: two minutes, one a second. */
|
||||
export const POINTS = 120;
|
||||
|
||||
/** Ask the watcher to sample for the next WANT_FOR seconds (the meter RPC). */
|
||||
export function want() {
|
||||
ensure_dir(RUN_DIR);
|
||||
writefile(WANT, `${time()}`);
|
||||
};
|
||||
|
||||
/** Someone asked for the meter within WANT_FOR seconds of `now`. */
|
||||
export function wanted(now) {
|
||||
let st = stat(WANT);
|
||||
return st != null && now - st.mtime < WANT_FOR && st.mtime - now < WANT_FOR;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the watcher wrote, for the RPC: { now, want: WANT_FOR, keep: POINTS,
|
||||
* ts (newest point, 0 for none), points } with only the points newer than
|
||||
* `since` when it is given (a page that polls asks for what it lacks).
|
||||
* No points when nobody asked within WANT_FOR seconds or the agent is not
|
||||
* running: FILE is gone (the agent removes it as it stops and starts), or,
|
||||
* from one that died while someone looked, its newest point is over
|
||||
* WANT_FOR seconds old (ts then stops moving).
|
||||
*/
|
||||
export function read(since) {
|
||||
let f = read_json(FILE, null);
|
||||
let ts = +(f?.ts ?? 0);
|
||||
let pts = type(f?.points) == 'array' && time() - ts <= WANT_FOR ? f.points : [];
|
||||
if (since > 0)
|
||||
pts = filter(pts, (p) => p.ts > since);
|
||||
return { now: time(), want: WANT_FOR, keep: POINTS, ts: ts, points: pts };
|
||||
};
|
||||
|
||||
/** Monotonic seconds, with the fraction: the gap between two samples. */
|
||||
function mono() {
|
||||
let c = clock(true);
|
||||
return c[0] + c[1] / 1e9;
|
||||
}
|
||||
|
||||
/**
|
||||
* One sample at `now` from the dump the watcher just read (`d`): { t, ts,
|
||||
* servers: [ server id ] (those whose tunnel was read), dev: { device id:
|
||||
* [ rx, tx, server id ] } (its peer's counters, on those servers) }. Nothing
|
||||
* but the dump is read.
|
||||
*/
|
||||
export function sample(m, d, now) {
|
||||
let s = { t: mono(), ts: now, servers: [], dev: {} };
|
||||
let read = {};
|
||||
for (let sid, srv in m.servers)
|
||||
if (d.reads[srv.ifname] == 'read') {
|
||||
read[sid] = true;
|
||||
push(s.servers, sid);
|
||||
}
|
||||
for (let id, dev in m.devices) {
|
||||
let peer = d.peers[dev.public_key];
|
||||
let sid = m.people[dev.person]?.server;
|
||||
if (peer && read[sid])
|
||||
s.dev[id] = [ peer.rx, peer.tx, sid ];
|
||||
}
|
||||
return s;
|
||||
};
|
||||
|
||||
/** A counter's change, 0 when it went down (a tunnel set up again starts from zero). */
|
||||
function delta(a, b) {
|
||||
return (b ?? 0) >= (a ?? 0) ? (b ?? 0) - (a ?? 0) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The point between samples `a` and `b`, null when they are not a second or
|
||||
* so apart (the first sample, a stalled watcher): { ts, servers: { server
|
||||
* id: [ rx, tx ] } }, bytes per second of its devices together (rx what came
|
||||
* from them, tx what went to them, as a server's per-minute `rate`), for
|
||||
* every server whose tunnel `b` read ([ 0, 0 ] when nothing moved). A device
|
||||
* is counted from its second sample on, on the server it was on in both.
|
||||
*/
|
||||
export function point(a, b) {
|
||||
let dt = b.t - a.t;
|
||||
if (!(dt > 0.2 && dt < 5))
|
||||
return null;
|
||||
let sum = {};
|
||||
for (let sid in b.servers)
|
||||
sum[sid] = [ 0, 0 ];
|
||||
for (let id, v in b.dev) {
|
||||
let o = a.dev[id];
|
||||
if (!o || o[2] != v[2])
|
||||
continue;
|
||||
sum[v[2]][0] += delta(o[0], v[0]);
|
||||
sum[v[2]][1] += delta(o[1], v[1]);
|
||||
}
|
||||
let p = { ts: b.ts, servers: {} };
|
||||
for (let sid, v in sum)
|
||||
p.servers[sid] = [ int(v[0] / dt), int(v[1] / dt) ];
|
||||
return p;
|
||||
};
|
||||
|
||||
/**
|
||||
* Keep point `p` in `ring` ([ [ ts, the point as JSON ] ], newest last; each
|
||||
* point is turned into text once, when it is made, not again every second for
|
||||
* as long as it is kept): at most POINTS of them, none older than POINTS
|
||||
* seconds before `p` (the watcher may have stalled in between) and none from
|
||||
* its second or later (the clock went back).
|
||||
*/
|
||||
export function keep(ring, p) {
|
||||
while (length(ring) && ring[length(ring) - 1][0] >= p.ts)
|
||||
pop(ring);
|
||||
push(ring, [ p.ts, sprintf('%J', p) ]);
|
||||
while (length(ring) > POINTS || ring[0][0] <= p.ts - POINTS)
|
||||
shift(ring);
|
||||
};
|
||||
|
||||
/** Write the points kept in `ring` (keep()) to FILE. */
|
||||
export function save(ring) {
|
||||
let ts = length(ring) ? ring[length(ring) - 1][0] : 0;
|
||||
ensure_dir(RUN_DIR);
|
||||
write_file(FILE, `{"ts":${ts},"points":[${join(',', map(ring, (r) => r[1]))}]}`, 0o644);
|
||||
};
|
||||
|
||||
/** Nobody looks any more: FILE goes (the next look gets the points kept then). */
|
||||
export function stop() {
|
||||
if (stat(FILE))
|
||||
unlink(FILE);
|
||||
};
|
||||
@@ -0,0 +1,114 @@
|
||||
// Dawnline — one-time steps for routers set up by older versions. Each one
|
||||
// checks first and writes nothing when there is nothing to do; dawnline.apply
|
||||
// runs them before it takes its own lock (changes to /etc/config/dawnline go
|
||||
// through dawnline.store and its config lock).
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { stat, unlink } from 'fs';
|
||||
import { q, slog } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as store from 'dawnline.store';
|
||||
import { L_ } from 'dawnline.i18n';
|
||||
|
||||
const LAN_CGI = '/www/cgi-bin/dawnline-portal';
|
||||
const LAN_CGI_URL = '/cgi-bin/dawnline-portal';
|
||||
|
||||
/** Every personal code is a word code; older random ones are replaced (their links stop working). */
|
||||
function word_codes() {
|
||||
let old = (s) => s.code != null && !match(s.code, core.WORD_CODE);
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let any = false;
|
||||
c.foreach('dawnline', 'person', (s) => {
|
||||
if (old(s))
|
||||
any = true;
|
||||
});
|
||||
if (!any)
|
||||
return;
|
||||
store.transact((w, m) => {
|
||||
w.foreach('dawnline', 'person', (s) => {
|
||||
if (old(s)) {
|
||||
w.set('dawnline', s['.name'], 'code', core.new_code());
|
||||
w.delete('dawnline', s['.name'], 'words');
|
||||
}
|
||||
});
|
||||
});
|
||||
slog('dawnline', 'info', L_('moved to word codes'), null, L_('Personal links'));
|
||||
}
|
||||
|
||||
/*
|
||||
* Older versions answered on 443 at home through LuCI's web server (its error
|
||||
* page ran the portal CGI). The portal now keeps its own port: remove that.
|
||||
*/
|
||||
export function uhttpd() {
|
||||
let c = cursor();
|
||||
c.load('uhttpd');
|
||||
if (c.get('uhttpd', 'main', 'error_page') == LAN_CGI_URL) {
|
||||
c.delete('uhttpd', 'main', 'error_page');
|
||||
c.commit('uhttpd');
|
||||
system('/etc/init.d/uhttpd reload >/dev/null 2>&1');
|
||||
system(`logger -t dawnline ${q('portal removed from the LuCI web server')}`);
|
||||
}
|
||||
if (stat(LAN_CGI))
|
||||
unlink(LAN_CGI);
|
||||
// The old setting itself.
|
||||
let d = cursor();
|
||||
d.load('dawnline');
|
||||
if (d.get('dawnline', 'settings', 'portal_443') != null)
|
||||
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
|
||||
};
|
||||
|
||||
/** The portal names itself after the server now (the breadcrumb, the tab): its own title setting is gone. */
|
||||
function portal_title() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
if (c.get('dawnline', 'settings', 'portal_title') != null)
|
||||
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_title'));
|
||||
}
|
||||
|
||||
/*
|
||||
* Steps that cannot tell from the config whether they ran are recorded in
|
||||
* `settings.migrated` (a list), so they run exactly once.
|
||||
*/
|
||||
function migrated(c, name) {
|
||||
let done = c.get('dawnline', 'settings', 'migrated') ?? [];
|
||||
return index(type(done) == 'array' ? done : [ done ], name) >= 0;
|
||||
}
|
||||
|
||||
function mark_migrated(w, name) {
|
||||
let done = w.get('dawnline', 'settings', 'migrated') ?? [];
|
||||
w.set('dawnline', 'settings', 'migrated', [ ...(type(done) == 'array' ? done : [ done ]), name ]);
|
||||
}
|
||||
|
||||
/*
|
||||
* 1380 was every server's stored MTU before it became automatic (by device
|
||||
* type and disguise). Once only: an admin may choose 1380 again on purpose.
|
||||
*/
|
||||
function auto_mtu() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
if (migrated(c, 'auto_mtu'))
|
||||
return;
|
||||
let any = false;
|
||||
c.foreach('dawnline', 'server', (s) => {
|
||||
if (s.mtu == '1380')
|
||||
any = true;
|
||||
});
|
||||
store.transact((w, m) => {
|
||||
w.foreach('dawnline', 'server', (s) => {
|
||||
if (s.mtu == '1380')
|
||||
w.delete('dawnline', s['.name'], 'mtu');
|
||||
});
|
||||
mark_migrated(w, 'auto_mtu');
|
||||
});
|
||||
if (any)
|
||||
slog('dawnline', 'info', L_('MTU is now automatic'), null, L_('Servers'));
|
||||
}
|
||||
|
||||
/** All of them, in order. */
|
||||
export function run() {
|
||||
word_codes();
|
||||
uhttpd();
|
||||
auto_mtu();
|
||||
portal_title();
|
||||
};
|
||||
@@ -9,17 +9,22 @@
|
||||
// lan_device extra interfaces that count as the home network (list)
|
||||
//
|
||||
// Home access is enforced by destination: the networks routed out of the
|
||||
// chosen interfaces form the nft `lan_nets` set, and the tunnel's firewall
|
||||
// zone gets a forwarding to each of their zones.
|
||||
// chosen interfaces form the server's nft `home_<id>` set, and the tunnel's
|
||||
// firewall zone gets a forwarding to each of their zones.
|
||||
|
||||
import { readfile, readlink, lsdir, stat } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { sh_out, ip2int, int2ip, uniq } from 'dawnline.util';
|
||||
import { sh_out, ip2int, int2ip, cidr_any, uniq } from 'dawnline.util';
|
||||
|
||||
const SYS = '/sys/class/net';
|
||||
/** Links Dawnline creates itself (dawnline.loop); never offered as interfaces. */
|
||||
export const INTERNAL = { transit: 'dlx0', lan: 'dll0' };
|
||||
const VPN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc', 'pptp', 'l2tp', 'gre', 'gretap', 'vti', 'xfrm' ];
|
||||
const VPN_NAMES = /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/;
|
||||
// Never the WAN while another default route exists: VPN clients. (PPTP and
|
||||
// L2TP stay eligible: some ISPs connect the WAN with them.)
|
||||
const NOT_WAN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc' ];
|
||||
const NOT_WAN_NAMES = /^(wg|awg|tun|tap|ovpn)/;
|
||||
// Kernel placeholder devices that never carry a network on their own.
|
||||
const NOISE = /^(ifb|teql|sit|ip6tnl|gre|gretap|erspan|ip6gre|ip6gretap|ip_vti|ip6_vti|tunl|bond)[0-9]*$/;
|
||||
const PRIVATE = [ [ '10.0.0.0', 8 ], [ '172.16.0.0', 12 ], [ '192.168.0.0', 16 ], [ '100.64.0.0', 10 ] ];
|
||||
@@ -48,16 +53,8 @@ function ubus_json(path, method) {
|
||||
|
||||
/** "a.b.c.d[/len]" → { net, prefix, size } for any prefix 1-32; null for default or junk. */
|
||||
function net_of(s) {
|
||||
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
|
||||
if (ip == null || prefix < 1 || prefix > 32)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
if (prefix == 1)
|
||||
size = 2147483648;
|
||||
return { net: ip - ip % size, prefix, size };
|
||||
let c = cidr_any(s);
|
||||
return c && c.prefix >= 1 ? c : null;
|
||||
}
|
||||
|
||||
function net_str(n) {
|
||||
@@ -107,12 +104,12 @@ export function snapshot(fresh) {
|
||||
return cache;
|
||||
|
||||
// Networks reachable through each device (main table, IPv4).
|
||||
let routes = {}, wan_dev = null;
|
||||
let routes = {}, defaults = [];
|
||||
for (let r in ip_json('-4 route show table main')) {
|
||||
if (!r.dev)
|
||||
continue;
|
||||
if (r.dst == 'default') {
|
||||
wan_dev ??= r.dev;
|
||||
push(defaults, r);
|
||||
continue;
|
||||
}
|
||||
push(routes[r.dev] ??= [], r.dst);
|
||||
@@ -130,6 +127,19 @@ export function snapshot(fresh) {
|
||||
if (dev && !logical[dev])
|
||||
logical[dev] = { name: i.interface, proto: i.proto, up: i.up };
|
||||
}
|
||||
// The WAN: the default route with the lowest metric that does not go into
|
||||
// a VPN client (its default route is not where the tunnels listen); only
|
||||
// VPN routes: the lowest of them.
|
||||
let vpn = (dev) => index(NOT_WAN_PROTOS, logical[dev]?.proto) >= 0 || match(dev, NOT_WAN_NAMES) != null;
|
||||
let wan_dev = null, wan_metric = null, wan_vpn = true;
|
||||
for (let r in defaults) {
|
||||
let v = vpn(r.dev), metric = r.metric ?? 0;
|
||||
if (wan_dev == null || (wan_vpn && !v) || (wan_vpn == v && metric < wan_metric)) {
|
||||
wan_dev = r.dev;
|
||||
wan_metric = metric;
|
||||
wan_vpn = v;
|
||||
}
|
||||
}
|
||||
let zone_by_net = {}, zone_by_dev = {}, zones = [];
|
||||
let fc = cursor();
|
||||
fc.load('firewall');
|
||||
@@ -153,7 +163,7 @@ export function snapshot(fresh) {
|
||||
let flags = hex(sysread(dev, 'flags') || '0');
|
||||
let kind = +(sysread(dev, 'type') || '0');
|
||||
let master = readlink(`${SYS}/${dev}/master`);
|
||||
master = master ? replace(master, /^.*\//, '') : null;
|
||||
master = master ? substr(master, rindex(master, '/') + 1) : null;
|
||||
let bridge = stat(`${SYS}/${dev}/bridge`) != null;
|
||||
let wifi = stat(`${SYS}/${dev}/phy80211`) != null || stat(`${SYS}/${dev}/wireless`) != null;
|
||||
let nets = routes[dev] ? collapse(routes[dev]) : [];
|
||||
@@ -163,7 +173,7 @@ export function snapshot(fresh) {
|
||||
let cat;
|
||||
if (wifi)
|
||||
cat = 'wifi';
|
||||
else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/))
|
||||
else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, VPN_NAMES))
|
||||
cat = 'vpn';
|
||||
else if (kind == 1 || bridge)
|
||||
cat = 'ethernet';
|
||||
@@ -238,7 +248,9 @@ export function server_net(srv, snap) {
|
||||
if (dev == wan.dev || dev == srv.ifname || devs[dev]?.master)
|
||||
continue;
|
||||
let d = devs[dev];
|
||||
let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? null, missing: !d };
|
||||
// The detected LAN missing for a moment (bridge recreated) keeps its zone,
|
||||
// so its forwardings are not removed meanwhile.
|
||||
let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? (p[1] ? srv.lan_zone : null), missing: !d };
|
||||
push(home, h);
|
||||
push(nets, ...h.nets);
|
||||
if (h.zone)
|
||||
@@ -266,3 +278,31 @@ export function wan_address(srv, snap) {
|
||||
let a = snap.devices[server_net(srv, snap).wan.dev]?.addrs?.[0];
|
||||
return a ? split(a, '/')[0] : null;
|
||||
};
|
||||
|
||||
/** Names of devices at home by address: DHCP leases, then static hosts. */
|
||||
export function lan_names() {
|
||||
let out = {};
|
||||
for (let line in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) {
|
||||
let f = split(line, ' ');
|
||||
if (length(f) >= 4 && f[3] != '*')
|
||||
out[f[2]] = f[3];
|
||||
}
|
||||
let c = cursor();
|
||||
c.foreach('dhcp', 'host', (h) => {
|
||||
if (h.ip && h.name)
|
||||
out[h.ip] ??= h.name;
|
||||
});
|
||||
return out;
|
||||
};
|
||||
|
||||
// A module constant, compiled once: event_hosts runs for every event of the log.
|
||||
const ANY_IPV4 = /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g;
|
||||
|
||||
/** Event addresses that belong to devices at home, with their names ({ ip: name }). */
|
||||
export function event_hosts(e, names) {
|
||||
let out = null;
|
||||
for (let ip in match(e.detail ?? '', ANY_IPV4) ?? [])
|
||||
if (names[ip[0]])
|
||||
(out ??= {})[ip[0]] = names[ip[0]];
|
||||
return out;
|
||||
};
|
||||
@@ -0,0 +1,175 @@
|
||||
// Dawnline — netifd: one AmneziaWG interface per server, named after its
|
||||
// ifname and marked `_dawnline` = server id. Only interfaces Dawnline created
|
||||
// are changed or removed: a name already used by another interface (`lan`, a
|
||||
// tunnel of your own, one from an imported config) is left alone and the
|
||||
// server is reported instead. Why a server is kept down is kept in
|
||||
// core.BLOCKED as a code with its values (awg.blocked_text says it).
|
||||
// drift() tells the watchdog when one of them was edited outside Dawnline.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { stat, unlink, writefile } from 'fs';
|
||||
import { q, uci_put, uci_section, ack_config, iface_intent, ensure_dir, read_json, write_json, slog, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import { L_ } from 'dawnline.i18n';
|
||||
|
||||
// Set while AmneziaWG is missing and that was logged (once until it is back).
|
||||
const NO_AWG = `${RUN_DIR}/netifd-no-awg`;
|
||||
|
||||
function log(who, msg, level, detail) {
|
||||
slog('dawnline', level ?? 'info', msg, detail, who);
|
||||
}
|
||||
|
||||
/** The server id that owns network.<ifname>: null when the section is free, '' when someone else's. */
|
||||
export function owner(ifname, c) {
|
||||
if (!c) {
|
||||
c = cursor();
|
||||
c.load('network');
|
||||
}
|
||||
if (c.get('network', ifname) == null)
|
||||
return null;
|
||||
return c.get('network', ifname, '_dawnline') ?? '';
|
||||
};
|
||||
|
||||
/** What sync() writes into network.<ifname> apart from the markers: what netifd sets the tunnel up from. */
|
||||
function options(srv) {
|
||||
let o = awg.netifd_options(srv);
|
||||
o.disabled = srv.enabled ? null : '1';
|
||||
o.auto = srv.enabled ? null : '0';
|
||||
return o;
|
||||
}
|
||||
|
||||
/** Bring network config in line with the servers; true when it changed. */
|
||||
export function sync(m) {
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
let changed = false, touched = [], want = {};
|
||||
// Servers whose interface can't be set up (core.BLOCKED), each logged once while it lasts.
|
||||
let was = read_json(core.BLOCKED, {}), blocked = {};
|
||||
let block = (srv, why, detail) => {
|
||||
blocked[srv.id] = why;
|
||||
// The rest of this apply works from the same model: no tunnel for it there either.
|
||||
srv.blocked = why;
|
||||
if (sprintf('%J', was[srv.id]) != sprintf('%J', why))
|
||||
log(srv.name, awg.blocked_note(why), 'error', detail);
|
||||
};
|
||||
|
||||
// Without amneziawg-tools there is no protocol script: changing or bringing
|
||||
// up an interface would only stop a tunnel that is still running.
|
||||
let tools = awg.state().tools;
|
||||
if (tools && stat(NO_AWG))
|
||||
unlink(NO_AWG);
|
||||
else if (!tools && length(filter(values(m.servers), (s) => s.private_key)) && !stat(NO_AWG)) {
|
||||
log('AmneziaWG', L_("isn't installed: tunnels were left as they are"), 'error', L_('Install it in Dawnline → Components.'));
|
||||
ensure_dir(RUN_DIR);
|
||||
writefile(NO_AWG, `${time()}`);
|
||||
}
|
||||
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.private_key)
|
||||
continue;
|
||||
let ifn = srv.ifname;
|
||||
if (!core.valid_ifname(ifn)) {
|
||||
block(srv, { code: 'ifname', ifname: ifn }, 'Interface name: 1-12 lowercase letters, digits or _.');
|
||||
continue;
|
||||
}
|
||||
let own = owner(ifn, c);
|
||||
if (own != null && own != id) {
|
||||
block(srv, { code: 'taken', ifname: ifn },
|
||||
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
|
||||
continue;
|
||||
}
|
||||
// Disguise values AmneziaWG refuses or crashes on (a hand edit in uci;
|
||||
// import and restore refuse them) never reach setconf and the kernel.
|
||||
// A disguise this build cannot run (a 3.1 preset after a rollback to
|
||||
// 2.0): the kernel would drop those options silently and run a tunnel
|
||||
// no device can reach. Down, and said so, until the build or the
|
||||
// disguise is changed.
|
||||
let why = !tools ? null : length(awg.obf_unsafe(srv.obf)) ? { code: 'disguise_invalid' } : awg.obf_unsupported(srv.obf);
|
||||
if (why) {
|
||||
block(srv, why, awg.blocked_fix(why));
|
||||
continue;
|
||||
}
|
||||
delete srv.blocked;
|
||||
want[ifn] = true;
|
||||
if (!tools)
|
||||
continue;
|
||||
// Per server: with several, each changed one has to be brought up again.
|
||||
let mine = uci_section(c, 'network', ifn, 'interface');
|
||||
for (let k, v in options(srv))
|
||||
if (uci_put(c, 'network', ifn, k, v))
|
||||
mine = true;
|
||||
// The markers are saved, but netifd does not read them: a renamed server
|
||||
// keeps its tunnel and every session in it.
|
||||
if (uci_put(c, 'network', ifn, '_dawnline', id))
|
||||
changed = true;
|
||||
// For the log once the server is gone.
|
||||
if (uci_put(c, 'network', ifn, '_dawnline_name', srv.name))
|
||||
changed = true;
|
||||
if (mine) {
|
||||
changed = true;
|
||||
push(touched, ifn);
|
||||
// The hotplug log says why the tunnel goes down (not a failure).
|
||||
iface_intent(ifn, srv.enabled ? 'settings' : 'off', srv.name);
|
||||
}
|
||||
}
|
||||
|
||||
if (sprintf('%J', blocked) != sprintf('%J', was)) {
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(core.BLOCKED, blocked, 0o644);
|
||||
}
|
||||
|
||||
// Remove interfaces Dawnline created for servers that no longer exist.
|
||||
let stale = [];
|
||||
c.foreach('network', 'interface', (s) => {
|
||||
if (s._dawnline && !want[s['.name']])
|
||||
push(stale, s['.name']);
|
||||
});
|
||||
for (let ifn in stale) {
|
||||
iface_intent(ifn, 'removed', c.get('network', ifn, '_dawnline_name') ?? ifn);
|
||||
system(`ifdown ${q(ifn)} 2>/dev/null`);
|
||||
c.delete('network', ifn);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
c.commit('network');
|
||||
ack_config([ 'network' ]);
|
||||
}
|
||||
// Only the markers changed: nothing for netifd to read (it ignores them, and so does a reload).
|
||||
if (length(touched) || length(stale)) {
|
||||
system('ubus call network reload');
|
||||
for (let ifn in touched)
|
||||
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
|
||||
system(`ifup ${q(ifn)}`);
|
||||
// Each tunnel's own line (restarting, turned off, removed) comes from hotplug.
|
||||
system(`logger -t dawnline ${q('network updated: ' + join(', ', [ ...touched, ...stale ]))}`);
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
|
||||
/**
|
||||
* For the watchdog: what of each running server's interface differs from
|
||||
* what sync() writes, by option name (a LuCI or uci edit of network.<ifname>,
|
||||
* which would otherwise last until the next apply): { server id: [ names ] },
|
||||
* an empty list when it is as Dawnline set it. Only enabled servers whose
|
||||
* section exists and is theirs (a missing one is the tunnel probe's); the
|
||||
* markers are not compared, netifd does not read them. A dry run on a
|
||||
* cursor of its own: nothing is saved. Meaningful while amneziawg-tools is
|
||||
* installed (sync() leaves the interfaces alone without it).
|
||||
*/
|
||||
export function drift(m) {
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
let out = {};
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.enabled || !length(core.tunnels(srv)) || owner(srv.ifname, c) != id || c.get('network', srv.ifname) != 'interface')
|
||||
continue;
|
||||
let diff = [];
|
||||
for (let k, v in options(srv))
|
||||
if (uci_put(c, 'network', srv.ifname, k, v))
|
||||
push(diff, k);
|
||||
out[id] = diff;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
@@ -0,0 +1,282 @@
|
||||
// Dawnline — the nft table `inet dawnline`: each person's access, enforced
|
||||
// on the tunnel interfaces before anything else on the router sees the
|
||||
// traffic, and where tunnel DNS goes. Its shape follows the servers and their
|
||||
// home networks (rebuild); who is in which set follows people's state and
|
||||
// changes often (update, one atomic transaction).
|
||||
|
||||
import { unlink } from 'fs';
|
||||
import { sh, ensure_dir, write_file, rand_hex, ip2int, uniq, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
|
||||
/** Private IPv4 ranges: internet people never reach them (awg.BYPASS4 is the rest). */
|
||||
export const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
|
||||
/** The sets whose members change at run time (update replaces them together). */
|
||||
const SETS = [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'svc_host', 'dns_real' ];
|
||||
|
||||
function ip4(a) {
|
||||
return ip2int(a ?? '') != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-person runtime membership: which tunnel addresses may reach what.
|
||||
* `snap` is the network (net.snapshot() when not given).
|
||||
*/
|
||||
export function access_sets(m, usage, states, snap) {
|
||||
// lan_ok: home access (the router itself, the mesh); lan_all: every home
|
||||
// network; lan_part: device . network for people limited to some networks;
|
||||
// mesh_pairs: device . device within a circle (or one person's own devices);
|
||||
// svc_ok: device . service . port; svc_host: device . service with no ports (all of them).
|
||||
let sets = {};
|
||||
for (let k in SETS)
|
||||
sets[k] = [];
|
||||
snap ??= net.snapshot();
|
||||
let homes = {}, groups = {};
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
// Off: paused, ended, over quota or out of hours. Addresses go into nft as they are: IPv4 only.
|
||||
if (!p || d.disabled || !ip4(d.address) || states[p.id] != 'active')
|
||||
continue;
|
||||
// Home names: the plain resolver (their internet does not use the tunnel).
|
||||
if (p.access == 'lan' && p.dns_mode == 'home')
|
||||
push(sets.dns_real, d.address);
|
||||
if (p.access == 'internet' || p.access == 'both')
|
||||
push(sets.inet_ok, d.address);
|
||||
if (p.access == 'both' || (p.access == 'lan' && !length(p.services))) {
|
||||
push(sets.lan_ok, d.address);
|
||||
let srv = m.servers[p.server];
|
||||
let h = homes[p.id] ??= srv ? core.person_home(srv, p, snap) : { all: true, nets: [] };
|
||||
if (h.all)
|
||||
push(sets.lan_all, d.address);
|
||||
else
|
||||
for (let n in h.nets)
|
||||
push(sets.lan_part, `${d.address} . ${n}`);
|
||||
// Who this device may reach directly: its circle, or at least its owner's devices.
|
||||
if (srv?.mesh == 'circles') {
|
||||
let ci = core.person_circle(m, p);
|
||||
push(groups[ci ? `c:${ci.id}` : `p:${p.id}`] ??= [], d.address);
|
||||
}
|
||||
}
|
||||
else if (p.access == 'lan')
|
||||
for (let sid in p.services) {
|
||||
let s = m.services[sid];
|
||||
if (!s || !ip4(s.address))
|
||||
continue;
|
||||
if (!length(s.ports))
|
||||
push(sets.svc_host, `${d.address} . ${s.address}`);
|
||||
for (let port in s.ports)
|
||||
if (match(port, /^[0-9]+$/))
|
||||
push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`);
|
||||
}
|
||||
}
|
||||
for (let g, addrs in groups)
|
||||
for (let a in addrs)
|
||||
for (let b in addrs)
|
||||
if (a != b)
|
||||
push(sets.mesh_pairs, `${a} . ${b}`);
|
||||
return sets;
|
||||
};
|
||||
|
||||
// Duplicate members (two devices with one address) would make the whole load fail.
|
||||
function set_elems(arr) {
|
||||
arr = uniq(arr);
|
||||
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
|
||||
}
|
||||
|
||||
/** The portal's TCP ports people may reach through the tunnel (never SSH, DNS or LuCI, whatever is stored). */
|
||||
function portal_ports(m) {
|
||||
if (!m.settings.portal_enabled)
|
||||
return [];
|
||||
let ok = (p) => p >= 1 && p <= 65535 && index([ 22, 53, 80, 443 ], p) < 0;
|
||||
let ports = filter([ m.settings.portal_port ], ok);
|
||||
if (core.portal_http(m) && ok(core.portal_http_port(m)))
|
||||
push(ports, core.portal_http_port(m));
|
||||
return ports;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the table is made from besides the model, read from the router: the
|
||||
* netns's DNS address (loop.client_dns), where the Home-only resolver runs
|
||||
* (loop.resolver_target), the LAN's DNS and the network snapshot.
|
||||
*/
|
||||
function router_ctx() {
|
||||
return { dns_addr: loop.client_dns(), resolver: loop.resolver_target(), lan_dns: loop.lan_dns(), snap: net.snapshot() };
|
||||
}
|
||||
|
||||
function table(m, sets, ctx) {
|
||||
ctx ??= router_ctx();
|
||||
let ifs = [], tun = [];
|
||||
let dns_addr = ctx.dns_addr;
|
||||
if (!ip4(dns_addr))
|
||||
dns_addr = null;
|
||||
let rt = ctx.resolver;
|
||||
let snap = ctx.snap;
|
||||
// Each server's home networks are its own: with several servers, "all
|
||||
// home" on one never reaches the other's networks (set lan_<id>).
|
||||
let homes = {};
|
||||
for (let id, srv in m.servers) {
|
||||
// Only valid interface names reach here (core.tunnels): they are written into the rules as strings.
|
||||
let tns = core.tunnels(srv);
|
||||
for (let t in tns) {
|
||||
push(ifs, `"${t.ifname}"`);
|
||||
push(tun, t.subnet);
|
||||
}
|
||||
if (length(tns))
|
||||
homes[id] = net.collapse(net.server_net(srv, snap).nets);
|
||||
}
|
||||
tun = net.collapse(tun);
|
||||
let t = [];
|
||||
push(t, 'table inet dawnline {');
|
||||
for (let id, nets in homes)
|
||||
push(t, ` set home_${id} { type ipv4_addr; flags interval; auto-merge; ${set_elems(nets)} }`);
|
||||
// Tunnel subnets are never "home", even inside a wider route to the LAN.
|
||||
push(t, ` set tun_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(tun)} }`);
|
||||
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
|
||||
push(t, ` set lan_all { type ipv4_addr; ${set_elems(sets.lan_all)} }`);
|
||||
push(t, ` set lan_part { type ipv4_addr . ipv4_addr; flags interval; ${set_elems(sets.lan_part)} }`);
|
||||
push(t, ` set mesh_pairs { type ipv4_addr . ipv4_addr; ${set_elems(sets.mesh_pairs)} }`);
|
||||
push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`);
|
||||
push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`);
|
||||
push(t, ` set svc_host { type ipv4_addr . ipv4_addr; ${set_elems(sets.svc_host)} }`);
|
||||
push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`);
|
||||
push(t, ' chain pre {');
|
||||
// Ahead of mangle-priority hooks (transparent proxies mark at -150).
|
||||
push(t, ' type filter hook prerouting priority -160; policy accept;');
|
||||
if (length(ifs))
|
||||
push(t, ` iifname { ${join(', ', ifs)} } jump guard`);
|
||||
push(t, ' }');
|
||||
push(t, ' chain guard {');
|
||||
push(t, ' meta nfproto ipv6 drop');
|
||||
// Every packet is judged by the rules below, not only the first of a
|
||||
// connection: a change of access cuts open connections too, instead of
|
||||
// letting a session or a long UDP flow run on for days. Only what has no
|
||||
// rule of its own passes on its connection: errors and the like, answers
|
||||
// to the admin's port forwards, and the router's own pings.
|
||||
push(t, ' ct state related accept');
|
||||
push(t, ' ct status dnat accept');
|
||||
push(t, ' icmp type { echo-request, echo-reply } fib daddr type local accept');
|
||||
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
|
||||
let pp = portal_ports(m);
|
||||
if (length(pp))
|
||||
// Their own portal, also with the VPN on (the address may be this router's).
|
||||
push(t, ` fib daddr type local tcp dport { ${join(', ', pp)} } accept`);
|
||||
// The router itself is part of home: for everyone with all of it, and for
|
||||
// people limited to some networks only on the addresses in those.
|
||||
push(t, ' fib daddr type local ip saddr @lan_all accept');
|
||||
push(t, ' fib daddr type local ip saddr . ip daddr @lan_part accept');
|
||||
push(t, ' fib daddr type local counter drop');
|
||||
if (dns_addr)
|
||||
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
|
||||
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
|
||||
for (let id, nets in homes)
|
||||
for (let tn in core.tunnels(m.servers[id]))
|
||||
push(t, ` iifname "${tn.ifname}" ip daddr @home_${id} ip daddr != @tun_nets ip saddr @lan_all accept`);
|
||||
push(t, ' ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept');
|
||||
// Devices with home access are part of home: they reach each other, where the
|
||||
// server allows it (everyone, or within circles). Within one server: the
|
||||
// firewall has no forwarding between different servers' zones.
|
||||
for (let id, srv in m.servers)
|
||||
for (let tn in core.tunnels(srv))
|
||||
if (srv.mesh == 'all')
|
||||
push(t, ` iifname "${tn.ifname}" ip saddr @lan_ok ip daddr @lan_ok accept`);
|
||||
else if (srv.mesh == 'circles')
|
||||
push(t, ` iifname "${tn.ifname}" ip saddr . ip daddr @mesh_pairs accept`);
|
||||
push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept');
|
||||
push(t, ' ip saddr . ip daddr @svc_host accept');
|
||||
push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`);
|
||||
push(t, ' ip saddr @inet_ok accept');
|
||||
push(t, ' counter drop');
|
||||
push(t, ' }');
|
||||
// The other way: fw4 lets the server's home zones reach the tunnel; here
|
||||
// only connections from its home networks to people with home access pass
|
||||
// (paused, ended and internet-only people are not reachable). The admin's
|
||||
// own port forwards (DNAT) stay with fw4.
|
||||
push(t, ' chain inbound {');
|
||||
push(t, ' type filter hook forward priority filter - 5; policy accept;');
|
||||
if (length(ifs))
|
||||
push(t, ` oifname { ${join(', ', ifs)} } iifname != { ${join(', ', ifs)} } ct state new jump to_device`);
|
||||
push(t, ' }');
|
||||
push(t, ' chain to_device {');
|
||||
push(t, ' meta nfproto ipv6 drop');
|
||||
push(t, ' ct status dnat accept');
|
||||
for (let id, nets in homes)
|
||||
for (let tn in core.tunnels(m.servers[id]))
|
||||
push(t, ` oifname "${tn.ifname}" ip saddr @home_${id} ip saddr != @tun_nets ip daddr @lan_all accept`);
|
||||
push(t, ' ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept');
|
||||
push(t, ' counter reject with icmpx admin-prohibited');
|
||||
push(t, ' }');
|
||||
// Devices ask the tunnel address; send each query where it belongs.
|
||||
let to_resolver = rt.mode == 'ns' && ip4(rt.address) ? `dnat ip to ${rt.address}:53` : `redirect to :${+rt.port}`;
|
||||
let lan_dns = ctx.lan_dns;
|
||||
if (!ip4(lan_dns))
|
||||
lan_dns = null;
|
||||
push(t, ' chain dns {');
|
||||
push(t, ' type nat hook prerouting priority dstnat - 5; policy accept;');
|
||||
if (length(ifs))
|
||||
// Home names (and no LAN DNS at all): the plain resolver, whatever address was asked.
|
||||
push(t, ` iifname { ${join(', ', ifs)} } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 ${to_resolver}`);
|
||||
for (let id, srv in m.servers)
|
||||
for (let tn in core.tunnels(srv)) {
|
||||
// Everyone else: the LAN's DNS, through the netns (from the LAN side) when internet goes that way.
|
||||
let target = srv.lan_like && dns_addr ? `dnat ip to ${dns_addr}:53` : lan_dns ? `dnat ip to ${lan_dns}:53` : to_resolver;
|
||||
push(t, ` iifname "${tn.ifname}" ip daddr ${tn.address} meta l4proto { tcp, udp } th dport 53 ${target}`);
|
||||
}
|
||||
push(t, ' }');
|
||||
push(t, '}');
|
||||
return join('\n', t) + '\n';
|
||||
}
|
||||
|
||||
/** Run an nft script (one transaction); null when it loaded, else what nft said. */
|
||||
export function load(script) {
|
||||
ensure_dir(RUN_DIR);
|
||||
// A file of its own: two writers must never load each other's script.
|
||||
let f = `${RUN_DIR}/nft.${rand_hex(4)}.rules`;
|
||||
if (!write_file(f, script))
|
||||
return `couldn't write ${f}`;
|
||||
let r = sh(`nft -f ${f}`);
|
||||
unlink(f);
|
||||
if (r.code == 0)
|
||||
return null;
|
||||
// Without the random file name, so the same failure reads the same every time.
|
||||
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* The table as text, for a check (`nft -c -f`) or a test; nothing is loaded.
|
||||
* `ctx` (a test's) stands for what is read from the router: { dns_addr,
|
||||
* resolver, lan_dns, snap } (router_ctx).
|
||||
*/
|
||||
export function render(m, sets, ctx) {
|
||||
return table(m, sets, ctx);
|
||||
};
|
||||
|
||||
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
|
||||
export function rebuild(m, sets) {
|
||||
return load('table inet dawnline\ndelete table inet dawnline\n' + table(m, sets));
|
||||
};
|
||||
|
||||
/**
|
||||
* Replace the members of every runtime set at once; null or the error. Fails
|
||||
* as a whole when the table or one of its sets is missing (not loaded yet,
|
||||
* or an older shape): the caller then rebuilds.
|
||||
*/
|
||||
export function update(sets) {
|
||||
let s = '';
|
||||
for (let name in SETS) {
|
||||
let members = uniq(sets[name]);
|
||||
s += `flush set inet dawnline ${name}\n`;
|
||||
if (length(members))
|
||||
s += `add element inet dawnline ${name} { ${join(', ', members)} }\n`;
|
||||
}
|
||||
return load(s);
|
||||
};
|
||||
|
||||
/** Is the table loaded (watchdog). */
|
||||
export function present() {
|
||||
return system('nft list table inet dawnline >/dev/null 2>&1') == 0;
|
||||
};
|
||||
|
||||
export function remove() {
|
||||
system('nft delete table inet dawnline 2>/dev/null');
|
||||
};
|
||||
@@ -1,660 +0,0 @@
|
||||
// Dawnline — operations: health checks (with fixes), backups, export/import.
|
||||
|
||||
import { readfile, writefile, stat, unlink, lsdir } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import {
|
||||
q, sh, sh_out, ensure_dir, read_json, write_json, write_file, parse_cidr, cidr_overlaps, cidr_str,
|
||||
ip2int, in_cidr, file_exists, valid_host, cloudflare_ip, DATA_DIR, RUN_DIR, VERSION
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import * as net from 'dawnline.net';
|
||||
|
||||
const BACKUP_DIR = `${DATA_DIR}/backups`;
|
||||
const KEEP_BACKUPS = 10;
|
||||
|
||||
/**
|
||||
* Packages a feature needs that are missing, by feature: https (the portal: openssl-util and any
|
||||
* TLS module for uhttpd), acme (Let's Encrypt certificates), home (the home-like link). Checked by
|
||||
* files, so it is cheap enough for every page load.
|
||||
*/
|
||||
export function needs() {
|
||||
let tls = false;
|
||||
for (let d in [ '/lib', '/usr/lib' ])
|
||||
for (let f in lsdir(d) ?? [])
|
||||
if (substr(f, 0, 16) == 'libustream-ssl.s')
|
||||
tls = true;
|
||||
let kver = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||
let veth = stat('/sys/module/veth') != null || file_exists(`/lib/modules/${kver}/veth.ko`);
|
||||
let miss = (list) => map(filter(list, (x) => !x[0]), (x) => x[1]);
|
||||
return {
|
||||
https: miss([ [ file_exists('/usr/bin/openssl'), 'openssl-util' ], [ tls, 'libustream-openssl' ] ]),
|
||||
acme: miss([ [ file_exists('/usr/lib/acme/client/acme.sh'), 'acme' ], [ file_exists('/usr/lib/acme/client/dnsapi/dns_cf.sh'), 'acme-acmesh-dnsapi' ],
|
||||
[ file_exists('/www/luci-static/resources/view/acme.js'), 'luci-app-acme' ] ]),
|
||||
home: miss([ [ file_exists('/usr/libexec/ip-full'), 'ip-full' ], [ veth, 'kmod-veth' ] ]),
|
||||
};
|
||||
};
|
||||
|
||||
/** ACME certificates on the router and the names each covers. */
|
||||
function acme_certs() {
|
||||
let out = [];
|
||||
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
|
||||
let m = match(f, /^(.+)\.fullchain\.crt$/);
|
||||
if (!m)
|
||||
continue;
|
||||
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
|
||||
if (!file_exists(k))
|
||||
continue;
|
||||
let sans = sh_out(`openssl x509 -in ${q(c)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '';
|
||||
push(out, { cert: c, key: k, names: filter(split(replace(sans, /DNS:/g, ''), /[ \t\r\n]+/), (x) => x != '') });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The ACME certificate that covers host (exact name or a wildcard), if any. */
|
||||
function acme_cert_for(host) {
|
||||
for (let a in acme_certs())
|
||||
for (let n in a.names)
|
||||
if (n == host || (substr(n, 0, 2) == '*.' && index(host, '.') > 0 && substr(host, index(host, '.')) == substr(n, 1)))
|
||||
return a;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Certificate the portal should use: configured, ACME for the host, or self-signed. */
|
||||
export function portal_cert(s) {
|
||||
if (s.portal_cert && s.portal_key && file_exists(s.portal_cert) && file_exists(s.portal_key))
|
||||
return { cert: s.portal_cert, key: s.portal_key, self_signed: false };
|
||||
if (s.portal_host) {
|
||||
for (let base in [ `/etc/ssl/acme/${s.portal_host}`, `/etc/acme/${s.portal_host}_ecc/${s.portal_host}` ]) {
|
||||
let c = `${base}.fullchain.crt`, k = `${base}.key`;
|
||||
if (file_exists(c) && file_exists(k))
|
||||
return { cert: c, key: k, self_signed: false };
|
||||
}
|
||||
// An ACME certificate issued for several names, the portal's among them.
|
||||
let a = acme_cert_for(s.portal_host);
|
||||
if (a)
|
||||
return { cert: a.cert, key: a.key, self_signed: false };
|
||||
}
|
||||
let c = `${DATA_DIR}/portal.crt`, k = `${DATA_DIR}/portal.key`;
|
||||
if (!file_exists(c) || !file_exists(k)) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
let cn = s.portal_host || 'dawnline';
|
||||
sh(`openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj ${q('/CN=' + cn)} -keyout ${k} -out ${c}`);
|
||||
system(`chmod 600 ${k}`);
|
||||
}
|
||||
return { cert: c, key: k, self_signed: true };
|
||||
};
|
||||
|
||||
/* ---------- health ---------- */
|
||||
|
||||
function check(id, title, status, detail, fix) {
|
||||
return { id, title, status, detail: detail ?? '', fix: fix ?? null };
|
||||
}
|
||||
|
||||
function udp_listening(port) {
|
||||
let hex = sprintf(':%04X ', port);
|
||||
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
|
||||
if (index(readfile(f) ?? '', hex) >= 0)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function tcp_listening(port) {
|
||||
let hex = sprintf(':%04X ', port);
|
||||
for (let f in [ '/proc/net/tcp', '/proc/net/tcp6' ])
|
||||
for (let line in split(readfile(f) ?? '', '\n'))
|
||||
// state 0A = LISTEN
|
||||
if (index(line, hex) > 0 && match(line, / 0A /))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Processes other than our portal listening on a TCP port: [ "name" ]. */
|
||||
export function tcp_port_owners(port) {
|
||||
let out = sh_out(`netstat -lntp 2>/dev/null | awk '$4 ~ /:${+port}$/ {print $7}'`) ?? '';
|
||||
let owners = [];
|
||||
for (let o in split(out, '\n')) {
|
||||
let name = split(o, '/')[1];
|
||||
if (!name || index(owners, name) >= 0)
|
||||
continue;
|
||||
// Our own portal runs as a dedicated uhttpd instance.
|
||||
let pid = +split(o, '/')[0];
|
||||
let cmd = readfile(`/proc/${pid}/cmdline`) ?? '';
|
||||
if (index(cmd, '/usr/share/dawnline/portal') >= 0)
|
||||
continue;
|
||||
push(owners, name);
|
||||
}
|
||||
return owners;
|
||||
};
|
||||
|
||||
function resolve(host) {
|
||||
if (ip2int(host) != null)
|
||||
return [ host ];
|
||||
// Public resolvers first: local DNS often rewrites the router's own name
|
||||
// to its LAN address (split horizon).
|
||||
for (let srv in [ '1.1.1.1', '8.8.8.8', '127.0.0.1' ]) {
|
||||
let out = sh_out(`timeout 5 nslookup ${q(host)} ${srv} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}'`);
|
||||
let ips = out ? filter(split(out, '\n'), (x) => ip2int(x) != null) : [];
|
||||
if (length(ips))
|
||||
return ips;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function wan_ipv4(zone) {
|
||||
let st = live.iface_status(zone == 'wan' ? 'wan' : zone);
|
||||
return st?.['ipv4-address']?.[0]?.address;
|
||||
}
|
||||
|
||||
/** The router's public IPv4 (the first server's WAN, else the wan interface). */
|
||||
function router_wan(m) {
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key) {
|
||||
let a = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
|
||||
if (a)
|
||||
return a;
|
||||
}
|
||||
return wan_ipv4('wan');
|
||||
}
|
||||
|
||||
/*
|
||||
* Addresses the portal could use in links, found on the router: names in ACME
|
||||
* certificates, server endpoints, DDNS names, the current one, and the WAN IP.
|
||||
* Each says where it points and whether a certificate covers it.
|
||||
*/
|
||||
export function portal_candidates(m) {
|
||||
let wan = router_wan(m);
|
||||
let names = [];
|
||||
let add = (h) => {
|
||||
if (h && valid_host(h) && ip2int(h) == null && substr(h, 0, 2) != '*.' && index(names, h) < 0)
|
||||
push(names, h);
|
||||
};
|
||||
for (let a in acme_certs())
|
||||
for (let n in a.names)
|
||||
add(n);
|
||||
for (let id, srv in m.servers)
|
||||
add(srv.endpoint);
|
||||
let dc = cursor();
|
||||
if (dc.load('ddns'))
|
||||
dc.foreach('ddns', 'service', (sv) => {
|
||||
if (sv.enabled != '0') {
|
||||
add(sv.lookup_host);
|
||||
add(sv.domain);
|
||||
}
|
||||
});
|
||||
for (let h in core.portal_hosts(m))
|
||||
add(h);
|
||||
let out = [];
|
||||
for (let h in names) {
|
||||
let ips = resolve(h);
|
||||
push(out, { host: h, kind: 'name', ips, here: wan != null && index(ips, wan) >= 0,
|
||||
cloudflare: length(filter(ips, (x) => cloudflare_ip(x))) > 0, cert: acme_cert_for(h) != null });
|
||||
}
|
||||
if (wan)
|
||||
push(out, { host: wan, kind: 'ip', ips: [ wan ], here: true, cloudflare: false, cert: false });
|
||||
for (let ph in core.portal_hosts(m))
|
||||
if (ip2int(ph) != null && ph != wan)
|
||||
push(out, { host: ph, kind: 'ip', ips: [ ph ], here: false, cloudflare: false, cert: false });
|
||||
// Best first: here with a certificate, then here, then the rest.
|
||||
let score = (c) => (c.here ? 4 : 0) + (c.cert ? 2 : 0) + (c.kind == 'name' ? 1 : 0) - (c.cloudflare ? 8 : 0);
|
||||
return sort(out, (a, b) => score(b) - score(a));
|
||||
};
|
||||
|
||||
function service_running(name, instance) {
|
||||
let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`);
|
||||
if (!s)
|
||||
return false;
|
||||
try {
|
||||
let j = json(s);
|
||||
let inst = j?.[name]?.instances?.[instance];
|
||||
return !!inst?.running;
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function other_subnets(srv_id) {
|
||||
let out = [];
|
||||
let st = sh_out('ubus call network.interface dump 2>/dev/null');
|
||||
let d = st ? json(st) : null;
|
||||
let ours = {};
|
||||
let m = core.load();
|
||||
for (let id, s in m.servers)
|
||||
ours[s.ifname] = id;
|
||||
for (let i in d?.interface ?? []) {
|
||||
if (srv_id != null && ours[i.interface] == srv_id)
|
||||
continue;
|
||||
for (let a in i['ipv4-address'] ?? [])
|
||||
push(out, { iface: i.interface, cidr: `${a.address}/${a.mask}` });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function used_subnets(except_srv) {
|
||||
return map(other_subnets(except_srv), (x) => x.cidr);
|
||||
};
|
||||
|
||||
/**
|
||||
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }.
|
||||
* `fix` names an action accepted by fix().
|
||||
*/
|
||||
/*
|
||||
* Policy rules that send the router's own (marked) traffic into a local table,
|
||||
* the way transparent proxies capture it: "pref 1000 fwmark 0x1 → table 100".
|
||||
*/
|
||||
function proxy_diverts() {
|
||||
let out = [];
|
||||
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
|
||||
let mm = match(line, /^(\d+):.*fwmark (\S+).* lookup (\S+)/);
|
||||
if (!mm || +mm[1] >= 32766)
|
||||
continue;
|
||||
if (match(sh_out(`ip -4 route show table ${mm[3]} 2>/dev/null`) ?? '', /(^|\n)local default/))
|
||||
push(out, `pref ${mm[1]} fwmark ${mm[2]} → table ${mm[3]}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Our "answers leave by main" rule for this port (see apply.sync_reply_routes). */
|
||||
function reply_rule(proto, port) {
|
||||
return index(sh_out('ip -4 rule show priority 90 2>/dev/null') ?? '', `ipproto ${proto} sport ${+port} lookup main`) >= 0;
|
||||
}
|
||||
|
||||
function reply_check(id, title, proto, port, diverts) {
|
||||
let ok = reply_rule(proto, port);
|
||||
let via = length(diverts) ? ` A proxy on the router diverts its own traffic (${join(', ', diverts)}); these answers skip it.` : '';
|
||||
return check(id, title, ok ? 'ok' : (length(diverts) ? 'error' : 'warn'),
|
||||
ok ? `Answers from ${uc(proto)} ${port} go straight out.${via}`
|
||||
: length(diverts) ? `Answers from ${uc(proto)} ${port} can be swallowed by a proxy on the router (${join(', ', diverts)}): clients get no reply.`
|
||||
: `The rule that keeps answers from ${uc(proto)} ${port} out of proxies is missing.`,
|
||||
ok ? null : 'apply');
|
||||
}
|
||||
|
||||
export function health(m) {
|
||||
let diverts = proxy_diverts();
|
||||
m ??= core.load();
|
||||
let out = [];
|
||||
let dmp = live.dump();
|
||||
|
||||
let kmod = file_exists('/sys/module/amneziawg');
|
||||
let tools = file_exists('/usr/bin/awg');
|
||||
push(out, check('awg', 'AmneziaWG installed', kmod && tools ? 'ok' : 'error',
|
||||
kmod && tools ? 'Kernel module and awg tool present.' :
|
||||
(!tools ? 'amneziawg-tools is missing.' : 'The kmod-amneziawg module is not loaded.'), kmod && tools ? null : 'updates'));
|
||||
|
||||
let y = localtime().year;
|
||||
push(out, check('clock', 'Clock is set', y >= 2025 ? 'ok' : 'error',
|
||||
y >= 2025 ? 'End dates and quotas use the router clock.' : 'The router clock looks wrong; end dates will misbehave. Check NTP.'));
|
||||
|
||||
push(out, check('agent', 'Background agent running', service_running('dawnline', 'agent') ? 'ok' : 'error',
|
||||
'Counts traffic and enforces end dates and quotas.', service_running('dawnline', 'agent') ? null : 'restart'));
|
||||
|
||||
if (!length(m.servers)) {
|
||||
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.'));
|
||||
return out;
|
||||
}
|
||||
|
||||
let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0;
|
||||
push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error',
|
||||
nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.' : 'Table inet dawnline is missing: access is not enforced.',
|
||||
nft_ok ? null : 'apply'));
|
||||
|
||||
let fwc = cursor();
|
||||
fwc.load('firewall');
|
||||
|
||||
for (let id, srv in m.servers) {
|
||||
let label = length(m.servers) > 1 ? ` (${srv.name})` : '';
|
||||
if (!srv.enabled) {
|
||||
push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.'));
|
||||
continue;
|
||||
}
|
||||
let st = live.iface_status(srv.ifname);
|
||||
let up = !!st?.up;
|
||||
push(out, check(`up_${id}`, `Tunnel interface up${label}`, up ? 'ok' : 'error',
|
||||
up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` :
|
||||
(st ? `${srv.ifname} is down${st.errors ? ': ' + join(', ', map(st.errors, (e) => e.code)) : ''}.` : `${srv.ifname} does not exist.`),
|
||||
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
|
||||
|
||||
if (up) {
|
||||
let expected = 0;
|
||||
let states = apply.states_for(m, core.load_usage());
|
||||
for (let did, d in m.devices)
|
||||
if (m.people[d.person]?.server == id && !d.disabled && states[d.person] == 'active')
|
||||
expected++;
|
||||
let actual = 0;
|
||||
for (let k, p in dmp.peers)
|
||||
if (p.ifname == srv.ifname)
|
||||
actual++;
|
||||
push(out, check(`peers_${id}`, `Devices loaded${label}`, expected == actual ? 'ok' : 'warn',
|
||||
`${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync'));
|
||||
}
|
||||
|
||||
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
|
||||
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
|
||||
push(out, check(`fw_${id}`, `Firewall${label}`, rule && zone ? 'ok' : 'error',
|
||||
rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.',
|
||||
rule && zone ? null : 'apply'));
|
||||
push(out, reply_check(`reply_${id}`, `Answers reach clients${label}`, 'udp', srv.port, diverts));
|
||||
|
||||
// Port collisions with other tunnels.
|
||||
let clash = [];
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
nc.foreach('network', 'interface', (s) => {
|
||||
if (s['.name'] != srv.ifname && (s.proto == 'amneziawg' || s.proto == 'wireguard') && +s.listen_port == srv.port)
|
||||
push(clash, s['.name']);
|
||||
});
|
||||
if (length(clash))
|
||||
push(out, check(`port_${id}`, `Port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', clash)}.`));
|
||||
|
||||
let overlaps = [];
|
||||
let sc = parse_cidr(srv.subnet);
|
||||
for (let o in other_subnets(id)) {
|
||||
let oc = parse_cidr(o.cidr);
|
||||
if (sc && oc && cidr_overlaps(sc, oc))
|
||||
push(overlaps, `${o.iface} (${o.cidr})`);
|
||||
}
|
||||
push(out, check(`subnet_${id}`, `Subnet is unique${label}`, length(overlaps) ? 'error' : 'ok',
|
||||
length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`));
|
||||
|
||||
let host = core.endpoint_host(m, srv);
|
||||
if (!host)
|
||||
push(out, check(`ep_${id}`, `Public address${label}`, 'error', 'No endpoint hostname: clients will not know where to connect.'));
|
||||
else {
|
||||
let ips = resolve(host);
|
||||
let wan = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
|
||||
let wc = wan ? ip2int(wan) : null;
|
||||
let cgnat = wc != null && (in_cidr(wc, parse_cidr('100.64.0.0/10')) || in_cidr(wc, parse_cidr('10.0.0.0/8')) ||
|
||||
in_cidr(wc, parse_cidr('172.16.0.0/12')) || in_cidr(wc, parse_cidr('192.168.0.0/16')));
|
||||
let stv = 'ok', det;
|
||||
if (!length(ips)) {
|
||||
stv = 'error';
|
||||
det = `${host} does not resolve.`;
|
||||
}
|
||||
else if (cgnat) {
|
||||
stv = 'warn';
|
||||
det = `WAN address ${wan} is private: forward UDP ${srv.port} on the upstream router, or clients cannot connect.`;
|
||||
}
|
||||
else if (length(filter(ips, (a) => cloudflare_ip(a))))
|
||||
det = `${host} → ${join(', ', ips)} (Cloudflare). The tunnel is UDP: it reaches the router only if this name is DNS-only there.`;
|
||||
else if (wan && index(ips, wan) < 0) {
|
||||
stv = 'warn';
|
||||
det = `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`;
|
||||
}
|
||||
else
|
||||
det = `${host} → ${join(', ', ips)}`;
|
||||
push(out, check(`ep_${id}`, `Public address${label}`, stv, det));
|
||||
}
|
||||
|
||||
if (srv.lan_like) {
|
||||
let ls = loop.status();
|
||||
let nh = needs().home;
|
||||
push(out, check(`home_${id}`, `Internet like a home device${label}`, ls.active && ls.bridged ? 'ok' : 'warn',
|
||||
ls.active && ls.bridged ? `Traffic enters ${ls.dev} as ${ls.address}, so it is handled like any device on your LAN.` :
|
||||
length(nh) ? `Needs ${join(' and ', nh)}. Internet traffic leaves through WAN directly until then.` :
|
||||
ls.active ? `The link is up but not attached to ${ls.dev}.` :
|
||||
`${ls.error ?? 'Not set up.'} Internet traffic leaves through WAN directly.`,
|
||||
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply'));
|
||||
}
|
||||
}
|
||||
|
||||
if (length(filter(values(m.servers), (x) => x.private_key))) {
|
||||
let rt = loop.resolver_target();
|
||||
let ok = stat(loop.RESOLVER.conf) != null && loop.resolver_running();
|
||||
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
|
||||
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`)
|
||||
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply'));
|
||||
}
|
||||
|
||||
let s = m.settings;
|
||||
let need = needs();
|
||||
if (s.portal_enabled && length(need.https))
|
||||
push(out, check('portal', 'Personal portal', 'error',
|
||||
`HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https'));
|
||||
else if (s.portal_enabled) {
|
||||
let owners = tcp_port_owners(s.portal_port);
|
||||
let listening = tcp_listening(s.portal_port);
|
||||
if (length(owners))
|
||||
push(out, check('portal', 'Personal portal', 'error',
|
||||
`TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`));
|
||||
else
|
||||
push(out, check('portal', 'Personal portal', listening ? 'ok' : 'error',
|
||||
listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart'));
|
||||
if (!s.portal_host)
|
||||
push(out, check('portal_host', 'Portal address', 'error', 'Set the public hostname in Settings so links can be generated.'));
|
||||
else {
|
||||
let ips = resolve(s.portal_host), wan = router_wan(m);
|
||||
let cf = filter(ips, (x) => cloudflare_ip(x));
|
||||
push(out, check('portal_dns', 'Portal address points here', !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok',
|
||||
!length(ips) ? `${s.portal_host} does not resolve.` :
|
||||
length(cf) ? `${s.portal_host} goes through Cloudflare; in Russia such connections often stall after ~16 KB.` :
|
||||
wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` :
|
||||
`${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`));
|
||||
}
|
||||
push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, diverts));
|
||||
if (core.portal_http(m)) {
|
||||
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
|
||||
push(out, check('portal_http', 'Plain HTTP links', 'warn',
|
||||
`Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`));
|
||||
}
|
||||
|
||||
// Links on 443: forwarded from outside, and the same link at home through LuCI's web server.
|
||||
let pub = core.portal_public_port(m);
|
||||
if (s.portal_port != 443) {
|
||||
if (!s.portal_443)
|
||||
push(out, check('portal_443', 'Links without a port', 'skip',
|
||||
`Off: links use port ${s.portal_port}. Mobile networks often drop HTTPS on ports other than 443.`));
|
||||
else if (pub != 443)
|
||||
push(out, check('portal_443', 'Links without a port', 'warn',
|
||||
`TCP 443 is already forwarded to another device, so links use port ${s.portal_port}.`));
|
||||
else {
|
||||
let fw = system(`nft list ruleset 2>/dev/null | grep -q 'Dawnline-Portal-443'`) == 0;
|
||||
push(out, check('portal_443', 'Links without a port', fw ? 'ok' : 'error',
|
||||
fw ? `From the internet TCP 443 reaches the portal only (LuCI stays closed there).` : 'The 443 forward to the portal is missing.',
|
||||
fw ? null : 'apply'));
|
||||
let uc_ = cursor();
|
||||
uc_.load('uhttpd');
|
||||
let ep = uc_.get('uhttpd', 'main', 'error_page');
|
||||
let mine = ep == '/cgi-bin/dawnline-portal' && stat('/www/cgi-bin/dawnline-portal') != null;
|
||||
push(out, check('portal_lan', 'Same link at home', mine ? 'ok' : ep ? 'warn' : 'error',
|
||||
mine ? 'At home the link opens through LuCI\'s web server, which hands unknown paths to the portal.'
|
||||
: ep ? `LuCI's web server already uses ${ep} for unknown paths, so at home links need :${s.portal_port}.`
|
||||
: 'LuCI\'s web server does not hand portal links to the portal: at home they show Not found.',
|
||||
mine || ep ? null : 'apply'));
|
||||
}
|
||||
}
|
||||
|
||||
let cert = portal_cert(s);
|
||||
if (ip2int(s.portal_host) != null)
|
||||
push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.'));
|
||||
else {
|
||||
let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0;
|
||||
let sans = cert.self_signed ? [] : split(replace(sh_out(`openssl x509 -in ${q(cert.cert)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '', /DNS:/g, ''), /[ \t\r\n]+/);
|
||||
let covers = !s.portal_host || cert.self_signed || index(sans, s.portal_host) >= 0 ||
|
||||
length(filter(sans, (n) => substr(n, 0, 2) == '*.' && substr(s.portal_host, index(s.portal_host, '.')) == substr(n, 1)));
|
||||
push(out, check('cert', 'Portal certificate', cert.self_signed || !ok || !covers ? 'warn' : 'ok',
|
||||
cert.self_signed ? `Using a self-signed certificate: browsers will show a warning.${length(need.acme) ? ' ACME can get a free Let’s Encrypt one.' : ''}` :
|
||||
!covers ? `${cert.cert} does not cover ${s.portal_host} (it has ${join(', ', sans)}): browsers will warn.` :
|
||||
ok ? `${cert.cert} covers ${s.portal_host} and is valid for more than 14 days.` : `${cert.cert} expires within 14 days.`));
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
};
|
||||
|
||||
export function fix(id) {
|
||||
if (id == 'apply')
|
||||
return apply.apply();
|
||||
if (id == 'sync')
|
||||
return apply.sync();
|
||||
if (id == 'restart')
|
||||
return { code: system('/etc/init.d/dawnline restart >/dev/null 2>&1') };
|
||||
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
|
||||
if (m) {
|
||||
system(`ifup ${q(m[1])}`);
|
||||
return { ok: true };
|
||||
}
|
||||
die('Unknown fix.');
|
||||
};
|
||||
|
||||
/* ---------- backups ---------- */
|
||||
|
||||
function backup_files() {
|
||||
let out = [ '/etc/config/dawnline' ];
|
||||
for (let f in [ 'usage.json', 'events.json' ])
|
||||
if (file_exists(`${DATA_DIR}/${f}`))
|
||||
push(out, `${DATA_DIR}/${f}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function backup_list() {
|
||||
let out = [];
|
||||
for (let f in lsdir(BACKUP_DIR) ?? []) {
|
||||
let mm = match(f, /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/);
|
||||
if (!mm)
|
||||
continue;
|
||||
let st = stat(`${BACKUP_DIR}/${f}`);
|
||||
push(out, { name: f, created: st?.mtime ?? 0, size: st?.size ?? 0, reason: mm[3] ?? 'manual' });
|
||||
}
|
||||
return sort(out, (a, b) => b.created - a.created);
|
||||
};
|
||||
|
||||
export function backup_create(reason) {
|
||||
// Flush live counters first so the backup has current usage.
|
||||
let u = read_json(`${RUN_DIR}/usage.json`, null);
|
||||
if (u)
|
||||
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
|
||||
live.persist_events();
|
||||
ensure_dir(BACKUP_DIR, 0o700);
|
||||
let t = localtime();
|
||||
let tag = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? `-${reason}` : '';
|
||||
let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, tag);
|
||||
let files = join(' ', map(backup_files(), (f) => q(substr(f, 1))));
|
||||
let r = sh(`tar -czf ${q(BACKUP_DIR + '/' + name)} -C / ${files}`);
|
||||
if (r.code != 0)
|
||||
die(`Backup failed: ${trim(r.out)}`);
|
||||
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
|
||||
let all = backup_list();
|
||||
for (let i = KEEP_BACKUPS; i < length(all); i++)
|
||||
unlink(`${BACKUP_DIR}/${all[i].name}`);
|
||||
return name;
|
||||
};
|
||||
|
||||
function backup_path(name) {
|
||||
if (!match(name ?? '', /^dawnline-[0-9]{8}-[0-9]{6}(-[a-z0-9-]+)?\.tar\.gz$/))
|
||||
die('Invalid backup name.');
|
||||
let p = `${BACKUP_DIR}/${name}`;
|
||||
if (!file_exists(p))
|
||||
die('Backup not found.');
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Validate an archive: only Dawnline's own files may be inside. */
|
||||
function check_archive(path) {
|
||||
let r = sh(`tar -tzf ${q(path)}`);
|
||||
if (r.code != 0)
|
||||
die('Not a valid backup archive.');
|
||||
let allowed = { 'etc/config/dawnline': true };
|
||||
let has_config = false;
|
||||
for (let f in split(trim(r.out), '\n')) {
|
||||
f = replace(f, /^\.?\//, '');
|
||||
// The config plus Dawnline's own data files (older versions had more of them).
|
||||
if (!allowed[f] && !match(f, /^etc\/dawnline\/[a-z0-9_-]+\.json$/))
|
||||
die(`Unexpected file in backup: ${f}`);
|
||||
if (f == 'etc/config/dawnline')
|
||||
has_config = true;
|
||||
}
|
||||
if (!has_config)
|
||||
die('Backup does not contain /etc/config/dawnline.');
|
||||
}
|
||||
|
||||
export function backup_restore(name, path) {
|
||||
path ??= backup_path(name);
|
||||
check_archive(path);
|
||||
backup_create('pre-restore');
|
||||
let r = sh(`tar -xzf ${q(path)} -C /`);
|
||||
if (r.code != 0)
|
||||
die(`Restore failed: ${trim(r.out)}`);
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
// Live counters must follow the restored file.
|
||||
unlink(`${RUN_DIR}/usage.json`);
|
||||
unlink(`${RUN_DIR}/events.json`);
|
||||
return apply.apply();
|
||||
};
|
||||
|
||||
export function backup_delete(name) {
|
||||
unlink(backup_path(name));
|
||||
return true;
|
||||
};
|
||||
|
||||
export function backup_read(name) {
|
||||
return b64enc(readfile(backup_path(name)));
|
||||
};
|
||||
|
||||
export function backup_upload(data_b64) {
|
||||
let data = b64dec(data_b64 ?? '');
|
||||
if (!data || length(data) > 4 * 1024 * 1024)
|
||||
die('Upload is empty or too large.');
|
||||
ensure_dir(RUN_DIR);
|
||||
let tmp = `${RUN_DIR}/upload.tar.gz`;
|
||||
write_file(tmp, data);
|
||||
let res;
|
||||
try {
|
||||
res = backup_restore(null, tmp);
|
||||
}
|
||||
catch (e) {
|
||||
unlink(tmp);
|
||||
die(e.message);
|
||||
}
|
||||
unlink(tmp);
|
||||
return res;
|
||||
};
|
||||
|
||||
/* ---------- export / import (JSON) ---------- */
|
||||
|
||||
export function export_json() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let sections = [];
|
||||
c.foreach('dawnline', null, (s) => {
|
||||
let o = { '.type': s['.type'], '.name': s['.name'] };
|
||||
for (let k, v in s)
|
||||
if (substr(k, 0, 1) != '.')
|
||||
o[k] = v;
|
||||
push(sections, o);
|
||||
});
|
||||
return { format: 'dawnline', version: VERSION, exported: time(), sections };
|
||||
};
|
||||
|
||||
export function import_json(data) {
|
||||
if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array')
|
||||
die('Not a Dawnline export.');
|
||||
let types = { settings: true, server: true, person: true, device: true, service: true };
|
||||
for (let s in data.sections) {
|
||||
if (!types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/))
|
||||
die(`Invalid section ${s['.name']}.`);
|
||||
for (let k, v in s)
|
||||
if (substr(k, 0, 1) != '.' && (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array')))
|
||||
die(`Invalid option ${k}.`);
|
||||
}
|
||||
backup_create('pre-import');
|
||||
let lines = [];
|
||||
for (let s in data.sections) {
|
||||
push(lines, `config ${s['.type']} '${s['.name']}'`);
|
||||
for (let k, v in s) {
|
||||
if (substr(k, 0, 1) == '.')
|
||||
continue;
|
||||
let esc = (x) => replace(`${x}`, "'", "'\\''");
|
||||
if (type(v) == 'array')
|
||||
for (let x in v)
|
||||
push(lines, `\tlist ${k} '${esc(x)}'`);
|
||||
else
|
||||
push(lines, `\toption ${k} '${esc(v)}'`);
|
||||
}
|
||||
push(lines, '');
|
||||
}
|
||||
write_file('/etc/config/dawnline', join('\n', lines), 0o600);
|
||||
return apply.apply();
|
||||
};
|
||||
@@ -0,0 +1,207 @@
|
||||
// Dawnline — one interface over the router's package manager: opkg on
|
||||
// OpenWrt 24.10, apk on 25.12. Commands that change packages take a log(line)
|
||||
// callback, which gets their output line by line.
|
||||
|
||||
import { access, popen, stat } from 'fs';
|
||||
import { q } from 'dawnline.util';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
function run(cmd) {
|
||||
let p = popen(cmd + ' 2>&1', 'r');
|
||||
if (!p)
|
||||
return { code: 127, out: '' };
|
||||
let out = p.read('all') ?? '';
|
||||
return { code: p.close(), out };
|
||||
}
|
||||
|
||||
function logged(cmd, log) {
|
||||
let r = run(cmd);
|
||||
for (let line in split(trim(r.out), '\n'))
|
||||
if (length(trim(line)))
|
||||
log?.(` ${line}`);
|
||||
return r;
|
||||
}
|
||||
|
||||
export function is_apk() {
|
||||
return access('/usr/bin/apk', 'x');
|
||||
};
|
||||
|
||||
export function ext() {
|
||||
return is_apk() ? 'apk' : 'ipk';
|
||||
};
|
||||
|
||||
/** The installed version of a package, or null. */
|
||||
export function version(name) {
|
||||
let esc = replace(name, /[.+]/g, '\\$&');
|
||||
if (is_apk()) {
|
||||
let m = match(run(`apk list --installed ${q(name)}`).out, regexp(`^${esc}-([^ ]+) `));
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
// Libraries carry their ABI in the name (libustream-openssl20201210).
|
||||
let re = regexp(`^${esc}([0-9]+)? - (.+)$`), found = null;
|
||||
for (let line in split(run('opkg list-installed').out, '\n')) {
|
||||
let m = match(trim(line), re);
|
||||
if (m && (found == null || m[1] == null))
|
||||
found = m;
|
||||
}
|
||||
return found ? trim(found[2]) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The package a control text names: { name, version }, each null when it
|
||||
* does not say. Pure: an ipk's control file (ipk true), else `apk adbdump`
|
||||
* of an apk, whose first name and version are the package's own (its files
|
||||
* are "- name:" entries further down).
|
||||
*/
|
||||
export function control_info(text, ipk) {
|
||||
if (ipk)
|
||||
return { name: match(text, /(^|\n)Package: *([^\n]+)/)?.[2], version: match(text, /(^|\n)Version: *([^\n]+)/)?.[2] };
|
||||
return { name: match(text, /\n *name: *([^\n]+)/)?.[1], version: match(text, /\n *version: *([^\n]+)/)?.[1] };
|
||||
};
|
||||
|
||||
/** The package inside a file: { name, version }, each null when the file does not say. */
|
||||
export function file_info(path) {
|
||||
if (match(path, /\.ipk$/))
|
||||
return control_info(run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out, true);
|
||||
return control_info(run(`apk adbdump ${q(path)}`).out, false);
|
||||
};
|
||||
|
||||
/** The version inside a package file, or null. */
|
||||
export function file_version(path) {
|
||||
return file_info(path).version;
|
||||
};
|
||||
|
||||
/**
|
||||
* Compare two package versions the way the package manager does (so -r10 is
|
||||
* newer than -r9 and ~rc before the release): -1, 0 or 1; null when unknown.
|
||||
*/
|
||||
export function cmp(a, b) {
|
||||
if (a == null || b == null)
|
||||
return null;
|
||||
if (a == b)
|
||||
return 0;
|
||||
if (is_apk()) {
|
||||
let r = trim(run(`apk version -t ${q(a)} ${q(b)}`).out);
|
||||
return r == '<' ? -1 : r == '>' ? 1 : r == '=' ? 0 : null;
|
||||
}
|
||||
if (run(`opkg compare-versions ${q(a)} '<<' ${q(b)}`).code == 0)
|
||||
return -1;
|
||||
if (run(`opkg compare-versions ${q(a)} '>>' ${q(b)}`).code == 0)
|
||||
return 1;
|
||||
return 0;
|
||||
};
|
||||
|
||||
export function refresh(log) {
|
||||
return logged(is_apk() ? 'apk update' : 'opkg update', log).code == 0;
|
||||
};
|
||||
|
||||
/** Free space on the overlay in KB (null when unknown). */
|
||||
function overlay_free_kb() {
|
||||
let out = run('df -Pk /overlay 2>/dev/null || df -Pk / 2>/dev/null').out;
|
||||
let m = match(out, /\n\S+\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s/);
|
||||
return m ? +m[1] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Room for `files` (or `need_kb` from the feeds): the package manager
|
||||
* unpacks before it removes, so a full flash leaves half an install behind.
|
||||
* Dies with the numbers.
|
||||
*/
|
||||
function preflight(files, need_kb, log) {
|
||||
let free = overlay_free_kb();
|
||||
if (free == null)
|
||||
return;
|
||||
let need = need_kb ?? 512;
|
||||
for (let f in files ?? [])
|
||||
need += int(((stat(f)?.size ?? 0) * 3) / 1024);
|
||||
if (free < need)
|
||||
die(sprintf(_('Not enough free space on the router: %d MB free, about %d MB needed. Remove old backups or packages first'),
|
||||
int(free / 1024), int(need / 1024) + 1));
|
||||
log?.(' ' + sprintf(_('%d MB free on the overlay'), int(free / 1024)));
|
||||
}
|
||||
|
||||
/** Dawnline's own package: a file of it tells whether apk really reinstalled it. */
|
||||
const SELF = 'luci-app-dawnline', SELF_MARKER = '/usr/share/ucode/dawnline/util.uc';
|
||||
|
||||
/**
|
||||
* The packages an apk install did not leave at their file's version: apk
|
||||
* takes a given file as it is (an older version too, a rollback) but leaves
|
||||
* an installed version alone, whatever the file. Pure: want [{ name,
|
||||
* version, file }] from the files (file_info()), have { name: installed
|
||||
* version }. [] when every package took.
|
||||
*/
|
||||
export function mismatched(want, have) {
|
||||
return filter(want, (w) => w.name == null || w.version == null || have?.[w.name] != w.version);
|
||||
};
|
||||
|
||||
/**
|
||||
* Package files (from a release): true when every one is installed. force
|
||||
* also reinstalls the same version or goes back to an older one (opkg; apk
|
||||
* takes a file as it is: Dawnline's own package is checked by a file of it,
|
||||
* any other by its installed version).
|
||||
*/
|
||||
export function install_files(files, force, log) {
|
||||
preflight(files, 0, log);
|
||||
let args = join(' ', map(files, q));
|
||||
if (!is_apk())
|
||||
return logged(`opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
|
||||
let want = map(files, (f) => ({ ...file_info(f), file: f }));
|
||||
let own = length(filter(want, (w) => w.name == SELF)) > 0;
|
||||
// Dawnline's own reinstall that changed nothing is a failure, not a silent "done".
|
||||
let before = own && force ? stat(SELF_MARKER)?.mtime : null;
|
||||
if (logged(`apk add --allow-untrusted ${args}`, log).code != 0)
|
||||
return false;
|
||||
if (own) {
|
||||
if (force && before != null && stat(SELF_MARKER)?.mtime == before) {
|
||||
log?.(' ' + _('apk did not reinstall the version that is already installed'));
|
||||
die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Any other package took when it is at its file's version (the same
|
||||
// version again counts: apk keeps the installed one).
|
||||
let have = {};
|
||||
for (let w in want)
|
||||
if (w.name != null)
|
||||
have[w.name] = version(w.name);
|
||||
let bad = mismatched(want, have);
|
||||
for (let w in bad)
|
||||
log?.(' ' + sprintf(_('apk did not install %s %s (installed: %s)'), w.name ?? w.file, w.version ?? '?', have[w.name] ?? '-'));
|
||||
return !length(bad);
|
||||
};
|
||||
|
||||
/** Packages by name from the feeds. */
|
||||
export function add(names, log) {
|
||||
preflight(null, 2048, log);
|
||||
return logged(is_apk() ? `apk add ${join(' ', map(names, q))}` : `opkg install ${join(' ', map(names, q))}`, log).code == 0;
|
||||
};
|
||||
|
||||
export function upgrade(names, log) {
|
||||
preflight(null, 2048, log);
|
||||
return logged(is_apk() ? `apk upgrade ${join(' ', map(names, q))}` : `opkg upgrade ${join(' ', map(names, q))}`, log).code == 0;
|
||||
};
|
||||
|
||||
export function remove(names, log) {
|
||||
return logged(is_apk() ? `apk del ${join(' ', map(names, q))}` : `opkg remove ${join(' ', map(names, q))}`, log).code == 0;
|
||||
};
|
||||
|
||||
/** Installed packages with a newer version in the feeds: { name: latest }. */
|
||||
export function upgradable() {
|
||||
let up = {};
|
||||
if (is_apk()) {
|
||||
for (let line in split(run('apk version -l "<"').out, '\n')) {
|
||||
// "name-version-rN < newer": the version is what follows the last dash
|
||||
// before the release suffix (a name may hold digits, a version no dash).
|
||||
let m = match(line, /^(\S+)-([^- ]+-r[0-9]+)\s+<\s+(\S+)/);
|
||||
if (m)
|
||||
up[m[1]] = m[3];
|
||||
}
|
||||
}
|
||||
else
|
||||
for (let line in split(run('opkg list-upgradable').out, '\n')) {
|
||||
let m = match(line, /^(\S+) - (\S+) - (\S+)/);
|
||||
if (m)
|
||||
up[m[1]] = m[3];
|
||||
}
|
||||
return up;
|
||||
};
|
||||
@@ -0,0 +1,588 @@
|
||||
// Dawnline — the personal portal.
|
||||
//
|
||||
// GET /<code> the app shell
|
||||
// GET /<code>/assets/<file> its script, styles and fonts
|
||||
// GET /<code>/api/state
|
||||
// POST /<code>/api/devices { name, kind, public_key?, lan_bypass? }
|
||||
// GET /<code>/api/devices/<id>/config
|
||||
// POST /<code>/api/devices/<id> { action: rename|rotate|delete, name? }
|
||||
//
|
||||
// The personal link is the key: every request carries its code, there are
|
||||
// no sessions. Without a valid code every path answers the same bare 404 —
|
||||
// the root, a person's link, the API and the assets alike — so nothing tells
|
||||
// a scanner there is a portal here. Wrong codes are rate-limited per client
|
||||
// (blocked clients get the same 404 even with the right code): per IPv4
|
||||
// address or IPv6 /64; behind Cloudflare per visitor (CF-Connecting-IP), with
|
||||
// a higher ceiling for all Cloudflare visitors together.
|
||||
// Regenerating the code in LuCI locks the old link out at once. POST bodies
|
||||
// must be JSON from the same origin; Referrer-Policy keeps the code out of
|
||||
// other sites' logs. The portal can only manage the person's own devices
|
||||
// within their limits, and not those the admin turned off (dawnline.devices).
|
||||
//
|
||||
// Changes through a link are limited too (a link is not a terminal: a few
|
||||
// dozen every quarter hour), and the configurations themselves (keys, the
|
||||
// disguise) only go over HTTPS: a plain-HTTP link (an IP address in Settings)
|
||||
// shows the page, but gets them from its HTTPS twin.
|
||||
//
|
||||
// Messages go out in the page's language (Accept-Language: the portal's
|
||||
// fetch sends the visitor's choice) when a Dawnline translation for it is
|
||||
// installed; else in English, and the page translates the ones it knows.
|
||||
//
|
||||
// handle() serves one request: `io` = { env, headers, read(n), write(s) }; the
|
||||
// CGI script (cgi.uc) is its wrapper, behind the shell door www/cgi-bin/portal
|
||||
// that answers anything not shaped like a link (its not_found() twin).
|
||||
|
||||
import { stat, readfile } from 'fs';
|
||||
import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as view from 'dawnline.view';
|
||||
import * as schema from 'dawnline.schema';
|
||||
import * as devices from 'dawnline.devices';
|
||||
import * as i18n from 'dawnline.i18n';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
const RATE = `${RUN_DIR}/portal-rate.json`;
|
||||
const ASSETS = '/usr/share/dawnline/portal/assets';
|
||||
const TYPES = { js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml', woff2: 'font/woff2', png: 'image/png' };
|
||||
const FAIL_LIMIT = 8;
|
||||
const FAIL_WINDOW = 900;
|
||||
// All Cloudflare visitors together (three-word codes can't be guessed anyway).
|
||||
const SHARED_LIMIT = FAIL_LIMIT * 25;
|
||||
const SHARED_KEY = 'cloudflare';
|
||||
// Clients remembered at most (the oldest go first).
|
||||
const RATE_MAX = 2000;
|
||||
// Changes one link may make within FAIL_WINDOW (each one writes flash and syncs the tunnels).
|
||||
const ACTION_LIMIT = 40;
|
||||
const BODY_MAX = 8192;
|
||||
// The early end of a request (a response was written).
|
||||
const DONE = '__dawnline_done__';
|
||||
|
||||
const SECURITY_HEADERS = {
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
'X-Frame-Options': 'DENY',
|
||||
'Cache-Control': 'no-store',
|
||||
};
|
||||
|
||||
// States the admin stopped the person in: the portal only shows, it changes nothing.
|
||||
const LOCKED = [ 'paused', 'expired' ];
|
||||
|
||||
/** Why a stopped person (a LOCKED state) can't change anything, in the visitor's language; null for other states. */
|
||||
function locked_reason(st) {
|
||||
if (st == 'paused')
|
||||
return _('Your access is paused.');
|
||||
if (st == 'expired')
|
||||
return _('Your access has ended.');
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Why a new device or a new set-up is refused while the router has no AmneziaWG. */
|
||||
function not_ready() {
|
||||
return _("Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.");
|
||||
}
|
||||
|
||||
function html_escape(s) {
|
||||
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
||||
}
|
||||
|
||||
/* ---------- answering ---------- */
|
||||
|
||||
function headers(r, status, extra) {
|
||||
let h = `Status: ${status}\r\n`;
|
||||
let all = { ...SECURITY_HEADERS, ...(extra ?? {}) };
|
||||
// HSTS pins the whole name: only when the visitor is on the standard port.
|
||||
if (r.hsts)
|
||||
all['Strict-Transport-Security'] = 'max-age=31536000';
|
||||
for (let k, v in all)
|
||||
h += `${k}: ${v}\r\n`;
|
||||
r.io.write(h + '\r\n');
|
||||
}
|
||||
|
||||
function finish() {
|
||||
die(DONE);
|
||||
}
|
||||
|
||||
function send_json(r, status, obj) {
|
||||
headers(r, status, { 'Content-Type': 'application/json' });
|
||||
r.io.write(sprintf('%J', obj));
|
||||
finish();
|
||||
}
|
||||
|
||||
function fail(r, status, msg) {
|
||||
send_json(r, status, { error: msg });
|
||||
}
|
||||
|
||||
/**
|
||||
* The one answer for anything without a valid code: a bare 404, or the redirect from Settings.
|
||||
* Files always get the 404: a missing asset must not turn into someone's website.
|
||||
*/
|
||||
function not_found(r) {
|
||||
let redirect = r.m.settings.portal_redirect;
|
||||
let parts = split(r.path, '/');
|
||||
let file = match(r.path, /^\/(luci-static|cgi-bin|ubus)(\/|$)/) || match(parts[length(parts) - 1], /\./);
|
||||
if (redirect && !file) {
|
||||
headers(r, '302 Found', { 'Location': redirect, 'Cache-Control': 'no-store', 'Content-Type': 'text/plain' });
|
||||
r.io.write('Moved\n');
|
||||
}
|
||||
else {
|
||||
headers(r, '404 Not Found', { 'Content-Type': 'text/plain' });
|
||||
r.io.write('Not found\n');
|
||||
}
|
||||
finish();
|
||||
}
|
||||
|
||||
/** The JSON object a POST carries ({} without a body). */
|
||||
function body(r) {
|
||||
let len = +(r.env.CONTENT_LENGTH ?? 0);
|
||||
if (len <= 0)
|
||||
return {};
|
||||
if (len > BODY_MAX)
|
||||
fail(r, '413 Payload Too Large', _('Request too large.'));
|
||||
let raw = '';
|
||||
while (length(raw) < len) {
|
||||
let chunk = r.io.read(len - length(raw));
|
||||
if (chunk == null || chunk == '')
|
||||
break;
|
||||
raw += chunk;
|
||||
}
|
||||
try {
|
||||
let j = json(raw);
|
||||
return type(j) == 'object' ? j : {};
|
||||
}
|
||||
catch (e) {
|
||||
fail(r, '400 Bad Request', _('Invalid JSON.'));
|
||||
}
|
||||
}
|
||||
|
||||
/** Run a change; what it refuses becomes a 400 with its message. */
|
||||
function guard(r, fn) {
|
||||
try {
|
||||
return fn();
|
||||
}
|
||||
catch (e) {
|
||||
if (e.message == DONE)
|
||||
die(DONE);
|
||||
fail(r, '400 Bad Request', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- rate limiting ---------- */
|
||||
|
||||
/** The rate-limit key of an address: an IPv4 address, or the /64 of an IPv6 one. */
|
||||
function addr_key(a) {
|
||||
if (schema.ipv4(a))
|
||||
return a;
|
||||
let g = schema.ipv6_groups(a);
|
||||
if (!g)
|
||||
return null;
|
||||
// An IPv4 address seen through an IPv6 socket.
|
||||
if (g[0] == 0 && g[1] == 0 && g[2] == 0 && g[3] == 0 && g[4] == 0 && g[5] == 0xffff)
|
||||
return sprintf('%d.%d.%d.%d', g[6] >> 8, g[6] & 255, g[7] >> 8, g[7] & 255);
|
||||
return sprintf('%x:%x:%x:%x::/64', g[0], g[1], g[2], g[3]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The buckets a request counts against, [{ key, limit }]: its client, and
|
||||
* behind Cloudflare (the only proxy whose CF-Connecting-IP is believed) also
|
||||
* the bucket all Cloudflare visitors share.
|
||||
*/
|
||||
function buckets(env) {
|
||||
let peer = env.REMOTE_ADDR ?? '';
|
||||
if (!cloudflare_ip(peer))
|
||||
return [ { key: addr_key(peer) ?? peer, limit: FAIL_LIMIT } ];
|
||||
let out = [ { key: SHARED_KEY, limit: SHARED_LIMIT } ];
|
||||
let visitor = addr_key(trim(env.HTTP_CF_CONNECTING_IP ?? ''));
|
||||
if (visitor && !cloudflare_ip(visitor))
|
||||
unshift(out, { key: visitor, limit: FAIL_LIMIT });
|
||||
return out;
|
||||
}
|
||||
|
||||
function rate_state() {
|
||||
let st = read_json(RATE, {});
|
||||
let now = time();
|
||||
for (let k, v in st)
|
||||
if (type(v) != 'object' || now - v.first > FAIL_WINDOW)
|
||||
delete st[k];
|
||||
return st;
|
||||
}
|
||||
|
||||
function rate_blocked(r) {
|
||||
let st = rate_state();
|
||||
return length(filter(r.buckets, (b) => (st[b.key]?.count ?? 0) >= b.limit)) > 0;
|
||||
}
|
||||
|
||||
function rate_fail(r) {
|
||||
let l = lock('portal-rate');
|
||||
let st = rate_state();
|
||||
let now = time();
|
||||
let hit = [];
|
||||
for (let b in r.buckets) {
|
||||
let v = st[b.key] ?? { first: now, count: 0 };
|
||||
v.count++;
|
||||
st[b.key] = v;
|
||||
if (v.count == b.limit)
|
||||
push(hit, b.key);
|
||||
}
|
||||
// Bounded: an attacker with many addresses cannot grow the file without end.
|
||||
let all = keys(st);
|
||||
if (length(all) > RATE_MAX) {
|
||||
all = sort(all, (a, b) => st[a].first - st[b].first);
|
||||
for (let i = 0; i < length(all) - RATE_MAX; i++)
|
||||
delete st[all[i]];
|
||||
}
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(RATE, st, 0o600);
|
||||
unlock(l);
|
||||
for (let k in hit)
|
||||
live.add_event({ type: 'portal_blocked', detail: k == SHARED_KEY ? 'all Cloudflare visitors' : k });
|
||||
}
|
||||
|
||||
/** One more change through this link; refused beyond ACTION_LIMIT per window. */
|
||||
function rate_action(r) {
|
||||
let key = `act:${r.person.id}`;
|
||||
let l = lock('portal-rate');
|
||||
let st = rate_state();
|
||||
let v = st[key] ?? { first: time(), count: 0 };
|
||||
v.count++;
|
||||
st[key] = v;
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(RATE, st, 0o600);
|
||||
unlock(l);
|
||||
if (v.count > ACTION_LIMIT)
|
||||
fail(r, '429 Too Many Requests', _('Too many changes in a short time. Try again in a few minutes.'));
|
||||
}
|
||||
|
||||
/* ---------- pages ---------- */
|
||||
|
||||
/** What the page is called (the tab, the first crumb): the person's server, or Dawnline. */
|
||||
function place(r) {
|
||||
return r.person ? r.m.servers[r.person.server]?.name || 'Dawnline' : 'Dawnline';
|
||||
}
|
||||
|
||||
/** The app shell; it reads the code from its own URL and sends it along. */
|
||||
function shell(r) {
|
||||
// The build's time joins the version so every update busts the hour-long asset cache.
|
||||
let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
|
||||
let base = r.base, title = place(r);
|
||||
headers(r, '200 OK', {
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
|
||||
"connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
|
||||
});
|
||||
r.io.write(`<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>${html_escape(title)}</title>
|
||||
<link rel="icon" href="${base}/assets/icon.svg${v}" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="${base}/assets/portal.css${v}">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" data-base="${html_escape(base)}" data-title="${html_escape(title)}"></div>
|
||||
<script src="${base}/assets/portal.js${v}" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
`);
|
||||
finish();
|
||||
}
|
||||
|
||||
/** Script, styles, icon and fonts (kept outside the web root). */
|
||||
function asset(r, name) {
|
||||
let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2|png)$/)?.[1];
|
||||
let data = ext ? readfile(`${ASSETS}/${name}`) : null;
|
||||
if (data == null)
|
||||
not_found(r);
|
||||
headers(r, '200 OK', { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=3600' });
|
||||
r.io.write(data);
|
||||
finish();
|
||||
}
|
||||
|
||||
/* ---------- the API ---------- */
|
||||
|
||||
/** The model again after a change. */
|
||||
function reload(r) {
|
||||
r.m = core.load();
|
||||
r.person = r.m.people[r.person.id];
|
||||
if (!r.person)
|
||||
not_found(r);
|
||||
}
|
||||
|
||||
/**
|
||||
* The person's state for the page: a stop by the admin (pause, end of access)
|
||||
* wins over their server being off, so they learn that their access is stopped.
|
||||
*/
|
||||
function person_state(m, p, usage) {
|
||||
let st = core.person_state(m, p, usage);
|
||||
if (st == 'server_off') {
|
||||
let own = core.own_state(m, p, usage);
|
||||
if (index(LOCKED, own) >= 0)
|
||||
return own;
|
||||
}
|
||||
return st;
|
||||
}
|
||||
|
||||
/** Why the person can't change anything right now, or null. */
|
||||
function locked(r) {
|
||||
return locked_reason(person_state(r.m, r.person, core.load_usage()));
|
||||
}
|
||||
|
||||
/** Refuses a change (or a config) while the person is stopped. */
|
||||
function need_open(r) {
|
||||
let why = locked(r);
|
||||
if (why)
|
||||
fail(r, '403 Forbidden', why);
|
||||
}
|
||||
|
||||
/** The same link over HTTPS (for a plain-HTTP visitor), or null when this is it. */
|
||||
function https_url(r) {
|
||||
if (r.https)
|
||||
return null;
|
||||
let host = r.host;
|
||||
let h = match(host, /^\[/) ? match(host, /^(\[[^\]]*\])/)?.[1] : split(host, ':')[0];
|
||||
let port = r.m.settings.portal_port;
|
||||
return `https://${h}${port == 443 ? '' : `:${port}`}${r.base}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keys and the disguise never travel in the clear: over plain HTTP a
|
||||
* configuration is refused, and the answer names the HTTPS link to use.
|
||||
*/
|
||||
function need_https(r) {
|
||||
let u = https_url(r);
|
||||
if (u)
|
||||
send_json(r, '403 Forbidden', { error: _('Open this link over HTTPS to get the connection settings.'), https_url: u });
|
||||
}
|
||||
|
||||
/** The router's offset from UTC in minutes: the admin sets hours in its time, the page shows the visitor's. */
|
||||
function tz_offset() {
|
||||
let t = time();
|
||||
return int((timegm(localtime(t)) - t) / 60);
|
||||
}
|
||||
|
||||
/** Everything the page shows. */
|
||||
function state(r) {
|
||||
let m = r.m, person = r.person;
|
||||
let usage = core.load_usage();
|
||||
// Only their server's tunnel: one `awg` process per request, however many servers there are.
|
||||
let v = view.person_view(m, person, usage, live.dump(m, person.server ?? ''), view.states(m, usage));
|
||||
v.state = person_state(m, person, usage);
|
||||
// Day by day this month, for the page's chart (the admin's views have no use for it).
|
||||
v.month_days = view.month_days(usage.people?.[person.id]);
|
||||
let srv = m.servers[person.server];
|
||||
// The device this page was opened from, through the tunnel or beside it.
|
||||
let here = view.device_here(v.devices, r.peer);
|
||||
return {
|
||||
person: v,
|
||||
here,
|
||||
server: {
|
||||
name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh,
|
||||
// AmneziaWG with the disguise off is plain WireGuard (any WireGuard app).
|
||||
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
|
||||
// Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets.
|
||||
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
|
||||
// The home networks a device with LAN Bypass still sends into the tunnel (home and internet access):
|
||||
// its own local network on the same addresses is out of reach (Add a device says so).
|
||||
home: srv && person.access == 'both' ? core.person_home(srv, person).nets : [],
|
||||
},
|
||||
can_add: length(person.devices) < person.device_limit,
|
||||
locked: index(LOCKED, v.state) >= 0,
|
||||
// Over plain HTTP: where the configurations are (keys only travel encrypted).
|
||||
https_url: https_url(r),
|
||||
kinds: core.KINDS,
|
||||
// The router's day: access ends and usage days follow its clock, not the browser's.
|
||||
today: today(),
|
||||
// Its clock too: "last connected 3 min ago" is measured against it, not the phone's.
|
||||
now: time(),
|
||||
// And its time zone: hours are set in the router's time, shown in the visitor's.
|
||||
tz_offset: tz_offset(),
|
||||
version: VERSION,
|
||||
};
|
||||
}
|
||||
|
||||
/** One of the person's own devices, or a 404. */
|
||||
function own_device(r, id) {
|
||||
let d = r.m.devices[id];
|
||||
if (!d || d.person != r.person.id)
|
||||
fail(r, '404 Not Found', _('Device not found.'));
|
||||
return d;
|
||||
}
|
||||
|
||||
function api_state(r) {
|
||||
send_json(r, '200 OK', state(r));
|
||||
}
|
||||
|
||||
function api_add(r) {
|
||||
need_open(r);
|
||||
need_https(r);
|
||||
let b = body(r);
|
||||
if (!devices.ready())
|
||||
fail(r, '503 Service Unavailable', not_ready());
|
||||
rate_action(r);
|
||||
// lan_bypass: JSON true keeps the device's own local network out of the tunnel; anything else is off.
|
||||
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key, lan_bypass: b.lan_bypass === true }));
|
||||
reload(r);
|
||||
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
|
||||
}
|
||||
|
||||
function api_config(r, id) {
|
||||
let d = own_device(r, id);
|
||||
need_open(r);
|
||||
need_https(r);
|
||||
awg.mark_issued(r.m, d.id);
|
||||
send_json(r, '200 OK', awg.client_config(r.m, d));
|
||||
}
|
||||
|
||||
/** POST /devices/<id> { action }: what each action does; the answer carries the new state. */
|
||||
const ACTIONS = {
|
||||
rename: (r, d, b) => {
|
||||
guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id }));
|
||||
return {};
|
||||
},
|
||||
// Set up from scratch: new keys and the new configuration, which the set-up sheet takes in.
|
||||
reconnect: (r, d, b) => {
|
||||
need_https(r);
|
||||
if (!devices.ready())
|
||||
fail(r, '503 Service Unavailable', not_ready());
|
||||
let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
|
||||
return { config };
|
||||
},
|
||||
'delete': (r, d, b) => {
|
||||
guard(r, () => devices.remove(d.id, { by: 'portal', person: r.person.id }));
|
||||
return {};
|
||||
},
|
||||
};
|
||||
|
||||
function api_device(r, id) {
|
||||
let d = own_device(r, id);
|
||||
need_open(r);
|
||||
let b = body(r);
|
||||
let act = ACTIONS[b.action];
|
||||
if (!act)
|
||||
fail(r, '400 Bad Request', _('Unknown action.'));
|
||||
rate_action(r);
|
||||
let res = act(r, d, b);
|
||||
reload(r);
|
||||
send_json(r, '200 OK', { ok: true, ...res, state: state(r) });
|
||||
}
|
||||
|
||||
/** API routes: method, path under /<code>/api ('*' matches one segment, passed to run). */
|
||||
const API = [
|
||||
{ method: 'GET', path: [ 'state' ], run: api_state },
|
||||
{ method: 'POST', path: [ 'devices' ], run: api_add },
|
||||
{ method: 'GET', path: [ 'devices', '*', 'config' ], run: api_config },
|
||||
{ method: 'POST', path: [ 'devices', '*' ], run: api_device },
|
||||
];
|
||||
|
||||
/** The route for a request: { run, args } or null (routes take at most one '*'). */
|
||||
function route(table, method, segs) {
|
||||
for (let rt in table) {
|
||||
if (rt.method != method || length(rt.path) != length(segs))
|
||||
continue;
|
||||
let args = [], ok = true;
|
||||
for (let i = 0; i < length(segs) && ok; i++)
|
||||
if (rt.path[i] == '*')
|
||||
push(args, segs[i]);
|
||||
else if (rt.path[i] != segs[i])
|
||||
ok = false;
|
||||
if (ok)
|
||||
return { run: rt.run, args };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ---------- one request ---------- */
|
||||
|
||||
export function handle(io) {
|
||||
let env = io.env ?? {};
|
||||
// Header names arrive lower-case from uhttpd; CGI has only HTTP_* variables.
|
||||
let hdr = {};
|
||||
for (let k, v in io.headers ?? {})
|
||||
hdr[lc(k)] = v;
|
||||
let header = (name) => hdr[name] ?? env[`HTTP_${uc(replace(name, /-/g, '_'))}`];
|
||||
let uri = env.REQUEST_URI ?? '/';
|
||||
let qpos = index(uri, '?');
|
||||
let path = qpos >= 0 ? substr(uri, 0, qpos) : uri;
|
||||
let https = env.HTTPS == 'on';
|
||||
let host = header('host') ?? '';
|
||||
let m = core.load();
|
||||
let r = {
|
||||
io, env, m, path, https, host,
|
||||
method: env.REQUEST_METHOD ?? 'GET',
|
||||
peer: env.REMOTE_ADDR ?? '',
|
||||
buckets: buckets(env),
|
||||
// The port in the visitor's address bar ([v6]:port, name:port, or the default).
|
||||
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
|
||||
person: null,
|
||||
base: '',
|
||||
};
|
||||
let segs = filter(split(path, '/'), (s) => s != '');
|
||||
|
||||
// Plain HTTP only for an IP address chosen in Settings (no certificate exists
|
||||
// for it); names stay HTTPS-only.
|
||||
if (!https) {
|
||||
let h = match(host, /^\[/) ? host : split(host, ':')[0];
|
||||
if (ip2int(h) == null || index(core.portal_hosts(m), h) < 0)
|
||||
not_found(r);
|
||||
}
|
||||
// The link is /<word-code>[/assets/…|/api/…]: the code is the address.
|
||||
if (length(segs) < 1 || !match(segs[0], core.WORD_CODE))
|
||||
not_found(r);
|
||||
let code = segs[0];
|
||||
for (let id, p in m.people)
|
||||
if (p.code == code)
|
||||
r.person = p;
|
||||
|
||||
// A wrong code is indistinguishable from a path that does not exist. Only
|
||||
// well-formed guesses count towards the limit, and a client over it is just
|
||||
// no longer counted: a valid link always opens, so guesses from a shared
|
||||
// address (every Cloudflare visitor) cannot lock its owner out.
|
||||
if (r.person == null) {
|
||||
if (!rate_blocked(r))
|
||||
rate_fail(r);
|
||||
not_found(r);
|
||||
}
|
||||
r.base = `/${code}`;
|
||||
let rest = slice(segs, 1);
|
||||
|
||||
if (length(rest) == 0 && r.method == 'GET')
|
||||
shell(r);
|
||||
if (rest[0] == 'assets' && length(rest) == 2 && r.method == 'GET')
|
||||
asset(r, rest[1]);
|
||||
if (rest[0] != 'api')
|
||||
not_found(r);
|
||||
|
||||
// CSRF: only same-origin JSON requests (a cross-site page cannot send
|
||||
// application/json without CORS, and it would need the code anyway).
|
||||
if (r.method == 'POST') {
|
||||
let origin = header('origin');
|
||||
if (!match(env.CONTENT_TYPE ?? '', /^application\/json/) ||
|
||||
(origin != null && origin != `${https ? 'https' : 'http'}://${host}`))
|
||||
fail(r, '403 Forbidden', _('Cross-site request refused.'));
|
||||
}
|
||||
else if (r.method != 'GET')
|
||||
fail(r, '405 Method Not Allowed', _('Method not allowed.'));
|
||||
|
||||
let rt = route(API, r.method, slice(rest, 1));
|
||||
if (!rt)
|
||||
fail(r, '404 Not Found', _('Not found.'));
|
||||
rt.run(r, rt.args[0]);
|
||||
fail(r, '404 Not Found', _('Not found.'));
|
||||
};
|
||||
|
||||
/** Run handle() and swallow its early end. */
|
||||
export function serve(io) {
|
||||
try {
|
||||
// "ru-RU,ru;q=0.9" → ru (i18n.use takes plain language codes only).
|
||||
i18n.use((match(io.env.HTTP_ACCEPT_LANGUAGE ?? '', /^[ \t]*([A-Za-z][A-Za-z][A-Za-z]?)/) ?? [])[1]);
|
||||
handle(io);
|
||||
}
|
||||
catch (e) {
|
||||
if (e.message != DONE)
|
||||
io.write(`Status: 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\nError\n`);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,119 @@
|
||||
// Dawnline — the portal's certificate (configured, ACME or self-signed) and
|
||||
// the addresses its links could use.
|
||||
|
||||
import { lsdir } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { q, sh, sh_out, ensure_dir, file_exists, valid_host, ip2int, cloudflare_ip, DATA_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as lookup from 'dawnline.lookup';
|
||||
|
||||
/** The DNS names a certificate file covers. */
|
||||
export function cert_names(path) {
|
||||
let sans = sh_out(`openssl x509 -in ${q(path)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '';
|
||||
return filter(split(replace(sans, /DNS:/g, ''), /[ \t\r\n]+/), (x) => x != '');
|
||||
};
|
||||
|
||||
/** A certificate name covers host: the same name, or a wildcard one level up. */
|
||||
export function name_covers(name, host) {
|
||||
if (name == host)
|
||||
return true;
|
||||
let dot = index(host ?? '', '.');
|
||||
return substr(name, 0, 2) == '*.' && dot > 0 && substr(host, dot) == substr(name, 1);
|
||||
};
|
||||
|
||||
// A module constant, compiled once, not for each file of the directory.
|
||||
const FULLCHAIN = /^(.+)\.fullchain\.crt$/;
|
||||
|
||||
/** ACME certificates on the router and the names each covers. */
|
||||
export function acme_certs() {
|
||||
let out = [];
|
||||
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
|
||||
let m = match(f, FULLCHAIN);
|
||||
if (!m)
|
||||
continue;
|
||||
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
|
||||
if (file_exists(k))
|
||||
push(out, { cert: c, key: k, names: cert_names(c) });
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** The ACME certificate that covers host (exact name or a wildcard), if any. */
|
||||
export function acme_cert_for(host) {
|
||||
for (let a in acme_certs())
|
||||
for (let n in a.names)
|
||||
if (name_covers(n, host))
|
||||
return a;
|
||||
return null;
|
||||
};
|
||||
|
||||
/** Certificate the portal should use: configured, ACME for the host, or self-signed. */
|
||||
export function portal_cert(s) {
|
||||
if (s.portal_cert && s.portal_key && file_exists(s.portal_cert) && file_exists(s.portal_key))
|
||||
return { cert: s.portal_cert, key: s.portal_key, self_signed: false };
|
||||
if (s.portal_host) {
|
||||
for (let base in [ `/etc/ssl/acme/${s.portal_host}`, `/etc/acme/${s.portal_host}_ecc/${s.portal_host}` ]) {
|
||||
let c = `${base}.fullchain.crt`, k = `${base}.key`;
|
||||
if (file_exists(c) && file_exists(k))
|
||||
return { cert: c, key: k, self_signed: false };
|
||||
}
|
||||
// An ACME certificate issued for several names, the portal's among them.
|
||||
let a = acme_cert_for(s.portal_host);
|
||||
if (a)
|
||||
return { cert: a.cert, key: a.key, self_signed: false };
|
||||
}
|
||||
let c = `${DATA_DIR}/portal.crt`, k = `${DATA_DIR}/portal.key`;
|
||||
if (!file_exists(c) || !file_exists(k)) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
let cn = s.portal_host || 'dawnline';
|
||||
sh(`openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj ${q('/CN=' + cn)} -keyout ${k} -out ${c}`);
|
||||
system(`chmod 600 ${k}`);
|
||||
}
|
||||
return { cert: c, key: k, self_signed: true };
|
||||
};
|
||||
|
||||
/*
|
||||
* Addresses the portal could use in links, found on the router: names in ACME
|
||||
* certificates, server endpoints, DDNS names, the current one, and the WAN IP.
|
||||
* Each says where it points and whether a certificate covers it.
|
||||
*/
|
||||
export function portal_candidates(m) {
|
||||
let wan = lookup.router_wan(m);
|
||||
let names = [];
|
||||
let add = (h) => {
|
||||
if (h && valid_host(h) && ip2int(h) == null && substr(h, 0, 2) != '*.' && index(names, h) < 0)
|
||||
push(names, h);
|
||||
};
|
||||
let certs = acme_certs();
|
||||
for (let a in certs)
|
||||
for (let n in a.names)
|
||||
add(n);
|
||||
for (let id, srv in m.servers)
|
||||
add(srv.endpoint);
|
||||
let dc = cursor();
|
||||
if (dc.load('ddns'))
|
||||
dc.foreach('ddns', 'service', (sv) => {
|
||||
if (sv.enabled != '0') {
|
||||
add(sv.lookup_host);
|
||||
add(sv.domain);
|
||||
}
|
||||
});
|
||||
for (let h in core.portal_hosts(m))
|
||||
add(h);
|
||||
let found = lookup.resolve_all(names);
|
||||
let covered = (h) => length(filter(certs, (a) => length(filter(a.names, (n) => name_covers(n, h))) > 0)) > 0;
|
||||
let out = [];
|
||||
for (let h in names) {
|
||||
let ips = found[h] ?? [];
|
||||
push(out, { host: h, kind: 'name', ips, here: wan != null && index(ips, wan) >= 0,
|
||||
cloudflare: length(filter(ips, (x) => cloudflare_ip(x))) > 0, cert: covered(h) });
|
||||
}
|
||||
if (wan)
|
||||
push(out, { host: wan, kind: 'ip', ips: [ wan ], here: true, cloudflare: false, cert: false });
|
||||
for (let ph in core.portal_hosts(m))
|
||||
if (ip2int(ph) != null && ph != wan)
|
||||
push(out, { host: ph, kind: 'ip', ips: [ ph ], here: false, cloudflare: false, cert: false });
|
||||
// Best first: here with a certificate, then here, then the rest.
|
||||
let score = (c) => (c.here ? 4 : 0) + (c.cert ? 2 : 0) + (c.kind == 'name' ? 1 : 0) - (c.cloudflare ? 8 : 0);
|
||||
return sort(out, (a, b) => score(b) - score(a));
|
||||
};
|
||||
@@ -0,0 +1,101 @@
|
||||
// Dawnline — the plain resolver for people with Home-only access: real
|
||||
// addresses from the WAN's DNS, home names from the LAN DNS. Their internet
|
||||
// does not use the tunnel, so fake-IP answers would break it. dawnline.loop
|
||||
// says where it runs (inside the netns while it exists, otherwise on the
|
||||
// tunnel interfaces); procd runs dnsmasq through /usr/libexec/dawnline/resolver.
|
||||
|
||||
import { readfile, writefile, stat } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { ensure_dir, iface_status, uniq } from 'dawnline.util';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as core from 'dawnline.core';
|
||||
|
||||
/** Port on the tunnel addresses while it runs on the router itself. */
|
||||
export const PORT = 5354;
|
||||
export const CONF = '/var/etc/dawnline-dns.conf';
|
||||
const RESOLV = '/var/etc/dawnline-dns.resolv';
|
||||
const PID = '/var/run/dawnline-dns.pid';
|
||||
const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ];
|
||||
|
||||
function wan_dns() {
|
||||
let out = [];
|
||||
let snap = net.snapshot();
|
||||
let wan = snap.devices[snap.wan]?.logical;
|
||||
for (let name in uniq([ wan, 'wan', 'wan6' ])) {
|
||||
if (!name)
|
||||
continue;
|
||||
for (let a in iface_status(name)?.['dns-server'] ?? [])
|
||||
if (match(a, /^[0-9.]+$/))
|
||||
push(out, a);
|
||||
}
|
||||
return length(out) ? uniq(out) : FALLBACK_DNS;
|
||||
}
|
||||
|
||||
/** Local domain of the LAN DNS (dnsmasq `domain`, else the Dawnline hostname domain). */
|
||||
function lan_domain(m) {
|
||||
let c = cursor();
|
||||
c.load('dhcp');
|
||||
let d = null;
|
||||
c.foreach('dhcp', 'dnsmasq', (s) => { d ??= s.domain; });
|
||||
return uniq(filter([ d, m.settings.domain ], (x) => x));
|
||||
}
|
||||
|
||||
/** True when the resolver process is alive. */
|
||||
export function running() {
|
||||
let pid = trim(readfile(PID) ?? '');
|
||||
return match(pid, /^[0-9]+$/) != null && stat(`/proc/${pid}`) != null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Write the config for `target` (dawnline.loop resolver_target) with home
|
||||
* names from `lan` (the LAN's DNS); returns true when it changed (the running
|
||||
* instance is then restarted by procd's respawn after a kill). The first line
|
||||
* tells /usr/libexec/dawnline/resolver where to run it.
|
||||
*/
|
||||
export function sync(m, target, lan) {
|
||||
ensure_dir('/var/etc');
|
||||
// Servers that are on: with none, the resolver idles on loopback.
|
||||
let ifs = [];
|
||||
for (let id, s in m.servers)
|
||||
if (s.enabled)
|
||||
for (let t in core.tunnels(s))
|
||||
push(ifs, t.ifname);
|
||||
let lines = [
|
||||
`# mode=${target.mode}`,
|
||||
'# Generated by Dawnline: plain DNS for Home-only tunnel clients.',
|
||||
`port=${target.port}`,
|
||||
'no-hosts',
|
||||
'bogus-priv',
|
||||
'cache-size=1000',
|
||||
`pid-file=${PID}`,
|
||||
'user=dnsmasq',
|
||||
'group=dnsmasq',
|
||||
];
|
||||
if (target.mode == 'ns') {
|
||||
push(lines, `listen-address=${target.address}`, 'bind-interfaces', 'no-resolv');
|
||||
// Upstream from the transit address: forwarded through the router to the WAN.
|
||||
for (let a in wan_dns())
|
||||
push(lines, `server=${a}@${target.address}`);
|
||||
}
|
||||
else {
|
||||
// No tunnel on: loopback only (without any interface= line dnsmasq would answer everywhere).
|
||||
push(lines, 'bind-dynamic', ...(length(ifs) ? map(ifs, (i) => `interface=${i}`) : [ 'listen-address=127.0.0.1' ]), `resolv-file=${RESOLV}`);
|
||||
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
|
||||
if ((readfile(RESOLV) ?? '') != resolv) {
|
||||
writefile(RESOLV, resolv);
|
||||
system(`chmod 644 ${RESOLV}`);
|
||||
}
|
||||
}
|
||||
if (lan)
|
||||
for (let d in lan_domain(m))
|
||||
push(lines, `server=/${d}/${lan}`);
|
||||
let conf = join('\n', lines) + '\n';
|
||||
if ((readfile(CONF) ?? '') == conf)
|
||||
return false;
|
||||
writefile(CONF, conf);
|
||||
system(`chmod 644 ${CONF}`);
|
||||
let pid = trim(readfile(PID) ?? '');
|
||||
if (match(pid, /^[0-9]+$/))
|
||||
system(`kill ${pid} 2>/dev/null`);
|
||||
return true;
|
||||
};
|
||||
@@ -0,0 +1,134 @@
|
||||
// Dawnline — what the rpcd method modules (dawnline.rpc.*) share: the call
|
||||
// wrapper, argument helpers, the disguise check and the portal port check.
|
||||
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as schema from 'dawnline.schema';
|
||||
import { uniq } from 'dawnline.util';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
/**
|
||||
* An rpcd handler from fn(args): an object result is passed on, anything else
|
||||
* is wrapped as { result }, and a failure becomes { error } (the UI shows it).
|
||||
*/
|
||||
export function wrap(fn) {
|
||||
return function(req) {
|
||||
try {
|
||||
let r = fn(req.args ?? {});
|
||||
return type(r) == 'object' ? r : { result: r };
|
||||
}
|
||||
catch (e) {
|
||||
return { error: e.message ?? `${e}` };
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/** An argument as a trimmed string ('' for null). */
|
||||
export function str(v) {
|
||||
return v == null ? '' : trim(`${v}`);
|
||||
};
|
||||
|
||||
/** Days of history a caller may ask for: 1–400, default 30. */
|
||||
export function clamp_days(v) {
|
||||
let n = +(v ?? 30);
|
||||
return n >= 1 ? (n > 400 ? 400 : int(n)) : 30;
|
||||
};
|
||||
|
||||
export const METHODS = [ 'off', 'balanced', 'max' ];
|
||||
|
||||
/** The disguise a new server gets: the strongest this router can run. */
|
||||
export function default_method() {
|
||||
let c = awg.caps();
|
||||
return c.v3 ? 'max' : c.v2 ? 'balanced' : 'off';
|
||||
};
|
||||
|
||||
/** A disguise method the installed AmneziaWG can run. */
|
||||
export function check_method(name) {
|
||||
if (index(METHODS, name) < 0)
|
||||
die(_('Unknown disguise method.'));
|
||||
let c = awg.caps();
|
||||
if (name == 'max' && !c.v3)
|
||||
die(awg.installed()
|
||||
? _('Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1): install a 3.1 build in Dawnline → Components.')
|
||||
: _('AmneziaWG is not installed: install it in Dawnline → Components, then choose Maximum.'));
|
||||
if (name == 'balanced' && !c.v2)
|
||||
die(awg.installed()
|
||||
? _('Balanced needs AmneziaWG 2.0 or newer on the router: install a current build in Dawnline → Components.')
|
||||
: _('AmneziaWG is not installed: install it in Dawnline → Components, then choose Balanced.'));
|
||||
return name;
|
||||
};
|
||||
|
||||
/**
|
||||
* The portal's ports in the final configuration `m` (compared with `was`,
|
||||
* before the change) are acceptable: its HTTPS port and, when links on IP
|
||||
* addresses use plain HTTP, the next port too — both get a WAN ACCEPT rule.
|
||||
* Neither may be 22, 53, 80 or 443, beyond 65535, or taken by another program.
|
||||
*/
|
||||
/** TCP port forwards from the servers' WAN zones: [{ from, to, name }]. */
|
||||
function tcp_forwards(m) {
|
||||
let out = [];
|
||||
for (let z in uniq([ 'wan', ...map(values(m.servers), (s) => s.wan_zone) ]))
|
||||
push(out, ...core.wan_forwards(z, 'tcp'));
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* TCP ports the portal can't take, and who holds them: [{ from, to, who }].
|
||||
* The router's own (22, 53, 80, 443), other programs and port forwards from WAN.
|
||||
* `who` is shown in the admin's language ("Used by %s.").
|
||||
*/
|
||||
export function tcp_taken(m) {
|
||||
let out = [];
|
||||
let held = {};
|
||||
let hold = (p, who) => {
|
||||
if (!held[p]) {
|
||||
held[p] = true;
|
||||
push(out, { from: p, to: p, who });
|
||||
}
|
||||
};
|
||||
for (let p in schema.RESERVED_PORTS)
|
||||
hold(p, _('the router itself'));
|
||||
for (let p, name in health.tcp_port_programs())
|
||||
hold(+p, sprintf(_('%s on this router'), name));
|
||||
for (let f in tcp_forwards(m))
|
||||
push(out, { from: f.from, to: f.to, who: sprintf(_('port forward “%s”'), f.name) });
|
||||
return out;
|
||||
};
|
||||
|
||||
export function check_portal(m, was) {
|
||||
let s = m.settings;
|
||||
if (!s.portal_enabled)
|
||||
return;
|
||||
let port = s.portal_port;
|
||||
if (!schema.valid_port(port) || index(schema.RESERVED_PORTS, port) >= 0)
|
||||
die(_('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).'));
|
||||
let ports = [ port ];
|
||||
if (core.portal_http(m)) {
|
||||
let hp = core.portal_http_port(m);
|
||||
if (!schema.valid_port(hp) || index(schema.RESERVED_PORTS, hp) >= 0)
|
||||
die(sprintf(_('Links on IP addresses use plain HTTP on the next port (%d), which the portal cannot take. Choose another portal port.'), hp));
|
||||
push(ports, hp);
|
||||
}
|
||||
// Only ports the portal does not hold already: our own uhttpd is not an owner anyway.
|
||||
let held = [];
|
||||
if (was?.settings?.portal_enabled) {
|
||||
push(held, was.settings.portal_port);
|
||||
if (core.portal_http(was))
|
||||
push(held, core.portal_http_port(was));
|
||||
}
|
||||
for (let p in ports) {
|
||||
if (index(held, p) >= 0)
|
||||
continue;
|
||||
let owners = health.tcp_port_owners(p);
|
||||
if (length(owners))
|
||||
die(sprintf(p != port
|
||||
? _("TCP %d is already used by %s. Links on IP addresses use plain HTTP on the port after the portal's. Choose another portal port.")
|
||||
: _('TCP %d is already used by %s. Choose another portal port.'), p, join(', ', owners)));
|
||||
}
|
||||
// A forwarded port never reaches the router: the portal would be unreachable.
|
||||
for (let p in ports)
|
||||
for (let f in tcp_forwards(m))
|
||||
if (f.from <= p && p <= f.to)
|
||||
die(sprintf(_('TCP %d is sent on by port forward “%s”. Choose another portal port.'), p, f.name));
|
||||
};
|
||||
@@ -0,0 +1,215 @@
|
||||
// Dawnline rpcd methods: what people reach at home — services (home
|
||||
// devices and ports), circles (who reaches whom), the devices found at home,
|
||||
// and "Check access".
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { sh_out, ip2int, rand_int, rand_hex, admin_log, valid_name, ulength } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as access from 'dawnline.access';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as schema from 'dawnline.schema';
|
||||
import { wrap, str } from 'dawnline.rpc.common';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
/* ---------- services ---------- */
|
||||
|
||||
/** A new id from make() that no section has yet. */
|
||||
function new_id(m, make) {
|
||||
for (let i = 0; i < 20; i++) {
|
||||
let id = make();
|
||||
if (!store.id_taken(m, id))
|
||||
return id;
|
||||
}
|
||||
die(_('Could not find a free id, try again.'));
|
||||
}
|
||||
|
||||
function service_set(a) {
|
||||
let name = str(a.name);
|
||||
if (!valid_name(name))
|
||||
die(_('Service: Enter a name: up to 48 characters, without < > " or \\.'));
|
||||
let address = str(a.address);
|
||||
if (!schema.ipv4(address))
|
||||
die(_('Address must be an IPv4 address.'));
|
||||
let ports = filter(map(type(a.ports) == 'array' ? a.ports : split(str(a.ports), /[ ,]+/), str), (x) => x != '');
|
||||
for (let pt in ports)
|
||||
if (!schema.valid_port(pt))
|
||||
die(sprintf(_('Invalid port %s.'), pt));
|
||||
let id = store.transact((c, m) => {
|
||||
let id = str(a.id);
|
||||
if (id == '')
|
||||
id = new_id(m, () => `svc_${rand_int(100000, 999999)}`);
|
||||
else if (!match(id, /^[A-Za-z0-9_]{1,32}$/))
|
||||
die(_('Invalid service id.'));
|
||||
// Never turn a person, device, server, circle or the settings into a service.
|
||||
else if (!m.services[id] && store.id_taken(m, id))
|
||||
die(_('That id is taken.'));
|
||||
c.set(core.CONFIG, id, 'service');
|
||||
c.set(core.CONFIG, id, 'name', name);
|
||||
c.set(core.CONFIG, id, 'address', address);
|
||||
if (length(ports))
|
||||
c.set(core.CONFIG, id, 'port', ports);
|
||||
else
|
||||
c.delete(core.CONFIG, id, 'port');
|
||||
return id;
|
||||
});
|
||||
let s = apply.sync();
|
||||
return { id, warning: s.warning };
|
||||
}
|
||||
|
||||
function service_delete(a) {
|
||||
store.transact((c, m) => {
|
||||
if (!m.services[a.id])
|
||||
die(_('Unknown service.'));
|
||||
c.delete(core.CONFIG, a.id);
|
||||
for (let pid, p in m.people)
|
||||
if (index(p.services, a.id) >= 0) {
|
||||
let rest = filter(p.services, (x) => x != a.id);
|
||||
if (length(rest))
|
||||
c.set(core.CONFIG, pid, 'service', rest);
|
||||
else
|
||||
c.delete(core.CONFIG, pid, 'service');
|
||||
}
|
||||
});
|
||||
let s = apply.sync();
|
||||
return { ok: true, warning: s.warning };
|
||||
}
|
||||
|
||||
/* ---------- circles ---------- */
|
||||
|
||||
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
|
||||
function circle_set(a) {
|
||||
let name = str(a.name);
|
||||
if (!valid_name(name) || ulength(name) > 32)
|
||||
die(_('Enter a circle name: up to 32 characters, without < > " or \\.'));
|
||||
let res = store.transact((c, m) => {
|
||||
let ci = a.id ? m.circles[a.id] : null;
|
||||
if (a.id && !ci)
|
||||
die(_('Unknown circle.'));
|
||||
let server = ci?.server ?? a.server;
|
||||
if (!m.servers[server])
|
||||
die(_('Unknown server.'));
|
||||
for (let id, o in m.circles)
|
||||
if (id != a.id && o.server == server && lc(o.name) == lc(name))
|
||||
die(sprintf(_('%s already exists.'), name));
|
||||
let id = ci?.id ?? new_id(m, () => `c_${rand_hex(4)}`);
|
||||
let n = core.CIRCLE_COLORS;
|
||||
c.set(core.CONFIG, id, 'circle');
|
||||
c.set(core.CONFIG, id, 'server', server);
|
||||
c.set(core.CONFIG, id, 'name', name);
|
||||
c.set(core.CONFIG, id, 'color', `${((int(a.color) || 0) % n + n) % n}`);
|
||||
if (type(a.members) == 'array') {
|
||||
let want = {};
|
||||
for (let pid in a.members)
|
||||
if (m.people[pid]?.server == server)
|
||||
want[pid] = true;
|
||||
for (let pid, p in m.people)
|
||||
if (want[pid])
|
||||
c.set(core.CONFIG, pid, 'circle', id);
|
||||
else if (p.circle == id)
|
||||
c.delete(core.CONFIG, pid, 'circle');
|
||||
}
|
||||
return { id, edit: !!ci, server: m.servers[server].name };
|
||||
});
|
||||
let s = apply.sync();
|
||||
admin_log('awg', res.edit ? 'changed' : 'added', 'circle', name, res.server);
|
||||
return { id: res.id, circles: values(core.load().circles), warning: s.warning };
|
||||
}
|
||||
|
||||
function circle_delete(a) {
|
||||
let res = store.transact((c, m) => {
|
||||
let ci = m.circles[a.id];
|
||||
if (!ci)
|
||||
die(_('Unknown circle.'));
|
||||
c.delete(core.CONFIG, a.id);
|
||||
for (let pid, p in m.people)
|
||||
if (p.circle == a.id)
|
||||
c.delete(core.CONFIG, pid, 'circle');
|
||||
return { name: ci.name, server: m.servers[ci.server]?.name };
|
||||
});
|
||||
let s = apply.sync();
|
||||
admin_log('awg', 'removed', 'circle', res.name, res.server);
|
||||
return { circles: values(core.load().circles), warning: s.warning };
|
||||
}
|
||||
|
||||
/* ---------- devices at home ---------- */
|
||||
|
||||
/** True while OpenWrt's mDNS daemon answers on ubus. */
|
||||
function mdns_running() {
|
||||
return index(split(sh_out('ubus list umdns 2>/dev/null') ?? '', '\n'), 'umdns') >= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Services announced on the home networks (Bonjour), from umdns:
|
||||
* [{ type: '_airplay._tcp', name, host, address, port, txt }].
|
||||
*/
|
||||
function mdns_services() {
|
||||
if (!mdns_running())
|
||||
return [];
|
||||
let r = {};
|
||||
try {
|
||||
r = json(sh_out(`ubus call umdns browse '{"address":true,"array":true}' 2>/dev/null`) || '{}') ?? {};
|
||||
}
|
||||
catch (e) {
|
||||
r = {};
|
||||
}
|
||||
let out = [];
|
||||
for (let t, insts in r)
|
||||
for (let name, i in insts) {
|
||||
let addr = type(i.ipv4) == 'array' ? i.ipv4[0] : i.ipv4;
|
||||
if (addr)
|
||||
push(out, { type: t, name, host: replace(i.host ?? '', /\.local\.?$/, ''), address: addr, port: i.port ?? 0, txt: i.txt ?? [] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Devices at home for the Home services picker: DHCP leases and static hosts
|
||||
* in the server's home networks, with the services they announce (Bonjour,
|
||||
* when umdns runs).
|
||||
*/
|
||||
function home_hosts(a) {
|
||||
let m = core.load();
|
||||
let srv = m.servers[a.id] ?? values(m.servers)[0];
|
||||
if (!srv)
|
||||
die(_('No server yet.'));
|
||||
let nets = [];
|
||||
for (let cidr in net.server_net(srv).nets) {
|
||||
let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/);
|
||||
if (x && ip2int(x[1]) != null)
|
||||
push(nets, [ ip2int(x[1]), 1 << (32 - +x[2]) ]);
|
||||
}
|
||||
let inside = (ip) => {
|
||||
let n = ip2int(ip);
|
||||
return n != null && length(filter(nets, (r) => n >= r[0] && n < r[0] + r[1])) > 0;
|
||||
};
|
||||
let hosts = {};
|
||||
for (let line in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) {
|
||||
let f = split(line, ' ');
|
||||
if (length(f) >= 4 && inside(f[2]))
|
||||
hosts[f[2]] = { address: f[2], name: f[3] == '*' ? '' : f[3], mac: f[1], services: [] };
|
||||
}
|
||||
let c = cursor();
|
||||
if (c.load('dhcp'))
|
||||
c.foreach('dhcp', 'host', (h) => {
|
||||
if (h.ip && inside(h.ip))
|
||||
hosts[h.ip] ??= { address: h.ip, name: h.name ?? '', mac: type(h.mac) == 'array' ? h.mac[0] : h.mac ?? '', services: [] };
|
||||
});
|
||||
for (let s in mdns_services())
|
||||
if (hosts[s.address])
|
||||
push(hosts[s.address].services, { type: s.type, name: s.name, port: s.port });
|
||||
else if (inside(s.address))
|
||||
hosts[s.address] = { address: s.address, name: s.host ?? '', mac: '', services: [ { type: s.type, name: s.name, port: s.port } ] };
|
||||
return { hosts: sort(values(hosts), (x, y) => ip2int(x.address) - ip2int(y.address)), mdns: mdns_running() };
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
service_set: { args: { id: '', name: '', address: '', ports: [] }, call: wrap(service_set) },
|
||||
service_delete: { args: { id: '' }, call: wrap(service_delete) },
|
||||
circle_set: { args: { id: '', server: '', name: '', color: 0, members: [] }, call: wrap(circle_set) },
|
||||
circle_delete: { args: { id: '' }, call: wrap(circle_delete) },
|
||||
home_hosts: { args: { id: '' }, call: wrap(home_hosts) },
|
||||
access_check: { args: { from: '', to: '' }, call: wrap((a) => access.check(core.load(), a.from, a.to)) },
|
||||
};
|
||||
@@ -0,0 +1,90 @@
|
||||
// Dawnline rpcd methods: Diagnostics (Health, the service log), backups,
|
||||
// export / import, and removing Dawnline.
|
||||
|
||||
import { _ } from 'dawnline.i18n';
|
||||
import { slog_clear, admin_log } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as watchdog from 'dawnline.watchdog';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as backup from 'dawnline.backup';
|
||||
import { wrap } from 'dawnline.rpc.common';
|
||||
|
||||
function health_view(extra) {
|
||||
return { ...(extra ?? {}), checks: health.health(), ...watchdog.view(core.load()) };
|
||||
}
|
||||
|
||||
function service_log_clear(a) {
|
||||
let removed = slog_clear(+a.older_days || 0);
|
||||
if (removed)
|
||||
admin_log('dawnline', 'cleared', null, 'the service log', `${removed} entr${removed == 1 ? 'y' : 'ies'}${+a.older_days ? ` older than ${a.older_days} days` : ''}`);
|
||||
return { removed };
|
||||
}
|
||||
|
||||
function backup_restore(a) {
|
||||
let r = backup.backup_restore(a.name);
|
||||
admin_log('dawnline', 'restored', 'backup', a.name);
|
||||
return r;
|
||||
}
|
||||
|
||||
function backup_upload(a) {
|
||||
let r = backup.backup_upload(a.data);
|
||||
admin_log('dawnline', 'restored', 'backup', 'from a file');
|
||||
return r;
|
||||
}
|
||||
|
||||
function export_all(a) {
|
||||
let r = backup.export_json();
|
||||
admin_log('dawnline', 'exported', null, 'all settings', 'the file holds private keys');
|
||||
return r;
|
||||
}
|
||||
|
||||
function import_all(a) {
|
||||
let r = backup.import_json(a.data);
|
||||
admin_log('dawnline', 'imported', null, 'settings from a file');
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Remove Dawnline's state from the router (the package is removed by the UI afterwards). */
|
||||
function uninstall(a) {
|
||||
if (a.confirm != 'remove')
|
||||
die(_('Type "remove" to confirm.'));
|
||||
// Not in the middle of an update (opkg/apk may be installing Dawnline itself).
|
||||
if (upd.busy())
|
||||
die(_('An update is running: wait for it to finish, then remove Dawnline.'));
|
||||
backup.backup_create('pre-remove');
|
||||
// Stop first: the agent would put back what teardown removes, and could start an automatic update.
|
||||
system('/etc/init.d/dawnline stop >/dev/null 2>&1; /etc/init.d/dawnline disable >/dev/null 2>&1');
|
||||
apply.teardown();
|
||||
store.transact((c, m) => {
|
||||
let rm = [];
|
||||
c.foreach(core.CONFIG, null, (s) => {
|
||||
if (s['.type'] != 'settings')
|
||||
push(rm, s['.name']);
|
||||
});
|
||||
for (let n in rm)
|
||||
c.delete(core.CONFIG, n);
|
||||
c.set(core.CONFIG, 'settings', 'settings');
|
||||
c.set(core.CONFIG, 'settings', 'portal_enabled', '0');
|
||||
});
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
apply: { call: wrap((a) => apply.apply()) },
|
||||
health: { call: wrap((a) => health_view()) },
|
||||
health_fix: { args: { id: '' }, call: wrap((a) => health_view({ result: health.fix(a.id) })) },
|
||||
service_log: { call: wrap((a) => watchdog.view(core.load())) },
|
||||
service_log_clear: { args: { older_days: '' }, call: wrap(service_log_clear) },
|
||||
backup_list: { call: wrap((a) => ({ backups: backup.backup_list() })) },
|
||||
backup_create: { call: wrap((a) => ({ name: backup.backup_create(null) })) },
|
||||
backup_restore: { args: { name: '' }, call: wrap(backup_restore) },
|
||||
backup_delete: { args: { name: '' }, call: wrap((a) => ({ ok: backup.backup_delete(a.name) })) },
|
||||
backup_read: { args: { name: '' }, call: wrap((a) => ({ data: backup.backup_read(a.name) })) },
|
||||
backup_upload: { args: { data: '' }, call: wrap(backup_upload) },
|
||||
'export': { call: wrap(export_all) },
|
||||
'import': { args: { data: {} }, call: wrap(import_all) },
|
||||
uninstall: { args: { confirm: '' }, call: wrap(uninstall) },
|
||||
};
|
||||
@@ -0,0 +1,188 @@
|
||||
// Dawnline rpcd methods: people (adding, editing, pausing, their personal
|
||||
// links and traffic) and their devices.
|
||||
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as view from 'dawnline.view';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as devices from 'dawnline.devices';
|
||||
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
const PERSON_FIELDS = [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period',
|
||||
'bonus_gb', 'hours', 'note', 'dns_mode', 'server' ];
|
||||
|
||||
/* ---------- people ---------- */
|
||||
|
||||
function person_create(a) {
|
||||
let id = store.transact((c, m) => core.create_person(c, m, {
|
||||
name: str(a.name), slug: str(a.slug) || null, server: str(a.server) || null, access: a.access,
|
||||
device_limit: str(a.device_limit), expires: str(a.expires), quota_gb: str(a.quota_gb), quota_period: a.quota_period,
|
||||
}));
|
||||
let m = core.load();
|
||||
live.add_event({ type: 'person_added', person: id, detail: m.people[id].name, by: 'admin' });
|
||||
return { id, link: core.portal_url(m, m.people[id]) };
|
||||
}
|
||||
|
||||
/** Immediate edits from the person's page; returns the person as the page shows them. */
|
||||
function person_update(a) {
|
||||
let fields = {};
|
||||
for (let k in PERSON_FIELDS)
|
||||
if (a[k] != null)
|
||||
fields[k] = a[k];
|
||||
if (a.paused != null)
|
||||
fields.paused = a.paused;
|
||||
if (type(a.services) == 'array')
|
||||
fields.services = a.services;
|
||||
if (a.circle != null)
|
||||
fields.circle = a.circle;
|
||||
if (type(a.home_nets) == 'array')
|
||||
fields.home_nets = a.home_nets;
|
||||
let m0 = null;
|
||||
let before = store.transact((c, m) => {
|
||||
let p = m.people[a.id];
|
||||
m0 = m;
|
||||
core.update_person(c, m, a.id, fields);
|
||||
return p;
|
||||
});
|
||||
// "moved to Test" says more than "server".
|
||||
let changes = join(', ', map(filter(keys(fields), (k) => k != 'note'),
|
||||
(k) => k == 'server' && m0?.servers[fields.server] ? `moved to ${m0.servers[fields.server].name}` : k));
|
||||
if (changes)
|
||||
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
|
||||
// Access changes affect the nft sets and client AllowedIPs.
|
||||
let s = apply.sync();
|
||||
let m = core.load();
|
||||
let u = core.load_usage();
|
||||
// One person: only their server's tunnel is read.
|
||||
let p = m.people[a.id];
|
||||
return { person: view.person_view(m, p, u, live.dump(m, p.server ?? ''), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
|
||||
}
|
||||
|
||||
function person_pause(a) {
|
||||
store.transact((c, m) => {
|
||||
if (!m.people[a.id])
|
||||
die(_('Unknown person.'));
|
||||
if (a.paused)
|
||||
c.set(core.CONFIG, a.id, 'paused', '1');
|
||||
else
|
||||
c.delete(core.CONFIG, a.id, 'paused');
|
||||
});
|
||||
live.add_event({ type: a.paused ? 'paused' : 'resumed', person: a.id, by: 'admin' });
|
||||
return apply.sync();
|
||||
}
|
||||
|
||||
/**
|
||||
* A new personal link: the old one stops working at once (every portal
|
||||
* request carries the code). What the old link already handed out stays
|
||||
* unless asked: `remove` lists the person's devices to take away with it.
|
||||
*/
|
||||
function person_regen(a) {
|
||||
let gone = store.transact((c, m) => {
|
||||
if (!m.people[a.id])
|
||||
die(_('Unknown person.'));
|
||||
c.set(core.CONFIG, a.id, 'code', core.new_code());
|
||||
c.set(core.CONFIG, a.id, 'code_set', `${time()}`);
|
||||
let gone = [];
|
||||
for (let id in (type(a.remove) == 'array' ? a.remove : []))
|
||||
if (m.devices[id]?.person == a.id) {
|
||||
push(gone, m.devices[id]);
|
||||
core.delete_device(c, m, id);
|
||||
}
|
||||
return gone;
|
||||
});
|
||||
live.add_event({ type: 'link_changed', person: a.id, by: 'admin' });
|
||||
let s = null;
|
||||
if (length(gone)) {
|
||||
for (let d in gone)
|
||||
live.add_event({ type: 'device_removed', person: a.id, device: d.id, detail: d.name, dname: d.name, dkind: d.kind, by: 'admin' });
|
||||
s = apply.sync();
|
||||
}
|
||||
let m = core.load();
|
||||
return { link: core.portal_url(m, m.people[a.id]), removed: length(gone), warning: s?.warning };
|
||||
}
|
||||
|
||||
/** The personal code and links (Copy link, QR, invite): admins only, unlike status. */
|
||||
function person_links(a) {
|
||||
let m = core.load();
|
||||
let p = m.people[a.id];
|
||||
if (!p)
|
||||
die(_('Unknown person.'));
|
||||
return { code: p.code, link: core.portal_url(m, p), links: core.portal_urls(m, p) };
|
||||
}
|
||||
|
||||
function person_delete(a) {
|
||||
let name = store.transact((c, m) => {
|
||||
let name = m.people[a.id]?.name;
|
||||
core.delete_person(c, m, a.id);
|
||||
return name;
|
||||
});
|
||||
live.add_event({ type: 'person_removed', person: a.id, detail: name, pname: name, by: 'admin' });
|
||||
return apply.sync();
|
||||
}
|
||||
|
||||
function person_usage(a) {
|
||||
let usage = core.load_usage();
|
||||
let m = core.load();
|
||||
let p = m.people[a.id];
|
||||
if (!p)
|
||||
die(_('Unknown person.'));
|
||||
let days = clamp_days(a.days);
|
||||
let devs = {};
|
||||
for (let d in p.devices)
|
||||
devs[d] = live.series([ usage.devices?.[d] ], days);
|
||||
return { person: live.series([ usage.people?.[a.id] ], days), devices: devs };
|
||||
}
|
||||
|
||||
/* ---------- devices ---------- */
|
||||
|
||||
function device_create(a) {
|
||||
devices.need_awg();
|
||||
return devices.add(a.person, a.name, a.kind, { by: 'admin', lan_bypass: a.lan_bypass === true });
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's configuration. Only `issue` (true: the admin shows its QR code,
|
||||
* downloads or copies it) counts as handing it out; a look at the device
|
||||
* marks nothing, so its "settings changed" stays until it really gets them.
|
||||
*/
|
||||
function device_config(a) {
|
||||
let m = core.load();
|
||||
let d = m.devices[a.id];
|
||||
if (!d)
|
||||
die(_('Unknown device.'));
|
||||
if (a.issue === true)
|
||||
awg.mark_issued(m, d.id);
|
||||
return awg.client_config(m, d);
|
||||
}
|
||||
|
||||
/** Name, on/off and the link values (mtu, keepalive: strings, '' = the server's; lan_bypass: true or false). */
|
||||
function device_update(a) {
|
||||
return devices.update(a.id, { name: a.name, disabled: a.disabled, mtu: a.mtu, keepalive: a.keepalive,
|
||||
lan_bypass: a.lan_bypass == null ? null : a.lan_bypass === true }, { by: 'admin' });
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
person_create: {
|
||||
args: { name: '', slug: '', server: '', access: '', device_limit: '', expires: '', quota_gb: '', quota_period: '' },
|
||||
call: wrap(person_create),
|
||||
},
|
||||
person_update: {
|
||||
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
|
||||
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [], server: '' },
|
||||
call: wrap(person_update),
|
||||
},
|
||||
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
|
||||
person_regen: { args: { id: '', remove: [] }, call: wrap(person_regen) },
|
||||
person_links: { args: { id: '' }, call: wrap(person_links) },
|
||||
person_delete: { args: { id: '' }, call: wrap(person_delete) },
|
||||
person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) },
|
||||
device_create: { args: { person: '', name: '', kind: '', lan_bypass: false }, call: wrap(device_create) },
|
||||
device_config: { args: { id: '', issue: false }, call: wrap(device_config) },
|
||||
device_update: { args: { id: '', name: '', disabled: false, mtu: '', keepalive: '', lan_bypass: false }, call: wrap(device_update) },
|
||||
device_delete: { args: { id: '' }, call: wrap((a) => devices.remove(a.id, { by: 'admin' })) },
|
||||
// New keys: the device is set up again, as with the portal's Reconnect.
|
||||
device_rotate: { args: { id: '' }, call: wrap((a) => devices.reconnect(a.id, { by: 'admin' })) },
|
||||
};
|
||||
@@ -0,0 +1,662 @@
|
||||
// Dawnline rpcd methods: setting up a server, its General / Network /
|
||||
// Interfaces settings, its disguise, and removing it.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, valid_name, rand_int, uniq, admin_log } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as schema from 'dawnline.schema';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as backup from 'dawnline.backup';
|
||||
import * as devices from 'dawnline.devices';
|
||||
import { wrap, str, check_method, default_method, check_portal, tcp_taken } from 'dawnline.rpc.common';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
/** Server ids that would shadow a portal path. */
|
||||
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
|
||||
|
||||
const MESH_WORDS = { off: 'devices kept apart', all: 'devices reach each other', circles: 'devices reach each other in circles' };
|
||||
|
||||
/* ---------- free names, ports and subnets ---------- */
|
||||
|
||||
/**
|
||||
* UDP ports a server can't listen on, and who holds them: [{ from, to, who }].
|
||||
* Other servers, tunnel interfaces, programs on the router and port forwards
|
||||
* from its WAN zone. `srv` is the server being edited: its own port isn't counted.
|
||||
* `who` is shown in the admin's language ("Used by %s.").
|
||||
*/
|
||||
function udp_taken(m, srv, wan_zone) {
|
||||
let out = [];
|
||||
let held = {};
|
||||
let hold = (p, who) => {
|
||||
if (p > 0 && !held[p]) {
|
||||
held[p] = true;
|
||||
push(out, { from: p, to: p, who });
|
||||
}
|
||||
};
|
||||
for (let id, o in m.servers)
|
||||
if (id != srv?.id)
|
||||
hold(o.port, sprintf(_('server “%s”'), o.name));
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
nc.foreach('network', 'interface', (s) => {
|
||||
if (s.listen_port && s['.name'] != srv?.ifname)
|
||||
hold(+s.listen_port, sprintf(_('interface %s'), s['.name']));
|
||||
});
|
||||
let progs = health.udp_port_programs();
|
||||
for (let p in health.udp_bound())
|
||||
if (p != srv?.port)
|
||||
hold(p, progs[`${p}`] ? sprintf(_('%s on this router'), progs[`${p}`]) : _('another program on this router'));
|
||||
for (let f in core.wan_forwards(wan_zone, 'udp'))
|
||||
push(out, { from: f.from, to: f.to, who: sprintf(_('port forward “%s”'), f.name) });
|
||||
return out;
|
||||
}
|
||||
|
||||
function check_udp_port(port, taken) {
|
||||
for (let t in taken)
|
||||
if (t.from <= port && port <= t.to)
|
||||
die(sprintf(_('UDP %d is used by %s. Choose another port.'), port, t.who));
|
||||
}
|
||||
|
||||
/** The usual AmneziaWG port when free, otherwise a random high one. */
|
||||
const DEFAULT_PORT = 4500;
|
||||
|
||||
function free_port(taken) {
|
||||
let used = (p) => length(filter(taken, (t) => t.from <= p && p <= t.to)) > 0;
|
||||
if (!used(DEFAULT_PORT))
|
||||
return DEFAULT_PORT;
|
||||
for (let i = 0; i < 50; i++) {
|
||||
let p = rand_int(40000, 60000);
|
||||
if (!used(p))
|
||||
return p;
|
||||
}
|
||||
return 51830;
|
||||
}
|
||||
|
||||
function free_subnet(taken) {
|
||||
for (let i = 0; i < 300; i++) {
|
||||
// 10.x first; past 200 tries (a 10/8 LAN) the 172.16-31 range.
|
||||
let cand = parse_cidr(i < 200 ? sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)) : sprintf('172.%d.%d.0/24', rand_int(16, 31), rand_int(0, 250)));
|
||||
let bad = false;
|
||||
for (let t in taken) {
|
||||
let tc = parse_cidr(t);
|
||||
if (tc && cidr_overlaps(cand, tc)) {
|
||||
bad = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!bad)
|
||||
return cidr_str(cand);
|
||||
}
|
||||
return '10.77.0.0/24';
|
||||
}
|
||||
|
||||
/**
|
||||
* A portal port free together with the next one (plain HTTP for IP links):
|
||||
* `first` (the server's UDP number, TCP is another port) before the usual ones.
|
||||
*/
|
||||
function free_portal_port(first, cur, taken) {
|
||||
let used = (p) => length(filter(taken, (t) => t.from <= p && p <= t.to)) > 0;
|
||||
for (let p in uniq([ first, cur || 8443, 8443, 9443, 10443, 7443, 4443 ]))
|
||||
if (!used(p) && !used(p + 1))
|
||||
return p;
|
||||
return 9443;
|
||||
}
|
||||
|
||||
/** A network section name nothing uses: not the router's, not Dawnline's own links, not another server's. */
|
||||
function ifname_free(m, nc, n) {
|
||||
if (nc.get('network', n) != null || index(values(net.INTERNAL), n) >= 0)
|
||||
return false;
|
||||
for (let id, s in m.servers)
|
||||
if (s.ifname == n)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function free_ifname(m) {
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
for (let i = 0; i < 10; i++)
|
||||
if (ifname_free(m, nc, `dawn${i}`))
|
||||
return `dawn${i}`;
|
||||
return 'dawnx';
|
||||
}
|
||||
|
||||
function id_free(m, id) {
|
||||
return !store.id_taken(m, id) && index(PORTAL_PATHS, id) < 0;
|
||||
}
|
||||
|
||||
/** A free server id: home, then server2, server3, … (never an id anything else has). */
|
||||
function free_server_id(m) {
|
||||
if (id_free(m, 'home'))
|
||||
return 'home';
|
||||
for (let n = 2; ; n++)
|
||||
if (id_free(m, `server${n}`))
|
||||
return `server${n}`;
|
||||
}
|
||||
|
||||
/** Networks a new server must not overlap, by name: the router's and the other servers'. */
|
||||
function taken_networks(m) {
|
||||
let out = [];
|
||||
let seen = {};
|
||||
let add = (name, cidr) => {
|
||||
let c = parse_cidr(cidr);
|
||||
if (c && !seen[cidr_str(c)]) {
|
||||
seen[cidr_str(c)] = true;
|
||||
push(out, { name, cidr: cidr_str(c) });
|
||||
}
|
||||
};
|
||||
for (let n in health.networks())
|
||||
add(n.iface, n.cidr);
|
||||
for (let id, s in m.servers)
|
||||
add(s.name, s.subnet);
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ---------- setup ---------- */
|
||||
|
||||
function setup_defaults(a) {
|
||||
let m = core.load();
|
||||
let networks = taken_networks(m);
|
||||
let zones = [];
|
||||
let fc = cursor();
|
||||
fc.load('firewall');
|
||||
fc.foreach('firewall', 'zone', (z) => push(zones, z.name));
|
||||
let snap = net.snapshot(true);
|
||||
let wan_ip = snap.wan ? split(snap.devices[snap.wan]?.addrs?.[0] ?? '', '/')[0] : '';
|
||||
let kind = health.wan_kind(wan_ip || null);
|
||||
let host = m.settings.portal_host, from = host ? 'portal' : '';
|
||||
if (!host) {
|
||||
// Prefer a DDNS name, then an ACME certificate's, then the WAN address —
|
||||
// but never a private or CGNAT one: nobody on the internet reaches it.
|
||||
let dc = cursor();
|
||||
if (dc.load('ddns'))
|
||||
dc.foreach('ddns', 'service', (s) => {
|
||||
if (!host && s.lookup_host && s.enabled == '1') {
|
||||
host = s.lookup_host;
|
||||
from = 'ddns';
|
||||
}
|
||||
});
|
||||
if (!host) {
|
||||
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
|
||||
from = host ? 'cert' : '';
|
||||
}
|
||||
if (!host && kind == 'public') {
|
||||
host = wan_ip;
|
||||
from = 'wan';
|
||||
}
|
||||
}
|
||||
// The zones the WAN and LAN devices are in, whatever they are called.
|
||||
let wan_zone = snap.devices[snap.wan]?.zone ?? (index(zones, 'wan') >= 0 ? 'wan' : zones[1]);
|
||||
let lan_zone = snap.devices[snap.lan]?.zone ?? (index(zones, 'lan') >= 0 ? 'lan' : zones[0]);
|
||||
let udp = udp_taken(m, null, wan_zone);
|
||||
let tcp = tcp_taken(m);
|
||||
let port = free_port(udp);
|
||||
return {
|
||||
id: free_server_id(m),
|
||||
// A name to start from, in the admin's language (it is theirs once saved).
|
||||
name: length(m.servers) ? sprintf(_('Server %d'), length(m.servers) + 1) : _('Home'),
|
||||
ifname: free_ifname(m),
|
||||
port,
|
||||
subnet: free_subnet(map(networks, (n) => n.cidr)),
|
||||
endpoint: host,
|
||||
// Where the address came from (ddns, cert, wan, portal) and what the WAN is (public, private, cgnat, none).
|
||||
endpoint_from: from,
|
||||
wan_kind: kind,
|
||||
wan_ip: wan_ip || null,
|
||||
// Automatic.
|
||||
mtu: 0,
|
||||
zones,
|
||||
lan_zone,
|
||||
wan_zone,
|
||||
// A portal already on keeps its port; a new one takes the server's number when it can.
|
||||
portal_port: m.settings.portal_enabled ? m.settings.portal_port : free_portal_port(port, m.settings.portal_port, tcp),
|
||||
awg: awg.caps(),
|
||||
awg_state: awg.load(),
|
||||
networks,
|
||||
udp_taken: udp,
|
||||
tcp_taken: tcp,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a public address points, as the admin types it (debounced in the
|
||||
* UI): the same facts Health uses, in words. `id` names the server whose WAN
|
||||
* to compare with (a new one: the default WAN).
|
||||
*/
|
||||
function endpoint_probe(a) {
|
||||
let host = str(a.host);
|
||||
if (host != '' && !valid_host(host))
|
||||
die(_('Public address must be a hostname or IP address.'));
|
||||
let m = core.load();
|
||||
let srv = m.servers[str(a.id)] ?? null;
|
||||
let f = health.endpoint_facts(srv, host);
|
||||
let w = health.endpoint_words(f, `UDP ${srv?.port ?? +a.port || 4500}`);
|
||||
return { ...f, status: w.status, text: w.text };
|
||||
}
|
||||
|
||||
/** AmneziaWG can run a server: installed, and its kernel module loads. */
|
||||
function need_awg_loaded() {
|
||||
devices.need_awg();
|
||||
if (!awg.load().loaded)
|
||||
die(_("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components."));
|
||||
}
|
||||
|
||||
/** An MTU as typed: '' (automatic) or 1280-1500. */
|
||||
function check_mtu(v) {
|
||||
let s = str(v);
|
||||
if (s != '' && (!match(s, /^[0-9]{1,4}$/) || +s < 1280 || +s > 1500))
|
||||
die(_('MTU must be 1280-1500.'));
|
||||
return s;
|
||||
}
|
||||
|
||||
function server_create(a) {
|
||||
need_awg_loaded();
|
||||
let snap = net.snapshot(true);
|
||||
let router_subnets = health.used_subnets(null);
|
||||
let id = store.transact((c, m) => {
|
||||
let id = str(a.id) || 'home';
|
||||
// A UCI section name: a dash would make uci drop it silently.
|
||||
if (!match(id, /^[a-z][a-z0-9_]{0,23}$/))
|
||||
die(_('Server ID may use lowercase letters, digits and underscores.'));
|
||||
if (!id_free(m, id))
|
||||
die(sprintf(_('"%s" is already taken.'), id));
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
let ifname = str(a.ifname) || free_ifname(m);
|
||||
if (!ifname_free(m, nc, ifname))
|
||||
die(sprintf(_('Network interface %s already exists.'), ifname));
|
||||
let udp = udp_taken(m, null, str(a.wan_zone) || 'wan');
|
||||
let port = free_port(udp);
|
||||
if (a.port != null && str(a.port) != '' && str(a.port) != '0') {
|
||||
if (!schema.valid_port(a.port))
|
||||
die(_('UDP port must be 1-65535.'));
|
||||
port = +str(a.port);
|
||||
}
|
||||
check_udp_port(port, udp);
|
||||
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu);
|
||||
let preset = str(a.preset) || default_method();
|
||||
let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) };
|
||||
let pc = parse_cidr(srv.subnet);
|
||||
if (pc)
|
||||
srv.subnet = cidr_str(pc);
|
||||
// Public addresses inside the tunnel would hide the real hosts behind them.
|
||||
// New servers only: a restored backup keeps what it had.
|
||||
if (pc && !core.private_cidr(pc))
|
||||
die(_('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.'));
|
||||
let taken = [ ...router_subnets ];
|
||||
for (let sid, o in m.servers)
|
||||
push(taken, o.subnet);
|
||||
let errs = core.server_errors(m, srv, taken);
|
||||
push(errs, ...awg.obf_errors(srv.obf));
|
||||
if (length(errs))
|
||||
die(join(' ', errs));
|
||||
|
||||
let set = (k, v) => c.set(core.CONFIG, id, k, v);
|
||||
c.set(core.CONFIG, 'settings', 'settings');
|
||||
c.set(core.CONFIG, id, 'server');
|
||||
if (!valid_name(str(a.name) || 'Home'))
|
||||
die(_('Server: Enter a name: up to 48 characters, without < > " or \\.'));
|
||||
set('name', str(a.name) || 'Home');
|
||||
set('ifname', ifname);
|
||||
set('port', `${port}`);
|
||||
set('subnet', srv.subnet);
|
||||
if (srv.endpoint)
|
||||
set('endpoint', srv.endpoint);
|
||||
if (mtu)
|
||||
set('mtu', mtu);
|
||||
set('keepalive', '25');
|
||||
let kp = awg.server_keys();
|
||||
set('private_key', kp.private_key);
|
||||
set('public_key', kp.public_key);
|
||||
set('preset', preset);
|
||||
for (let ok, ov in srv.obf)
|
||||
set(ok, ov);
|
||||
set('lan_zone', str(a.lan_zone) || 'lan');
|
||||
set('wan_zone', str(a.wan_zone) || 'wan');
|
||||
set('auto_wan', '1');
|
||||
set('auto_lan', '1');
|
||||
if (snap.wan)
|
||||
set('detected_wan', snap.wan);
|
||||
if (snap.lan)
|
||||
set('detected_lan', snap.lan);
|
||||
// Off unless asked for: the loop through the LAN costs speed (the wizard says how much).
|
||||
set('lan_like', a.lan_like === true || a.lan_like === 1 || a.lan_like === '1' ? '1' : '0');
|
||||
set('enabled', '1');
|
||||
if (a.portal_enabled != null) {
|
||||
let on = a.portal_enabled === true || a.portal_enabled === 1 || a.portal_enabled === '1';
|
||||
c.set(core.CONFIG, 'settings', 'portal_enabled', on ? '1' : '0');
|
||||
if (a.portal_port != null && str(a.portal_port) != '' && str(a.portal_port) != '0') {
|
||||
if (!schema.valid_port(a.portal_port))
|
||||
die(_('Portal port must be 1-65535.'));
|
||||
c.set(core.CONFIG, 'settings', 'portal_port', `${+str(a.portal_port)}`);
|
||||
}
|
||||
}
|
||||
if (srv.endpoint && !c.get(core.CONFIG, 'settings', 'portal_host') && valid_host(srv.endpoint))
|
||||
c.set(core.CONFIG, 'settings', 'portal_host', srv.endpoint);
|
||||
// The portal as it will be, whatever this call changed.
|
||||
check_portal(core.load(c), m);
|
||||
return id;
|
||||
});
|
||||
let r = apply.apply();
|
||||
system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable');
|
||||
let made = core.load().servers[id];
|
||||
admin_log('dawnline', 'created', 'server', made?.name ?? id, made ? `UDP ${made.port}` : null);
|
||||
// netifd reads its protocol handlers when it starts: AmneziaWG installed
|
||||
// after that (by hand, or by an older installer) needs a network restart.
|
||||
let network_restart = !awg.state().handler;
|
||||
sh_bg(network_restart ? '/etc/init.d/network restart; /etc/init.d/dawnline restart' : '/etc/init.d/dawnline restart');
|
||||
return { id, applied: r, network_restart, warning: r.warning };
|
||||
}
|
||||
|
||||
/* ---------- interfaces ---------- */
|
||||
|
||||
/** Interfaces card on the Server page: what exists, what is detected, what the server uses. */
|
||||
function interfaces_view(m, srv, snap) {
|
||||
let sn = net.server_net(srv, snap);
|
||||
let home = {};
|
||||
for (let h in sn.home)
|
||||
home[h.dev] = h;
|
||||
let devs = [];
|
||||
for (let dev, d in snap.devices)
|
||||
push(devs, {
|
||||
...d,
|
||||
own: dev == srv.ifname,
|
||||
home: !!home[dev],
|
||||
auto: !!home[dev]?.auto,
|
||||
});
|
||||
// Saved names that no longer exist still show, so they can be removed.
|
||||
for (let h in sn.home)
|
||||
if (h.missing)
|
||||
push(devs, { name: h.dev, category: 'other', kind: 'other', missing: true, nets: [], addrs: [], members: [], home: true, auto: h.auto });
|
||||
let lan_only = 0;
|
||||
for (let id, p in m.people)
|
||||
if (p.server == srv.id && p.access == 'lan')
|
||||
lan_only++;
|
||||
return {
|
||||
server: srv.id,
|
||||
ifname: srv.ifname,
|
||||
detected: { wan: snap.wan, lan: snap.lan },
|
||||
saved: { wan: srv.detected_wan, lan: srv.detected_lan },
|
||||
config: { auto_wan: srv.auto_wan, wan_device: srv.wan_device, auto_lan: srv.auto_lan, lan_devices: srv.lan_devices, lan_like: srv.lan_like,
|
||||
device_mesh: srv.device_mesh, mesh: srv.mesh },
|
||||
like_home: loop.status(),
|
||||
needs: health.needs().home,
|
||||
effective: sn,
|
||||
zones: snap.zones,
|
||||
devices: devs,
|
||||
lan_only,
|
||||
};
|
||||
}
|
||||
|
||||
function interfaces_get(a) {
|
||||
let m = core.load();
|
||||
let srv = m.servers[a.id] ?? values(m.servers)[0];
|
||||
if (!srv)
|
||||
die(_('No server yet.'));
|
||||
return interfaces_view(m, srv, net.snapshot(true));
|
||||
}
|
||||
|
||||
function server_interfaces(a) {
|
||||
let snap = net.snapshot(true);
|
||||
let auto_wan = a.auto_wan != false && a.auto_wan != '0';
|
||||
let auto_lan = a.auto_lan != false && a.auto_lan != '0';
|
||||
let wan_dev = str(a.wan_device);
|
||||
let res = store.transact((c, m) => {
|
||||
let srv = m.servers[a.id];
|
||||
if (!srv)
|
||||
die(_('Unknown server.'));
|
||||
if (!auto_wan) {
|
||||
if (!snap.devices[wan_dev])
|
||||
die(_('Choose the interface that leads to the internet.'));
|
||||
if (!snap.devices[wan_dev].zone)
|
||||
die(sprintf(_('%s is not in a firewall zone, so the server port cannot be opened on it.'), wan_dev));
|
||||
}
|
||||
let lans = [];
|
||||
for (let d in (type(a.lan_devices) == 'array' ? a.lan_devices : [])) {
|
||||
d = str(d);
|
||||
// Unknown names are kept only if they were saved before (interface down right now).
|
||||
if (d == '' || d == srv.ifname || (!snap.devices[d] && index(srv.lan_devices, d) < 0))
|
||||
continue;
|
||||
if (snap.devices[d]?.master)
|
||||
die(sprintf(_('%s is part of %s; choose %s instead.'), d, snap.devices[d].master, snap.devices[d].master));
|
||||
if (d == (auto_wan ? snap.wan : wan_dev))
|
||||
die(sprintf(_('%s is the WAN.'), d));
|
||||
push(lans, d);
|
||||
}
|
||||
lans = uniq(lans);
|
||||
let id = srv.id;
|
||||
if (a.lan_like != null)
|
||||
c.set(core.CONFIG, id, 'lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
|
||||
let mesh = index(core.MESH, a.mesh) >= 0 ? a.mesh
|
||||
: a.device_mesh == null ? srv.mesh : (a.device_mesh === false || a.device_mesh === '0' ? 'off' : 'all');
|
||||
c.set(core.CONFIG, id, 'mesh', mesh);
|
||||
c.delete(core.CONFIG, id, 'device_mesh');
|
||||
c.set(core.CONFIG, id, 'auto_wan', auto_wan ? '1' : '0');
|
||||
c.set(core.CONFIG, id, 'auto_lan', auto_lan ? '1' : '0');
|
||||
if (auto_wan || wan_dev == '')
|
||||
c.delete(core.CONFIG, id, 'wan_device');
|
||||
else
|
||||
c.set(core.CONFIG, id, 'wan_device', wan_dev);
|
||||
if (length(lans))
|
||||
c.set(core.CONFIG, id, 'lan_device', lans);
|
||||
else
|
||||
c.delete(core.CONFIG, id, 'lan_device');
|
||||
// Remember what was detected, as the fallback while an interface is down.
|
||||
if (snap.wan)
|
||||
c.set(core.CONFIG, id, 'detected_wan', snap.wan);
|
||||
if (snap.lan)
|
||||
c.set(core.CONFIG, id, 'detected_lan', snap.lan);
|
||||
// Keep the legacy zone options in step (older code paths, health checks).
|
||||
let now = core.load(c).servers[id];
|
||||
let sn = net.server_net(now, snap);
|
||||
if (sn.wan.zone)
|
||||
c.set(core.CONFIG, id, 'wan_zone', sn.wan.zone);
|
||||
if (length(sn.zones))
|
||||
c.set(core.CONFIG, id, 'lan_zone', sn.zones[0]);
|
||||
return { was: srv, now: core.load(c).servers[id], mesh };
|
||||
});
|
||||
let srv = res.was;
|
||||
// What the admin changed here: the networks, and/or whether devices reach each other.
|
||||
let sig = (x) => {
|
||||
let sn = net.server_net(x, snap);
|
||||
return `${join(',', sn.nets)}|${sn.wan.dev}|${x.lan_like}`;
|
||||
};
|
||||
let what = [];
|
||||
if (sig(res.now) != sig(srv))
|
||||
push(what, 'home network and internet path');
|
||||
if (res.mesh != srv.mesh)
|
||||
push(what, MESH_WORDS[res.mesh]);
|
||||
if (length(what))
|
||||
admin_log('awg', 'changed', 'server', srv.name, join(', ', what));
|
||||
let before = join(',', net.server_net(srv, snap).nets);
|
||||
apply.apply();
|
||||
let m = core.load();
|
||||
let v = interfaces_view(m, m.servers[srv.id], net.snapshot(true));
|
||||
v.nets_changed = before != join(',', v.effective.nets);
|
||||
return v;
|
||||
}
|
||||
|
||||
/* ---------- settings ---------- */
|
||||
|
||||
/** A list of DNS servers as typed (array or "a, b"): each an IPv4 or IPv6 address. */
|
||||
function dns_list(v) {
|
||||
let list = filter(map(type(v) == 'array' ? v : split(str(v), /[ ,]+/), str), (x) => x != '');
|
||||
for (let d in list)
|
||||
if (!schema.ip(d))
|
||||
die(sprintf(_('%s is not an IP address.'), d));
|
||||
return list;
|
||||
}
|
||||
|
||||
/** Server settings from the General and Network tabs; applied at once. */
|
||||
function server_update(a) {
|
||||
let v = a.values ?? {};
|
||||
if (v.device_mesh != null && v.mesh == null)
|
||||
v.mesh = v.device_mesh === true || v.device_mesh == '1' ? 'all' : 'off';
|
||||
let srv = store.transact((c, m) => {
|
||||
let srv = m.servers[a.id];
|
||||
if (!srv)
|
||||
die(_('Unknown server.'));
|
||||
let set = (k, val) => (val == null || val == '') ? c.delete(core.CONFIG, srv.id, k) : c.set(core.CONFIG, srv.id, k, val);
|
||||
if (v.name != null) {
|
||||
if (!valid_name(str(v.name)))
|
||||
die(_('Server: Enter a name: up to 48 characters, without < > " or \\.'));
|
||||
set('name', str(v.name));
|
||||
}
|
||||
// Empty = the portal's address (core.endpoint_host), as at creation.
|
||||
if (v.endpoint != null) {
|
||||
if (str(v.endpoint) != '' && !valid_host(str(v.endpoint)))
|
||||
die(_('Public address must be a hostname or IP address.'));
|
||||
set('endpoint', str(v.endpoint));
|
||||
}
|
||||
if (v.port != null) {
|
||||
if (!schema.valid_port(v.port))
|
||||
die(_('UDP port must be 1-65535.'));
|
||||
let n = +str(v.port);
|
||||
if (n != srv.port)
|
||||
check_udp_port(n, udp_taken(m, srv, srv.wan_zone));
|
||||
set('port', `${n}`);
|
||||
}
|
||||
if (v.enabled != null)
|
||||
set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0');
|
||||
if (v.mesh != null) {
|
||||
if (index(core.MESH, v.mesh) < 0)
|
||||
die(_('Unknown choice for devices reaching each other.'));
|
||||
set('mesh', v.mesh);
|
||||
set('device_mesh', null);
|
||||
}
|
||||
if (v.mtu != null)
|
||||
set('mtu', check_mtu(v.mtu));
|
||||
if (v.keepalive != null) {
|
||||
if (str(v.keepalive) != '' && (!match(str(v.keepalive), /^[0-9]{1,3}$/) || +v.keepalive > 600))
|
||||
die(_('Keep-alive must be 0-600 seconds.'));
|
||||
set('keepalive', str(v.keepalive));
|
||||
}
|
||||
if (v.dns != null) {
|
||||
let list = dns_list(v.dns);
|
||||
if (length(list))
|
||||
c.set(core.CONFIG, srv.id, 'dns', list);
|
||||
else
|
||||
c.delete(core.CONFIG, srv.id, 'dns');
|
||||
}
|
||||
// A new tunnel network: private, free, and every device renumbered into it.
|
||||
if (v.subnet != null && str(v.subnet) != '' && str(v.subnet) != srv.subnet) {
|
||||
let pc = parse_cidr(str(v.subnet));
|
||||
if (!pc)
|
||||
die(_('Subnet must look like 10.77.0.0/24.'));
|
||||
if (!core.private_cidr(pc))
|
||||
die(_('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.'));
|
||||
let taken = map(filter(taken_networks(m), (n) => n.cidr != srv.subnet && n.name != srv.name), (n) => n.cidr);
|
||||
for (let t in taken)
|
||||
if (cidr_overlaps(pc, parse_cidr(t)))
|
||||
die(sprintf(_('Subnet overlaps %s.'), t));
|
||||
core.renumber_server(c, m, srv, cidr_str(pc));
|
||||
}
|
||||
return srv;
|
||||
});
|
||||
// For the log: what changed, in words. Turning on or off is its own line.
|
||||
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS', subnet: 'tunnel network' };
|
||||
let what = [];
|
||||
for (let k, label in labels) {
|
||||
if (v[k] == null)
|
||||
continue;
|
||||
let was = k == 'dns' ? join(' ', srv.dns ?? []) : k == 'mtu' && !srv.mtu ? '' : `${srv[k] ?? ''}`;
|
||||
let now = k == 'dns' ? join(' ', dns_list(v.dns)) : str(v[k]);
|
||||
if (trim(was) != trim(now))
|
||||
push(what, label);
|
||||
}
|
||||
let turned = v.enabled == null ? null : (v.enabled === true || v.enabled == '1');
|
||||
let name = v.name != null ? str(v.name) : srv.name;
|
||||
let r = apply.apply();
|
||||
if (turned != null && turned != srv.enabled)
|
||||
admin_log('dawnline', turned ? 'turned on' : 'turned off', 'server', name);
|
||||
if (length(what))
|
||||
admin_log('dawnline', 'changed', 'server', name, join(', ', what));
|
||||
if (v.mesh != null && v.mesh != srv.mesh)
|
||||
admin_log('dawnline', 'changed', 'server', name, MESH_WORDS[v.mesh]);
|
||||
return r;
|
||||
}
|
||||
|
||||
/** What the ports of an existing server must avoid (the AmneziaWG card checks as you type). */
|
||||
function server_ports(a) {
|
||||
let m = core.load();
|
||||
let srv = m.servers[a.id];
|
||||
if (!srv)
|
||||
die(_('Unknown server.'));
|
||||
// `networks`: what a new tunnel network must not overlap (everything but this server's own).
|
||||
return { udp_taken: udp_taken(m, srv, srv.wan_zone), tcp_taken: tcp_taken(m),
|
||||
networks: filter(taken_networks(m), (n) => n.cidr != srv.subnet) };
|
||||
}
|
||||
|
||||
function server_obfuscation(a) {
|
||||
let preset = str(a.preset) || default_method();
|
||||
let o = awg.obf_preset(check_method(preset));
|
||||
// A cheap self-check: new values pass what a restore would be held to.
|
||||
let errs = awg.obf_errors(o);
|
||||
if (length(errs))
|
||||
die(join(' ', errs));
|
||||
let srv = store.transact((c, m) => {
|
||||
let srv = m.servers[a.id];
|
||||
if (!srv)
|
||||
die(_('Unknown server.'));
|
||||
for (let k in core.OBF_KEYS)
|
||||
c.delete(core.CONFIG, srv.id, k);
|
||||
for (let k, v in o)
|
||||
c.set(core.CONFIG, srv.id, k, v);
|
||||
c.set(core.CONFIG, srv.id, 'preset', preset);
|
||||
return srv;
|
||||
});
|
||||
let r = apply.apply();
|
||||
admin_log('awg', 'changed', 'server', srv.name, `disguise: ${preset}`);
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Remove a server with its people, their devices and its circles (a backup is made first). */
|
||||
function server_delete(a) {
|
||||
if (!core.load().servers[a.id])
|
||||
die(_('Unknown server.'));
|
||||
backup.backup_create('pre-delete');
|
||||
let res = store.transact((c, m) => {
|
||||
let srv = m.servers[a.id];
|
||||
if (!srv)
|
||||
die(_('Unknown server.'));
|
||||
let gone = 0;
|
||||
for (let pid, p in m.people)
|
||||
if (p.server == srv.id) {
|
||||
core.delete_person(c, m, pid);
|
||||
gone++;
|
||||
}
|
||||
for (let cid, ci in m.circles)
|
||||
if (ci.server == srv.id)
|
||||
c.delete(core.CONFIG, cid);
|
||||
c.delete(core.CONFIG, srv.id);
|
||||
return { name: srv.name, gone };
|
||||
});
|
||||
let r = apply.apply();
|
||||
admin_log('awg', 'removed', 'server', res.name, res.gone ? `with ${res.gone} ${res.gone == 1 ? 'person' : 'people'}` : null);
|
||||
return r;
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
setup_defaults: { call: wrap(setup_defaults) },
|
||||
server_create: {
|
||||
args: { id: '', name: '', ifname: '', port: 0, subnet: '', endpoint: '', mtu: 0, preset: '', lan_zone: '', wan_zone: '',
|
||||
lan_like: true, portal_enabled: false, portal_port: 0 },
|
||||
call: wrap(server_create),
|
||||
},
|
||||
server_ports: { args: { id: '' }, call: wrap(server_ports) },
|
||||
endpoint_probe: { args: { host: '', id: '', port: 0 }, call: wrap(endpoint_probe) },
|
||||
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
|
||||
server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
|
||||
interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
|
||||
server_interfaces: {
|
||||
args: { id: '', auto_wan: false, wan_device: '', auto_lan: false, lan_devices: [], lan_like: false, device_mesh: true, mesh: '' },
|
||||
call: wrap(server_interfaces),
|
||||
},
|
||||
server_delete: { args: { id: '' }, call: wrap(server_delete) },
|
||||
};
|
||||
@@ -0,0 +1,155 @@
|
||||
// Dawnline rpcd methods: the Settings page (the portal, defaults, logs and
|
||||
// history, updates). What may be saved is dawnline.schema's.
|
||||
|
||||
import { stat } from 'fs';
|
||||
import { q, sh_out, admin_log, RUN_DIR, DATA_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as geo from 'dawnline.geo';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as schema from 'dawnline.schema';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as pc from 'dawnline.portalcert';
|
||||
import { wrap, check_portal, tcp_taken } from 'dawnline.rpc.common';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
/** The portal's own checks from Health, shown next to its settings. */
|
||||
const PORTAL_CHECKS = [ 'portal', 'portal_dns', 'portal_reply', 'portal_http', 'cert' ];
|
||||
|
||||
function file_size(path) {
|
||||
return stat(path)?.size ?? 0;
|
||||
}
|
||||
|
||||
/** What the log and traffic history hold right now (Settings → Logs & history). */
|
||||
function logs_info(m) {
|
||||
let ev = live.load_events();
|
||||
let by = {};
|
||||
for (let cat in live.CATEGORIES)
|
||||
by[cat] = 0;
|
||||
for (let e in ev)
|
||||
by[live.category_of(e.type)]++;
|
||||
let usage = core.load_usage();
|
||||
let days = {};
|
||||
for (let grp in [ usage?.devices ?? {}, usage?.people ?? {} ])
|
||||
for (let id, rec in grp)
|
||||
for (let k in keys(rec.days ?? {}))
|
||||
days[k] = true;
|
||||
let dk = sort(keys(days));
|
||||
return {
|
||||
policy: live.policy(m.settings.retention),
|
||||
events: length(ev),
|
||||
oldest: length(ev) ? ev[0].ts : 0,
|
||||
by_category: by,
|
||||
log_ram: file_size(`${RUN_DIR}/events.json`),
|
||||
log_flash: file_size(`${DATA_DIR}/events.json`),
|
||||
usage_flash: file_size(`${DATA_DIR}/usage.json`),
|
||||
usage_since: length(dk) ? dk[0] : '',
|
||||
usage_days: length(dk),
|
||||
geo_flash: file_size(`${DATA_DIR}/geo.json`),
|
||||
};
|
||||
}
|
||||
|
||||
function settings_get(a) {
|
||||
let c = core.open_cursor();
|
||||
let raw = c.get_all(core.CONFIG, 'settings') ?? {};
|
||||
let m = core.load(c);
|
||||
let out = {};
|
||||
for (let k in keys(schema.SETTINGS))
|
||||
out[k] = raw[k] ?? '';
|
||||
out.log_category = live.policy(m.settings.retention).categories;
|
||||
let cert = m.settings.portal_enabled ? pc.portal_cert(m.settings) : null;
|
||||
return {
|
||||
settings: out,
|
||||
needs: health.needs(),
|
||||
effective: m.settings,
|
||||
services: values(m.services),
|
||||
cert: cert ? { path: cert.cert, self_signed: cert.self_signed,
|
||||
expires: sh_out(`openssl x509 -enddate -noout -in ${q(cert.cert)} 2>/dev/null | cut -d= -f2`) } : null,
|
||||
tcp_taken: tcp_taken(m),
|
||||
portal_public_port: core.portal_public_port(m),
|
||||
geo_cached: length(keys(geo.load().ips)),
|
||||
logs: logs_info(m),
|
||||
};
|
||||
}
|
||||
|
||||
/*
|
||||
* The slow part of the portal settings (DNS lookups and the Health checks),
|
||||
* fetched after the page shows.
|
||||
*/
|
||||
function portal_info(a) {
|
||||
let m = core.load();
|
||||
return {
|
||||
candidates: pc.portal_candidates(m),
|
||||
checks: filter(health.health(m), (x) => index(PORTAL_CHECKS, x.id) >= 0),
|
||||
};
|
||||
}
|
||||
|
||||
function same(a, b) {
|
||||
return (type(a) == 'array' ? join('\n', a) : a ?? '') == (type(b) == 'array' ? join('\n', b) : b ?? '');
|
||||
}
|
||||
|
||||
/** Save settings (`values`: key → value, '' back to the default); the portal is checked as it will be. */
|
||||
function settings_update(a) {
|
||||
let v = a.values ?? {};
|
||||
if (type(v) != 'object')
|
||||
die(_('Nothing to save.'));
|
||||
let res = store.transact((c, m) => {
|
||||
let restart = false;
|
||||
c.set(core.CONFIG, 'settings', 'settings');
|
||||
for (let k, val in v) {
|
||||
if (k == 'log_category') {
|
||||
let lst = filter(type(val) == 'array' ? val : [], (x) => index(live.CATEGORIES, x) >= 0);
|
||||
c.set(core.CONFIG, 'settings', 'log_category', length(lst) ? lst : [ '' ]);
|
||||
// Superseded by the category list.
|
||||
c.delete(core.CONFIG, 'settings', 'log_connections');
|
||||
continue;
|
||||
}
|
||||
let nv = schema.validate(k, val);
|
||||
if (schema.SETTINGS[k].restart && !same(nv, c.get(core.CONFIG, 'settings', k)))
|
||||
restart = true;
|
||||
if (nv == null)
|
||||
c.delete(core.CONFIG, 'settings', k);
|
||||
else
|
||||
c.set(core.CONFIG, 'settings', k, nv);
|
||||
}
|
||||
check_portal(core.load(c), m);
|
||||
return { restart, was: m.settings };
|
||||
});
|
||||
let s = null;
|
||||
if (res.restart)
|
||||
system('/etc/init.d/dawnline reload >/dev/null 2>&1');
|
||||
else
|
||||
s = apply.sync();
|
||||
// The changes worth a line: the portal and the watchdog (other settings are housekeeping).
|
||||
let now = core.load().settings, was = res.was;
|
||||
if (now.portal_enabled != was.portal_enabled)
|
||||
admin_log('portal', now.portal_enabled ? 'turned on' : 'turned off', null, 'the personal portal', now.portal_enabled ? `port ${now.portal_port}` : null);
|
||||
else if (now.portal_enabled) {
|
||||
let what = [];
|
||||
if (now.portal_port != was.portal_port)
|
||||
push(what, `port ${now.portal_port}`);
|
||||
if (now.portal_host != was.portal_host)
|
||||
push(what, `address ${now.portal_host}`);
|
||||
if (join(' ', now.portal_alt) != join(' ', was.portal_alt))
|
||||
push(what, 'other addresses');
|
||||
if (now.portal_cert != was.portal_cert || now.portal_key != was.portal_key)
|
||||
push(what, 'certificate');
|
||||
if (now.portal_redirect != was.portal_redirect)
|
||||
push(what, 'redirect');
|
||||
if (length(what))
|
||||
admin_log('portal', 'changed', null, 'the personal portal', join(', ', what));
|
||||
}
|
||||
if (now.watchdog != was.watchdog)
|
||||
admin_log('dawnline', now.watchdog ? 'turned on' : 'turned off', null, 'the watchdog', now.watchdog ? null : 'problems are only logged, nothing is repaired');
|
||||
let out = settings_get({});
|
||||
if (s?.warning)
|
||||
out.warning = s.warning;
|
||||
return out;
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
settings_get: { call: wrap(settings_get) },
|
||||
portal_info: { call: wrap(portal_info) },
|
||||
settings_update: { args: { values: {} }, call: wrap(settings_update) },
|
||||
};
|
||||
@@ -0,0 +1,309 @@
|
||||
// Dawnline rpcd methods: the live revision, the Overview status (servers,
|
||||
// people, totals, map, recent activity), the live meter, the activity log and
|
||||
// traffic history.
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
import { read_json, write_json, ensure_dir, lock, unlock, admin_log, VERSION, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as view from 'dawnline.view';
|
||||
import * as geo from 'dawnline.geo';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as lookup from 'dawnline.lookup';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as meter from 'dawnline.meter';
|
||||
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
|
||||
|
||||
/** The router's public IPv4 (null when none or private). */
|
||||
function wan_public(m) {
|
||||
let w = lookup.router_wan(m);
|
||||
return w && health.wan_kind(w) == 'public' ? w : null;
|
||||
}
|
||||
|
||||
/** The router's own public addresses: a device at home that reaches the server through the WAN address (NAT loopback) is not "outside". */
|
||||
function own_addresses(m) {
|
||||
let own = {};
|
||||
for (let id, srv in m.servers) {
|
||||
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
|
||||
if (a)
|
||||
own[a] = true;
|
||||
}
|
||||
let wan = lookup.wan_ipv4('wan');
|
||||
if (wan)
|
||||
own[wan] = true;
|
||||
return own;
|
||||
}
|
||||
|
||||
/** Router location plus one point per (device, recent client address). */
|
||||
function geo_view(m, usage, dmp) {
|
||||
if (!m.settings.geo_enabled)
|
||||
return { enabled: false, home: null, points: [] };
|
||||
let cache = geo.load();
|
||||
let points = [];
|
||||
let now = time();
|
||||
// The router's own public addresses: a device at home that reaches the server through the
|
||||
// WAN address (NAT loopback) shows up from there. Home is not a place people connect from.
|
||||
let own = {};
|
||||
for (let id, srv in m.servers) {
|
||||
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
|
||||
if (a)
|
||||
own[a] = true;
|
||||
}
|
||||
let wan = lookup.wan_ipv4('wan');
|
||||
if (wan)
|
||||
own[wan] = true;
|
||||
for (let id, d in m.devices) {
|
||||
let rec = usage.devices?.[id];
|
||||
let peer = dmp.peers[d.public_key];
|
||||
let cur = live.endpoint_ip(peer?.endpoint);
|
||||
let online = live.online(dmp, id, peer);
|
||||
for (let ip, ts in rec?.ips ?? {}) {
|
||||
// Local (LAN / CGNAT) client addresses and the router's own are not shown on the map.
|
||||
let pl = geo.is_public(ip) && !own[ip] ? geo.place(cache, ip) : null;
|
||||
if (!pl)
|
||||
continue;
|
||||
push(points, {
|
||||
person: d.person, device: id, ip, ts,
|
||||
online: online && ip == cur,
|
||||
lat: pl.lat, lon: pl.lon, city: pl.city, country: pl.country, cc: pl.cc,
|
||||
asn: pl.asn ?? 0, org: pl.org ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
let h = cache.home;
|
||||
return {
|
||||
enabled: true,
|
||||
provider: m.settings.geo_provider,
|
||||
cached: length(keys(cache.ips)),
|
||||
home: (h && h.lat != null) ? { lat: h.lat, lon: h.lon, city: h.city, country: h.country, cc: h.cc, asn: h.asn ?? 0, org: h.org ?? '' } : null,
|
||||
points,
|
||||
};
|
||||
}
|
||||
|
||||
/** Older connections from home get the DHCP name their address has now. */
|
||||
function with_hosts(ev) {
|
||||
let names = null;
|
||||
for (let e in ev)
|
||||
if ((e.type == 'connect' || e.type == 'roam') && !e.hosts) {
|
||||
let h = net.event_hosts(e, names ??= net.lan_names());
|
||||
if (h)
|
||||
e.hosts = h;
|
||||
}
|
||||
return ev;
|
||||
}
|
||||
|
||||
function server_view(m, srv, usage, dmp, rates, days) {
|
||||
let online = 0, peers = 0;
|
||||
let links = map(core.tunnels(srv), (t) => t.ifname);
|
||||
let ids = {};
|
||||
for (let id, d in m.devices)
|
||||
ids[d.public_key] = id;
|
||||
for (let k, p in dmp.peers)
|
||||
if (index(links, p.ifname) >= 0) {
|
||||
peers++;
|
||||
if (live.online(dmp, ids[k], p))
|
||||
online++;
|
||||
}
|
||||
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
|
||||
// The newest handshake from a public address that is not the router's own:
|
||||
// proof that the port is reachable from the internet.
|
||||
let own = own_addresses(m);
|
||||
let reached = 0;
|
||||
for (let id, d in m.devices)
|
||||
if (m.people[d.person]?.server == srv.id)
|
||||
for (let ip, ts in usage.devices?.[id]?.ips ?? {})
|
||||
if (geo.is_public(ip) && !own[ip] && ts > reached)
|
||||
reached = ts;
|
||||
return {
|
||||
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet, reached,
|
||||
endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled,
|
||||
lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
|
||||
// What devices get now, by kind (mtu 0 = automatic).
|
||||
mtus: { computer: core.device_mtu(srv, { kind: 'computer' }), phone: core.device_mtu(srv, { kind: 'phone' }) },
|
||||
address: core.server_address(srv), up: !!st.up, uptime: st.uptime ?? 0,
|
||||
// Why the tunnel cannot run (its interface name belongs to another network section), or null.
|
||||
// Why it can't start, as a whole sentence in the admin's language (stored as a code).
|
||||
blocked: awg.blocked_text(srv),
|
||||
// Home networks (interfaces) for the per-person picker.
|
||||
home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })),
|
||||
// The header protection key is a secret every device shares: whether there is one.
|
||||
peers, online, obf: awg.obf_public(srv.obf), hpk: !!srv.obf.header_protection_key,
|
||||
// Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices).
|
||||
rate: rates[srv.id] ?? [],
|
||||
// Daily traffic of the people on this server (its Overview chart).
|
||||
series: live.series(map(filter(keys(m.people), (pid) => m.people[pid].server == srv.id), (pid) => usage.people?.[pid]), days),
|
||||
};
|
||||
}
|
||||
|
||||
/*
|
||||
* Everything the pages show at once. Readable by read-only users: no personal
|
||||
* codes or links here (person_links has them), and no keys but public ones
|
||||
* (device_config has the rest).
|
||||
*/
|
||||
function status(a) {
|
||||
let m = core.load();
|
||||
let usage = core.load_usage();
|
||||
let dmp = live.dump(m);
|
||||
let states = view.states(m, usage);
|
||||
let days = clamp_days(a.days);
|
||||
|
||||
let servers = [];
|
||||
let rates = read_json(`${RUN_DIR}/rate.json`, {});
|
||||
let prates = read_json(`${RUN_DIR}/rate_people.json`, {});
|
||||
for (let id, srv in m.servers)
|
||||
push(servers, server_view(m, srv, usage, dmp, rates, days));
|
||||
|
||||
let people = [];
|
||||
for (let id, p in m.people) {
|
||||
let pv = view.person_view(m, p, usage, dmp, states, { admin: true });
|
||||
pv.rate = type(prates[p.id]?.[0]) == 'array' ? prates[p.id] : [];
|
||||
push(people, pv);
|
||||
}
|
||||
people = sort(people, (a, b) => (b.online - a.online) || (b.last_seen - a.last_seen) || (a.name < b.name ? -1 : 1));
|
||||
|
||||
let totals = { people: length(people), devices: 0, online: 0, active: 0 };
|
||||
for (let p in people) {
|
||||
totals.devices += length(p.devices);
|
||||
totals.online += p.online;
|
||||
if (p.state == 'active')
|
||||
totals.active++;
|
||||
}
|
||||
let recs = values(usage.people ?? {});
|
||||
let day = live.series(recs, 1)[0];
|
||||
totals.today = [ day.rx, day.tx ];
|
||||
let mon = [ 0, 0 ];
|
||||
for (let r in recs) {
|
||||
let v = live.month(r);
|
||||
mon[0] += v[0];
|
||||
mon[1] += v[1];
|
||||
}
|
||||
totals.month = mon;
|
||||
|
||||
let events = live.load_events();
|
||||
let s = m.settings;
|
||||
return {
|
||||
geo: geo_view(m, usage, dmp),
|
||||
version: VERSION,
|
||||
now: time(),
|
||||
hostname: trim(readfile('/proc/sys/kernel/hostname') ?? ''),
|
||||
settings: {
|
||||
portal_enabled: s.portal_enabled, portal_port: s.portal_port, portal_host: s.portal_host,
|
||||
portal_public_port: core.portal_public_port(m),
|
||||
default_device_limit: s.default_device_limit, domain: s.domain,
|
||||
hostnames: s.hostnames, geo_enabled: s.geo_enabled, home_dns_fallback: s.home_dns_fallback,
|
||||
},
|
||||
servers,
|
||||
people,
|
||||
services: values(m.services),
|
||||
circles: values(m.circles),
|
||||
totals,
|
||||
series: live.series(recs, days),
|
||||
events: with_hosts(slice(events, length(events) > 60 ? length(events) - 60 : 0)),
|
||||
like_home: loop.status(),
|
||||
awg: awg.caps(),
|
||||
awg_state: awg.state(),
|
||||
// The router's public IPv4 (null when none or private): a server whose public address is an old one is told so.
|
||||
wan: wan_public(m),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/** The newest `limit` events; `person` keeps one person's only, `since` only those after a time. */
|
||||
function events_list(a) {
|
||||
// Tunnel down/up events of older versions: the service log tells it better (names, reasons).
|
||||
let person = str(a.person), since = +a.since || 0;
|
||||
let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up' &&
|
||||
(!person || e.person == person) && (!since || (e.ts ?? 0) > since));
|
||||
let n = +a.limit || 300;
|
||||
return { events: with_hosts(slice(ev, length(ev) > n ? length(ev) - n : 0)), total: length(ev), policy: live.policy() };
|
||||
}
|
||||
|
||||
/** Remove activity by person, device, category and/or age; nothing given clears it all. */
|
||||
function logs_clear(a) {
|
||||
let m = core.load();
|
||||
let f = {};
|
||||
if (a.person) {
|
||||
if (!m.people[a.person])
|
||||
die(_('Unknown person.'));
|
||||
f.person = a.person;
|
||||
}
|
||||
if (a.device)
|
||||
f.device = a.device;
|
||||
if (a.category) {
|
||||
if (index(live.CATEGORIES, a.category) < 0)
|
||||
die(_('Unknown category.'));
|
||||
f.category = a.category;
|
||||
}
|
||||
if (a.older_days) {
|
||||
if (!match(a.older_days, /^[1-9][0-9]{0,3}$/))
|
||||
die(_('Older than must be a number of days.'));
|
||||
f.before = time() - +a.older_days * 86400;
|
||||
}
|
||||
let removed = live.clear_events(f);
|
||||
if (removed)
|
||||
admin_log('dawnline', 'cleared', null, 'the activity log',
|
||||
join(' · ', filter([ `${removed} event${removed == 1 ? '' : 's'}`, f.category, f.person ? m.people[f.person].name : null,
|
||||
a.older_days ? `older than ${a.older_days} days` : null ], (x) => x)));
|
||||
return { ok: true, removed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset traffic history (all | person | device). The agent owns the live
|
||||
* counters, so it gets a marker; the tmpfs copy is edited too so the UI
|
||||
* shows the result straight away.
|
||||
*/
|
||||
function usage_clear(a) {
|
||||
let m = core.load();
|
||||
if (index([ 'all', 'person', 'device' ], a.scope) < 0)
|
||||
die(_('Unknown scope.'));
|
||||
if (a.scope == 'person' && !m.people[a.id])
|
||||
die(_('Unknown person.'));
|
||||
if (a.scope == 'device' && !m.devices[a.id])
|
||||
die(_('Unknown device.'));
|
||||
let req = { scope: a.scope, id: a.id, ts: time() };
|
||||
ensure_dir(RUN_DIR);
|
||||
let l = lock('usage-reset');
|
||||
let pending = read_json(`${RUN_DIR}/usage.reset`, []);
|
||||
push(pending, req);
|
||||
write_json(`${RUN_DIR}/usage.reset`, pending, 0o600);
|
||||
unlock(l);
|
||||
let usage = core.load_usage();
|
||||
if (usage) {
|
||||
live.reset_usage(usage, m, a.scope, a.id);
|
||||
write_json(`${RUN_DIR}/usage.json`, usage, 0o600);
|
||||
}
|
||||
admin_log('dawnline', 'reset traffic history', null,
|
||||
a.scope == 'all' ? 'for everyone' : a.scope == 'person' ? `for ${m.people[a.id].name}` : `for ${m.devices[a.id].name} (${m.people[m.devices[a.id].person]?.name})`);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/** The live revision (dawnline.live.PRESENCE): pages refresh when it moves; 0 without the agent. */
|
||||
/** The live revision, and the version answering (a page notices an update under it). */
|
||||
function rev() {
|
||||
return { rev: +(live.presence()?.rev ?? 0), version: VERSION };
|
||||
}
|
||||
|
||||
/*
|
||||
* The live meter (Overview): each call keeps the agent's watcher writing out
|
||||
* the points it keeps for meter.WANT_FOR seconds more (a first call finds
|
||||
* none yet: the watcher writes the last two minutes within a second) and
|
||||
* returns them (dawnline.meter.read), those newer than `since` when given. Read-only users may look: server ids
|
||||
* and bytes per second only, no keys or personal codes.
|
||||
*/
|
||||
function meter_points(a) {
|
||||
meter.want();
|
||||
return meter.read(+a.since || 0);
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
rev: { call: wrap(rev) },
|
||||
meter: { args: { since: 0 }, call: wrap(meter_points) },
|
||||
status: { args: { days: 30 }, call: wrap(status) },
|
||||
events: { args: { limit: 300, person: '', since: 0 }, call: wrap(events_list) },
|
||||
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
|
||||
usage_clear: { args: { scope: '', id: '' }, call: wrap(usage_clear) },
|
||||
geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) },
|
||||
};
|
||||
@@ -0,0 +1,149 @@
|
||||
// Dawnline rpcd methods for the Components tab: status, starting update jobs
|
||||
// (the updater does the work in the background), releases, release notes
|
||||
// and the changes between two releases. luci.dawnline merges `methods`.
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { read_json, ensure_dir, VERSION, REPO, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as gh from 'dawnline.github';
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
import { NAMES as PKG_NAMES } from 'dawnline.upd_pkgs';
|
||||
import { langs } from 'dawnline.upd_app';
|
||||
import * as i18n from 'dawnline.i18n';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
const TAG = /^v?[0-9][0-9A-Za-z.+~-]{0,40}$/;
|
||||
// check[:app|amneziawg|packages] | app[@tag|:reinstall|:rollback|:lang:<code>|:nolang]
|
||||
// | amneziawg[:auto|slava|grey[:ru]|:rollback] | pkgs:<name,…> (only packages Dawnline manages)
|
||||
const TARGET = /^(check(:(app|amneziawg|packages))?|app(@v?[0-9][0-9A-Za-z.+~-]{0,40}|:reinstall|:rollback|:lang:[a-z]{2,3}(_[A-Za-z]{2,4})?|:nolang)?|amneziawg(:rollback|:(auto|slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/;
|
||||
|
||||
function wrap(fn) {
|
||||
return function(req) {
|
||||
try {
|
||||
let r = fn(req.args ?? {});
|
||||
return type(r) == 'object' ? r : { result: r };
|
||||
}
|
||||
catch (e) {
|
||||
return { error: e.message ?? `${e}` };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** AmneziaWG interfaces by name: switching builds restarts them. */
|
||||
function awg_tunnels() {
|
||||
let out = [];
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
c.foreach('network', 'interface', (s) => {
|
||||
if (s.proto == 'amneziawg' && s.disabled != '1')
|
||||
push(out, s._dawnline_name ?? s['.name']);
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
// A line of /etc/openwrt_release. A module constant, compiled once, not for each line.
|
||||
const RELEASE_LINE = /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/;
|
||||
|
||||
function status(a) {
|
||||
let m = core.load();
|
||||
let rel = {};
|
||||
for (let line in split(readfile('/etc/openwrt_release') ?? '', '\n')) {
|
||||
let x = match(line, RELEASE_LINE);
|
||||
if (x)
|
||||
rel[lc(x[1])] = x[2];
|
||||
}
|
||||
return {
|
||||
version: VERSION,
|
||||
firmware: { version: rel.release ?? '', target: rel.target ?? '', arch: rel.arch ?? '' },
|
||||
portal: m.settings.portal_enabled,
|
||||
home: length(filter(values(m.servers), (x) => x.lan_like)) > 0,
|
||||
needs: health.needs(),
|
||||
check: read_json(upd.CHECK_FILE, null),
|
||||
job: upd.job(),
|
||||
now: time(),
|
||||
repo: REPO,
|
||||
policy: m.settings.updates,
|
||||
auto: upd.auto_state(),
|
||||
kept: upd.kept_all(builds.firmware()?.postfix),
|
||||
// The admin's translations installed (luci-i18n-dawnline-<lang>).
|
||||
translations: langs(),
|
||||
history: slice(upd.history(), 0, 12),
|
||||
tunnels: awg_tunnels(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Releases for the Versions list (Dawnline), five per page. */
|
||||
function releases(a) {
|
||||
let page = +(a.page ?? 1);
|
||||
if (page != int(page) || page < 1 || page > 50)
|
||||
die(_('Unknown page.'));
|
||||
return { releases: map(gh.releases(REPO, page), (x) => ({ ...x, body: null, digests: null })), page };
|
||||
}
|
||||
|
||||
/** Release notes for What's new: Dawnline by tag, or an AmneziaWG build's release. */
|
||||
function notes(a) {
|
||||
let rp = a.component == 'amneziawg' ? builds.SOURCES[a.build || 'slava']?.repo : REPO;
|
||||
let tag = a.tag ?? '';
|
||||
if (!rp || !match(tag, TAG))
|
||||
die(_('Unknown release.'));
|
||||
let r = gh.release(rp, tag);
|
||||
if (!r && a.component != 'amneziawg' && substr(tag, 0, 1) != 'v')
|
||||
r = gh.release(rp, `v${tag}`);
|
||||
if (!r)
|
||||
die(sprintf(_('No release %s in %s.'), tag, rp));
|
||||
return { ...r, digests: null, repo: rp };
|
||||
}
|
||||
|
||||
/** What changed between the installed Dawnline and a release (points for the Components tab). */
|
||||
function changes(a) {
|
||||
let to = a.to ?? '', from = a.from ?? '';
|
||||
if (!match(to, TAG) || (from != '' && !match(from, TAG)))
|
||||
die(_('Unknown release.'));
|
||||
// The installed version as a tag when it was released (a build ahead of the releases has none).
|
||||
let base = null;
|
||||
for (let t in (from != '' ? [ `v${replace(from, /^v/, '')}`, replace(from, /^v/, '') ] : []))
|
||||
if (!base && gh.release(REPO, t))
|
||||
base = t;
|
||||
return { items: gh.changes(REPO, base, to) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Start an update job. Returns the new job once its worker has written it,
|
||||
* else null (the caller follows updates_status); never an older job.
|
||||
*/
|
||||
function run(a) {
|
||||
let what = a.what ?? 'check';
|
||||
if (length(what) > 400 || !match(what, TARGET))
|
||||
die(_('Unknown update target.'));
|
||||
// Checked here too, so a wrong name never becomes a failed job in the history.
|
||||
if (substr(what, 0, 5) == 'pkgs:')
|
||||
for (let n in split(substr(what, 5), ','))
|
||||
if (index(PKG_NAMES, n) < 0)
|
||||
die(n == '' ? _('Unknown update target.') : sprintf(_('%s is not a package Dawnline manages'), n));
|
||||
if (upd.busy())
|
||||
die(_('Another component action is already running'));
|
||||
ensure_dir(RUN_DIR);
|
||||
let t0 = time();
|
||||
let args = substr(what, 0, 5) == 'check' ? `check ${substr(what, 6)}` : `install ${what}`;
|
||||
// The job speaks the admin's language (use() let only a plain language code through).
|
||||
let lang = i18n.current();
|
||||
system(`${lang ? `DAWNLINE_LANG=${lang} ` : ''}start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${args}`);
|
||||
for (let i = 0; i < 20; i++) {
|
||||
let j = read_json(upd.JOB_FILE, null);
|
||||
if (j?.state == 'running' && j.started >= t0)
|
||||
return { started: true, job: j };
|
||||
system('usleep 100000 2>/dev/null || sleep 1');
|
||||
}
|
||||
return { started: true, job: null };
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
updates_status: { call: wrap(status) },
|
||||
updates_run: { args: { what: '' }, call: wrap(run) },
|
||||
updates_releases: { args: { page: 1 }, call: wrap(releases) },
|
||||
updates_notes: { args: { component: '', tag: '', build: '' }, call: wrap(notes) },
|
||||
updates_changes: { args: { from: '', to: '' }, call: wrap(changes) },
|
||||
};
|
||||
@@ -0,0 +1,276 @@
|
||||
// Dawnline — what the settings section may hold: one entry per option with
|
||||
// its type, default and range, used to validate what the admin saves and to
|
||||
// parse what is stored. Also the address checks the rest of the code shares.
|
||||
//
|
||||
// Booleans are stored as '1' / '0' only, and parsed the way the init script's
|
||||
// config_get_bool does, so the service and the code never disagree.
|
||||
|
||||
import { stat } from 'fs';
|
||||
import { ip2int, valid_host, ulength } from 'dawnline.util';
|
||||
import { INTERVALS, TARGETS } from 'dawnline.updates';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
/* ---------- addresses ---------- */
|
||||
|
||||
/** An IPv4 address in dotted form. */
|
||||
export function ipv4(s) {
|
||||
return type(s) == 'string' && ip2int(s) != null;
|
||||
};
|
||||
|
||||
/**
|
||||
* An IPv6 address → its eight 16-bit groups, or null. Accepts '::' and an
|
||||
* embedded IPv4 at the end (::ffff:192.0.2.1); no zone ids or prefixes.
|
||||
*/
|
||||
export function ipv6_groups(s) {
|
||||
if (type(s) != 'string' || length(s) < 2 || length(s) > 45 || !match(s, /^[0-9A-Fa-f:.]+$/))
|
||||
return null;
|
||||
let tail = [];
|
||||
let v4 = match(s, /^(.*:)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/);
|
||||
if (v4) {
|
||||
let n = ip2int(v4[2]);
|
||||
if (n == null)
|
||||
return null;
|
||||
tail = [ (n >> 16) & 0xffff, n & 0xffff ];
|
||||
s = substr(v4[1], -2) == '::' ? v4[1] : substr(v4[1], 0, length(v4[1]) - 1);
|
||||
}
|
||||
else if (index(s, '.') >= 0)
|
||||
return null;
|
||||
let halves = split(s, '::');
|
||||
if (length(halves) > 2)
|
||||
return null;
|
||||
let groups = (part) => {
|
||||
let out = [];
|
||||
if (part == '')
|
||||
return out;
|
||||
for (let g in split(part, ':')) {
|
||||
if (!match(g, /^[0-9A-Fa-f]{1,4}$/))
|
||||
return null;
|
||||
push(out, hex(g));
|
||||
}
|
||||
return out;
|
||||
};
|
||||
let head = groups(halves[0]);
|
||||
let rest = length(halves) == 2 ? groups(halves[1]) : [];
|
||||
if (head == null || rest == null)
|
||||
return null;
|
||||
if (length(halves) == 1) {
|
||||
push(head, ...tail);
|
||||
return length(head) == 8 ? head : null;
|
||||
}
|
||||
push(rest, ...tail);
|
||||
let gap = 8 - length(head) - length(rest);
|
||||
if (gap < 1)
|
||||
return null;
|
||||
let out = [ ...head ];
|
||||
for (let i = 0; i < gap; i++)
|
||||
push(out, 0);
|
||||
push(out, ...rest);
|
||||
return out;
|
||||
};
|
||||
|
||||
/** An IPv6 address (any valid notation). */
|
||||
export function ipv6(s) {
|
||||
return ipv6_groups(s) != null;
|
||||
};
|
||||
|
||||
/** An IPv4 or IPv6 address. */
|
||||
export function ip(s) {
|
||||
return ipv4(s) || ipv6(s);
|
||||
};
|
||||
|
||||
/** A TCP/UDP port as typed: 1-5 digits, 1-65535. */
|
||||
export function valid_port(v) {
|
||||
let s = trim(`${v ?? ''}`);
|
||||
return match(s, /^[0-9]{1,5}$/) != null && +s >= 1 && +s <= 65535;
|
||||
};
|
||||
|
||||
/* ---------- parsing stored values ---------- */
|
||||
|
||||
/** A stored boolean, as the init script's config_get_bool reads it. */
|
||||
export function bool(v, dflt) {
|
||||
v = lc(trim(`${v ?? ''}`));
|
||||
if (index([ '1', 'on', 'true', 'yes', 'enabled' ], v) >= 0)
|
||||
return true;
|
||||
if (index([ '0', 'off', 'false', 'no', 'disabled' ], v) >= 0)
|
||||
return false;
|
||||
return dflt;
|
||||
};
|
||||
|
||||
/** A stored whole number within [min, max], else the default. */
|
||||
export function to_int(v, dflt, lo, hi) {
|
||||
let s = trim(`${v ?? ''}`);
|
||||
if (!match(s, /^-?[0-9]{1,9}$/))
|
||||
return dflt;
|
||||
let n = +s;
|
||||
return (lo != null && n < lo) || (hi != null && n > hi) ? dflt : n;
|
||||
};
|
||||
|
||||
/* ---------- the settings section ---------- */
|
||||
|
||||
/*
|
||||
* type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | targets
|
||||
* dflt: the parsed default; restart: the portal (uhttpd) must restart when it changes;
|
||||
* min/max: ints; values: enums. The error for a bad value is in messages().
|
||||
*/
|
||||
export const SETTINGS = {
|
||||
portal_enabled: { type: 'bool', dflt: false, restart: true },
|
||||
portal_host: { type: 'host', dflt: '', restart: true },
|
||||
portal_alt: { type: 'hosts', dflt: [], restart: true },
|
||||
portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true },
|
||||
portal_redirect: { type: 'url', dflt: '' },
|
||||
portal_cert: { type: 'file', dflt: '', restart: true },
|
||||
portal_key: { type: 'file', dflt: '', restart: true },
|
||||
default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32 },
|
||||
hostnames: { type: 'bool', dflt: true },
|
||||
domain: { type: 'domain', dflt: 'lan' },
|
||||
// Off until the admin turns it on: lookups send people's addresses to a third party.
|
||||
geo_enabled: { type: 'bool', dflt: false },
|
||||
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ] },
|
||||
log_connections: { type: 'bool', dflt: true },
|
||||
watchdog: { type: 'bool', dflt: true },
|
||||
log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999 },
|
||||
log_max: { type: 'int', dflt: 2000, min: 100, max: 20000 },
|
||||
log_persist: { type: 'enum', dflt: 'hourly', values: [ '10min', 'hourly', 'off' ] },
|
||||
usage_keep_days: { type: 'int', dflt: 62, min: 7, max: 1830 },
|
||||
usage_keep_months: { type: 'int', dflt: 24, min: 1, max: 120 },
|
||||
// Empty means "no fallback" (stored as 'none'); unset means the default.
|
||||
home_dns_fallback: { type: 'ipv4', dflt: '1.1.1.1' },
|
||||
update_check: { type: 'bool', dflt: true },
|
||||
update_interval: { type: 'enum', dflt: '1d', values: keys(INTERVALS) },
|
||||
update_auto: { type: 'bool', dflt: true },
|
||||
update_mode: { type: 'enum', dflt: 'scheduled', values: [ 'immediate', 'scheduled' ] },
|
||||
update_time: { type: 'time', dflt: '04:00' },
|
||||
update_targets: { type: 'targets', dflt: [ 'app', 'packages' ] },
|
||||
update_keep: { type: 'bool', dflt: false },
|
||||
update_mirrors: { type: 'bool', dflt: true },
|
||||
};
|
||||
|
||||
/** Ports the portal never takes: SSH, DNS and the LuCI web server. */
|
||||
export const RESERVED_PORTS = [ 22, 53, 80, 443 ];
|
||||
|
||||
/** What the admin is told about a bad value, by setting (made per call: the language changes between calls). */
|
||||
function messages() {
|
||||
return {
|
||||
portal_host: _('Public address must be a hostname or IP address.'),
|
||||
portal_alt: _('Other addresses must be hostnames or IP addresses.'),
|
||||
portal_port: _('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).'),
|
||||
portal_redirect: _('Redirect must be a full http:// or https:// address.'),
|
||||
default_device_limit: _('Default device limit must be 1-32.'),
|
||||
domain: _('Domain may use lowercase letters, digits, dashes and dots.'),
|
||||
geo_provider: _('Unknown location service.'),
|
||||
log_keep_days: _('Keep activity for 0 (no age limit) to 9999 days.'),
|
||||
log_max: _('Log size must be 100-20000 events.'),
|
||||
log_persist: _('Save the log every 10min, hourly or off.'),
|
||||
usage_keep_days: _('Daily traffic history must be 7-1830 days.'),
|
||||
usage_keep_months: _('Monthly traffic history must be 1-120 months.'),
|
||||
home_dns_fallback: _('Fallback DNS must be an IPv4 address (or empty for none).'),
|
||||
update_interval: _('Check every 6h, 12h, 1d or 7d.'),
|
||||
update_mode: _('Install updates immediately or scheduled.'),
|
||||
update_time: _('Enter a time as HH:MM, 00:00 to 23:59.'),
|
||||
};
|
||||
}
|
||||
|
||||
function bad(key) {
|
||||
die(messages()[key] ?? sprintf(_('Invalid value for %s.'), key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a value the admin saves for setting `key`. Returns what to store: a
|
||||
* string, a list, or null to remove the option (back to the default). Dies
|
||||
* with a message for the admin when the value is not acceptable.
|
||||
*/
|
||||
export function validate(key, val) {
|
||||
let spec = SETTINGS[key];
|
||||
if (!spec)
|
||||
die(sprintf(_('Unknown setting %s.'), key));
|
||||
let t = spec.type;
|
||||
if (t == 'hosts') {
|
||||
let lst = [];
|
||||
for (let x in (type(val) == 'array' ? val : [])) {
|
||||
// A typo must not vanish on Save: refused, like the main address.
|
||||
if (type(x) != 'string' || (trim(x) != '' && !valid_host(trim(x))))
|
||||
bad(key);
|
||||
if (trim(x) != '' && index(lst, trim(x)) < 0)
|
||||
push(lst, trim(x));
|
||||
}
|
||||
return length(lst) ? lst : null;
|
||||
}
|
||||
if (t == 'targets') {
|
||||
let lst = [];
|
||||
for (let x in (type(val) == 'array' ? val : []))
|
||||
if (index(TARGETS, x) >= 0 && index(lst, x) < 0)
|
||||
push(lst, x);
|
||||
// An empty list is a choice too ("none"), unlike a missing option (the default).
|
||||
return length(lst) ? lst : [ 'none' ];
|
||||
}
|
||||
if (type(val) == 'bool')
|
||||
val = val ? '1' : '0';
|
||||
val = trim(`${val ?? ''}`);
|
||||
if (t == 'ipv4' && val == '')
|
||||
return 'none';
|
||||
if (val == '')
|
||||
return null;
|
||||
if (t == 'bool') {
|
||||
if (val != '0' && val != '1')
|
||||
die(sprintf(_('%s is 0 or 1.'), key));
|
||||
}
|
||||
else if (t == 'int') {
|
||||
if (!match(val, /^[0-9]{1,9}$/) || +val < spec.min || +val > spec.max)
|
||||
bad(key);
|
||||
val = `${+val}`;
|
||||
}
|
||||
else if (t == 'enum') {
|
||||
if (index(spec.values, val) < 0)
|
||||
bad(key);
|
||||
}
|
||||
else if (t == 'host') {
|
||||
if (!valid_host(val))
|
||||
bad(key);
|
||||
}
|
||||
else if (t == 'url') {
|
||||
if (length(val) > 300 || !match(val, /^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^[:space:]"'<>]*)?$/))
|
||||
bad(key);
|
||||
}
|
||||
else if (t == 'file') {
|
||||
if (substr(val, 0, 1) != '/' || !stat(val))
|
||||
die(sprintf(_('File %s does not exist.'), val));
|
||||
}
|
||||
else if (t == 'domain') {
|
||||
if (!match(val, /^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/))
|
||||
bad(key);
|
||||
}
|
||||
else if (t == 'ipv4') {
|
||||
if (!ipv4(val))
|
||||
bad(key);
|
||||
}
|
||||
else if (t == 'time') {
|
||||
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
|
||||
bad(key);
|
||||
}
|
||||
return val;
|
||||
};
|
||||
|
||||
/**
|
||||
* A stored setting parsed by its schema entry: the typed value, or the default
|
||||
* when it is missing or invalid. For dawnline.core's load().
|
||||
*/
|
||||
export function get(raw, key) {
|
||||
let spec = SETTINGS[key];
|
||||
let v = raw?.[key];
|
||||
if (!spec)
|
||||
return v;
|
||||
let t = spec.type;
|
||||
if (t == 'bool')
|
||||
return bool(v, spec.dflt);
|
||||
if (t == 'int')
|
||||
return to_int(v, spec.dflt, spec.min, spec.max);
|
||||
if (t == 'hosts' || t == 'targets')
|
||||
return v == null ? spec.dflt : filter(type(v) == 'array' ? v : [ v ], (x) => x != '');
|
||||
if (v == null || v == '')
|
||||
return spec.dflt;
|
||||
if (t == 'enum')
|
||||
return index(spec.values, v) >= 0 ? v : spec.dflt;
|
||||
if (t == 'ipv4')
|
||||
return v == 'none' ? '' : (ipv4(v) ? v : spec.dflt);
|
||||
return v;
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
// Dawnline — changes to /etc/config/dawnline, the one way: under the config
|
||||
// lock, against a model loaded inside that lock, committed with the file kept
|
||||
// private. rpcd, the portal, the CLI and the agent all go through here, so
|
||||
// no change is made on a stale model and none is lost to another writer.
|
||||
|
||||
import { lock, unlock } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
/** Section names that are never ids of people, devices, servers, services or circles. */
|
||||
export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
|
||||
|
||||
/**
|
||||
* Commit the dawnline config and keep it readable by root only. A commit
|
||||
* that did not reach flash (full or read-only overlay) is an error: the
|
||||
* caller's change never happened, and nothing downstream may act on it.
|
||||
*/
|
||||
export function commit(c) {
|
||||
if (!c.commit(core.CONFIG)) {
|
||||
let why = c.error();
|
||||
die(why != null ? sprintf(_("Couldn't save /etc/config/dawnline: %s. Is the flash full?"), why)
|
||||
: _("Couldn't save /etc/config/dawnline: the write failed. Is the flash full?"));
|
||||
}
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
};
|
||||
|
||||
/**
|
||||
* Run fn(c, m) with the config lock held, on a fresh cursor and model; commit
|
||||
* when fn returns (the return value is passed on). Anything fn throws aborts
|
||||
* without committing and is rethrown with the same message.
|
||||
*/
|
||||
export function transact(fn) {
|
||||
let l = lock('config');
|
||||
try {
|
||||
let c = core.open_cursor();
|
||||
let m = core.load(c);
|
||||
let r = fn(c, m);
|
||||
commit(c);
|
||||
unlock(l);
|
||||
return r;
|
||||
}
|
||||
catch (e) {
|
||||
unlock(l);
|
||||
die(e.message ?? `${e}`);
|
||||
}
|
||||
};
|
||||
|
||||
/** Is `id` used by anything in the model (any kind of section), or reserved? */
|
||||
export function id_taken(m, id) {
|
||||
return index(RESERVED_IDS, id) >= 0 || m.servers?.[id] != null || m.people?.[id] != null || m.devices?.[id] != null ||
|
||||
m.services?.[id] != null || m.circles?.[id] != null;
|
||||
};
|
||||
@@ -0,0 +1,202 @@
|
||||
// Dawnline updater: Dawnline itself — check the latest release, install a
|
||||
// release (latest, a tag, the same one again) or the kept previous version.
|
||||
// The admin's translations installed on the router (luci-i18n-dawnline-<lang>)
|
||||
// come from the same release and go in with it, in one transaction.
|
||||
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
|
||||
|
||||
import { readfile, lsdir } from 'fs';
|
||||
import { VERSION, REPO } from 'dawnline.util';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as gh from 'dawnline.github';
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
function status(installed, latest) {
|
||||
let c = upd.version_cmp(installed, latest);
|
||||
return c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
|
||||
}
|
||||
|
||||
export function check(ctx) {
|
||||
let r = gh.latest(REPO);
|
||||
if (!r)
|
||||
return { installed: VERSION, latest: null, update: false, repo: REPO, status: '', note: sprintf(_('Cannot reach github.com/%s'), REPO) };
|
||||
let latest = replace(r.tag, /^v/, '');
|
||||
let st = status(VERSION, latest);
|
||||
ctx.log(st == 'outdated' ? sprintf(_('Dawnline update is available: %s → %s'), VERSION, latest)
|
||||
: st == 'dev' ? sprintf(_('Installed Dawnline %s is newer than the release %s'), VERSION, latest)
|
||||
: sprintf(_('Dawnline is up to date (%s)'), VERSION));
|
||||
return { installed: VERSION, latest, tag: r.tag, repo: REPO, url: r.url, published: r.published, update: st == 'outdated', status: st };
|
||||
};
|
||||
|
||||
/**
|
||||
* The sha256 a release publishes for a file: GitHub's own (API), else the
|
||||
* release's sha256sums.txt fetched straight from github.com (never a mirror).
|
||||
*/
|
||||
function want_sha(ctx, tag, asset, dir) {
|
||||
let want = gh.asset_sha256(REPO, tag, asset);
|
||||
if (want)
|
||||
return want;
|
||||
let sums = `${dir}/sha256sums-${replace(tag, /[^A-Za-z0-9.-]/g, '_')}.txt`;
|
||||
if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/sha256sums.txt`, sums, { mirrors: false, log: ctx.log }))
|
||||
return null;
|
||||
for (let line in split(readfile(sums) ?? '', '\n')) {
|
||||
let m = match(trim(line), /^([0-9a-f]{64})[ \t]+\*?(\S+)$/);
|
||||
if (m && m[2] == asset)
|
||||
return m[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The languages of the translations installed here, by their catalogs (dawnline.<lang>.lmo). */
|
||||
export function langs() {
|
||||
let out = [];
|
||||
for (let f in lsdir('/usr/lib/lua/luci/i18n') ?? []) {
|
||||
let m = match(f, /^dawnline\.([A-Za-z_-]+)\.lmo$/);
|
||||
if (m)
|
||||
push(out, m[1]);
|
||||
}
|
||||
return sort(out);
|
||||
};
|
||||
|
||||
const i18n_pkg = (lang) => `luci-i18n-dawnline-${lang}`;
|
||||
|
||||
/**
|
||||
* Download one file of a release, verified against its sha256. `optional`: a
|
||||
* release without it (one from before the translations) gives null.
|
||||
*/
|
||||
function fetch_file(ctx, tag, asset, dir, optional) {
|
||||
ctx.phase(sprintf(_('Downloading %s'), asset));
|
||||
let want = want_sha(ctx, tag, asset, dir);
|
||||
if (!want && optional) {
|
||||
ctx.log(sprintf(_('Release %s has no %s: it stays as it is'), tag, asset));
|
||||
return null;
|
||||
}
|
||||
if (!want)
|
||||
die(sprintf(_('Release %s publishes no checksum for %s: not installing an unverified package'), tag, asset));
|
||||
let f = `${dir}/${asset}`;
|
||||
if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/${asset}`, f, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log }))
|
||||
die(sprintf(_('Download failed: %s'), asset));
|
||||
ctx.log(sprintf(_('sha256 matches the release (%s…)'), substr(want, 0, 12)));
|
||||
return f;
|
||||
}
|
||||
|
||||
/** A release's package and the translations installed here, verified. */
|
||||
function fetch(ctx, tag, dir) {
|
||||
let ver = replace(tag, /^v/, '');
|
||||
let files = [ fetch_file(ctx, tag, `luci-app-dawnline-${ver}.${pkg.ext()}`, dir) ];
|
||||
for (let l in langs()) {
|
||||
let f = fetch_file(ctx, tag, `${i18n_pkg(l)}-${ver}.${pkg.ext()}`, dir, true);
|
||||
if (f)
|
||||
push(files, f);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/** The release tag of a version: tags may or may not carry the v. */
|
||||
function tag_of(ver) {
|
||||
for (let t in [ `v${ver}`, ver ]) {
|
||||
try {
|
||||
if (gh.release(REPO, t))
|
||||
return t;
|
||||
}
|
||||
catch (e) {}
|
||||
}
|
||||
return `v${ver}`;
|
||||
}
|
||||
|
||||
function backup(ctx) {
|
||||
ctx.phase(_('Backing up configuration'));
|
||||
system('/usr/bin/dawnline backup --reason pre-update >/dev/null 2>&1');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the translation `lang` of the installed version from its release, or
|
||||
* (lang null) remove the installed ones. LuCI reads its catalogs once per web
|
||||
* server process: it restarts after the job.
|
||||
*/
|
||||
function set_lang(ctx, lang) {
|
||||
if (lang == null) {
|
||||
let have = map(langs(), i18n_pkg);
|
||||
if (length(have)) {
|
||||
ctx.phase(_('Removing the translation'));
|
||||
if (!pkg.remove(have, ctx.log))
|
||||
die(_('The translation could not be removed'));
|
||||
}
|
||||
}
|
||||
else {
|
||||
let tag = tag_of(VERSION);
|
||||
let f = fetch_file(ctx, tag, `${i18n_pkg(lang)}-${VERSION}.${pkg.ext()}`, ctx.work, true);
|
||||
if (!f)
|
||||
die(sprintf(_('Release %s has no translation into %s: install a release that has one'), tag, lang));
|
||||
ctx.phase(_('Installing the translation'));
|
||||
if (!pkg.install_files([ f ], false, ctx.log))
|
||||
die(_('Installation failed'));
|
||||
}
|
||||
ctx.after('luci');
|
||||
return { from: VERSION, to: VERSION, lang };
|
||||
}
|
||||
|
||||
/** arg: null (latest) | @<tag> | reinstall | rollback | lang:<code> | nolang */
|
||||
export function install(ctx, arg) {
|
||||
if (arg == 'nolang')
|
||||
return set_lang(ctx, null);
|
||||
if (substr(arg ?? '', 0, 5) == 'lang:')
|
||||
return set_lang(ctx, substr(arg, 5));
|
||||
let out = { from: VERSION, to: null };
|
||||
if (arg == 'rollback') {
|
||||
let k = upd.kept('app');
|
||||
if (!k)
|
||||
die(_('No previous Dawnline version is kept on the router'));
|
||||
out.to = k.version;
|
||||
ctx.versions(VERSION, k.version);
|
||||
backup(ctx);
|
||||
ctx.phase(sprintf(_('Rolling back to %s'), k.version));
|
||||
if (!pkg.install_files(k.files, true, ctx.log))
|
||||
die(_('Installation failed'));
|
||||
upd.forget('app');
|
||||
ctx.after('app');
|
||||
return out;
|
||||
}
|
||||
let tag, force = false;
|
||||
if (arg == 'reinstall') {
|
||||
tag = tag_of(VERSION);
|
||||
force = true;
|
||||
}
|
||||
else if (arg && substr(arg, 0, 1) == '@') {
|
||||
tag = substr(arg, 1);
|
||||
force = upd.version_cmp(replace(tag, /^v/, ''), VERSION) <= 0;
|
||||
}
|
||||
else {
|
||||
let c = check(ctx);
|
||||
if (!c.latest)
|
||||
die(c.note);
|
||||
if (!c.update) {
|
||||
out.to = VERSION;
|
||||
return out;
|
||||
}
|
||||
tag = c.tag;
|
||||
}
|
||||
out.to = replace(tag, /^v/, '');
|
||||
ctx.versions(VERSION, out.to);
|
||||
let files = fetch(ctx, tag, ctx.work);
|
||||
// The version being replaced, for Roll back (downloaded again: opkg keeps
|
||||
// no package files). Always for an automatic run: nobody is there to
|
||||
// recover a router whose new version does not come up (postupdate rolls
|
||||
// back to it on its own).
|
||||
if ((ctx.pol.keep || ctx.auto?.()) && out.to != VERSION && upd.kept('app')?.version != VERSION) {
|
||||
ctx.phase(sprintf(_('Keeping Dawnline %s for rollback'), VERSION));
|
||||
try {
|
||||
system(`mkdir -p '${ctx.work}/keep'`);
|
||||
upd.keep('app', VERSION, fetch(ctx, tag_of(VERSION), `${ctx.work}/keep`));
|
||||
}
|
||||
catch (e) {
|
||||
ctx.log(sprintf(_('Warning: could not keep %s: %s'), VERSION, e.message));
|
||||
}
|
||||
}
|
||||
backup(ctx);
|
||||
ctx.phase(_('Installing package'));
|
||||
if (!pkg.install_files(files, force, ctx.log))
|
||||
die(_('Installation failed'));
|
||||
ctx.after('app');
|
||||
return out;
|
||||
};
|
||||
@@ -0,0 +1,274 @@
|
||||
// Dawnline updater: AmneziaWG — the builds published for this firmware by
|
||||
// each source, installing or switching a build (verified against GitHub's
|
||||
// sha256), the Russian LuCI translation, and rolling back to a kept build.
|
||||
// Every install and rollback is recorded (dawnline.awg_builds), with whether
|
||||
// the new kernel module runs or waits for the next boot.
|
||||
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
|
||||
|
||||
import { stat } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { iface_intent } from 'dawnline.util';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as gh from 'dawnline.github';
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
import { _, N_ } from 'dawnline.i18n';
|
||||
|
||||
function sh(cmd) {
|
||||
return system(`${cmd} >/dev/null 2>&1`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download one package of a build to dir, verified when GitHub publishes its
|
||||
* sha256 (then mirrors may serve it); without a sha256 only github.com itself.
|
||||
* Returns the path or null.
|
||||
*/
|
||||
function fetch(ctx, fw, name, src, dir) {
|
||||
let file = builds.asset(fw, name);
|
||||
let dest = `${dir}/${src}_${file}`;
|
||||
let want = gh.asset_sha256(builds.SOURCES[src].repo, fw.tag, file);
|
||||
let url = `https://github.com/${builds.SOURCES[src].repo}/releases/download/${fw.tag}/${file}`;
|
||||
return gh.download(url, dest, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log }) ? dest : null;
|
||||
}
|
||||
|
||||
/** The newest tag of the same OpenWrt series (24.10.x) in a repository, if newer than ours. */
|
||||
function newer_series_tag(rp, tag) {
|
||||
let series = match(tag, /^v([0-9]+\.[0-9]+)\./)?.[1];
|
||||
let best = null;
|
||||
try {
|
||||
for (let x in gh.releases(rp, 1)) {
|
||||
let t = x.tag;
|
||||
if (series && match(t, regexp(`^v${replace(series, '.', '\\.')}\\.`)) && pkg.cmp(substr(t, 1), substr(tag, 1)) > 0 &&
|
||||
(!best || pkg.cmp(substr(t, 1), substr(best, 1)) > 0))
|
||||
best = t;
|
||||
}
|
||||
}
|
||||
catch (e) {}
|
||||
return best;
|
||||
}
|
||||
|
||||
export function check(ctx) {
|
||||
let installed = builds.installed();
|
||||
let ru = pkg.version(builds.RU) != null;
|
||||
let cur = installed['amneziawg-tools'];
|
||||
let fw = builds.firmware();
|
||||
if (!fw)
|
||||
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
|
||||
note: _('Cannot detect the firmware target') };
|
||||
if (fw.snapshot)
|
||||
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
|
||||
note: _('This is a SNAPSHOT firmware: the AmneziaWG projects publish builds for releases only') };
|
||||
let dir = `${ctx.work}/check`;
|
||||
system(`mkdir -p '${dir}'`);
|
||||
let sources = {};
|
||||
for (let id in builds.ORDER) {
|
||||
let src = builds.SOURCES[id];
|
||||
ctx.log(sprintf(_('Looking for the %s build for OpenWrt %s'), src.label, substr(fw.tag, 1)));
|
||||
let f = fetch(ctx, fw, 'amneziawg-tools', id, dir);
|
||||
let v = f ? pkg.file_version(f) : null;
|
||||
let date = null;
|
||||
try {
|
||||
date = f ? gh.release(src.repo, fw.tag)?.published : null;
|
||||
}
|
||||
catch (e) {}
|
||||
let s = { label: src.label, repo: src.repo, tag: fw.tag, version: v, gen: builds.gen(v), date };
|
||||
// A newer firmware may already get 3.1 from this source.
|
||||
if (s.gen != '3.1') {
|
||||
let nt = newer_series_tag(src.repo, fw.tag);
|
||||
if (nt) {
|
||||
let nf = fetch(ctx, builds.for_tag(fw, nt), 'amneziawg-tools', id, dir);
|
||||
if (builds.gen(nf ? pkg.file_version(nf) : null) == '3.1')
|
||||
s.newer = { tag: nt, gen: '3.1' };
|
||||
}
|
||||
}
|
||||
sources[id] = s;
|
||||
}
|
||||
// The installed build: the source whose package matches. Unknown stays unknown
|
||||
// (an automatic update never switches a build it could not identify).
|
||||
let current = null;
|
||||
for (let id, x in sources)
|
||||
if (!current && cur && x.version == cur)
|
||||
current = id;
|
||||
let mine = current ? sources[current] : null;
|
||||
let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null;
|
||||
// An update that waits for a reboot: Components says so after a check.
|
||||
let pending = builds.waits_for_reboot();
|
||||
let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
|
||||
ctx.log(cur == null ? _('AmneziaWG is not installed')
|
||||
: !current ? sprintf(_('AmneziaWG %s: no source publishes this build for this firmware any more'), cur)
|
||||
: st == 'outdated' ? sprintf(_('AmneziaWG update is available: %s → %s'), cur, mine.version)
|
||||
: sprintf(_('AmneziaWG is up to date (%s)'), cur));
|
||||
return { installed: cur, gen: builds.gen(cur), packages: installed, current, ru, release: fw.tag, sources,
|
||||
latest: mine?.version ?? null, status: st,
|
||||
update: cur == null || st == 'outdated',
|
||||
// An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic.
|
||||
gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version),
|
||||
pending,
|
||||
note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1))
|
||||
: pending ? _('The AmneziaWG update is installed and starts after a reboot.') : null };
|
||||
};
|
||||
|
||||
/**
|
||||
* Tunnels on a new kernel module: every AmneziaWG interface is brought down,
|
||||
* the module swapped and the interfaces brought up again. False when the old
|
||||
* module stays loaded: the tunnels come back on it (the tools talk to an
|
||||
* older module at its own netlink version) and the installed one starts
|
||||
* with the next boot, which caps() and Health then wait for.
|
||||
*/
|
||||
function reload_module(ctx) {
|
||||
let ifaces = [];
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
c.foreach('network', 'interface', (s) => {
|
||||
if (s.proto == 'amneziawg' && s.disabled != '1')
|
||||
push(ifaces, s['.name']);
|
||||
});
|
||||
let n = length(ifaces);
|
||||
ctx.phase(sprintf(N_(n, 'Reloading the kernel module (%d tunnel restarts)', 'Reloading the kernel module (%d tunnels restart)'), n));
|
||||
for (let i in ifaces) {
|
||||
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
|
||||
sh(`ifdown '${i}'`);
|
||||
}
|
||||
if (stat('/sys/module/amneziawg'))
|
||||
ctx.run('rmmod amneziawg');
|
||||
let swapped = !stat('/sys/module/amneziawg');
|
||||
if (swapped) {
|
||||
ctx.run('modprobe amneziawg');
|
||||
if (!stat('/sys/module/amneziawg'))
|
||||
die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)"));
|
||||
}
|
||||
for (let i in ifaces)
|
||||
sh(`ifup '${i}'`);
|
||||
return swapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* After packages changed: the module loaded, netifd knowing the protocol,
|
||||
* Dawnline set up again. was: the module loaded before (builds.module_now()).
|
||||
* Returns whether the module that runs is the installed one; false while the
|
||||
* old one stays loaded until the next boot.
|
||||
*/
|
||||
function settle(ctx, before, after, was) {
|
||||
let b = before['kmod-amneziawg'], a = after['kmod-amneziawg'];
|
||||
let fresh = true;
|
||||
// A new module package, one over a module loaded by hand, or an earlier
|
||||
// update that still waits for a boot (Reinstall tries again).
|
||||
if (a && (a != b || was.pending) && (b || was.core != null))
|
||||
fresh = reload_module(ctx);
|
||||
else if (a && !b) {
|
||||
ctx.phase(_('Loading the kernel module'));
|
||||
if (ctx.run('modprobe amneziawg').code != 0 && !stat('/sys/module/amneziawg'))
|
||||
die(_("AmneziaWG is installed, but its kernel module doesn't load on this firmware"));
|
||||
}
|
||||
// netifd reads its protocol handlers when it starts.
|
||||
if (index(ctx.run('ubus call network get_proto_handlers').out, '"amneziawg"') < 0) {
|
||||
ctx.phase(_('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)'));
|
||||
ctx.run('/etc/init.d/network restart');
|
||||
}
|
||||
ctx.after('apply');
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/**
|
||||
* The packages are in: settle them and record the build (source, tag) with
|
||||
* the module that ran before (was). An old module that stays loaded is no
|
||||
* failure: the job says so, and Health until the next boot.
|
||||
*/
|
||||
function finish(ctx, out, source, tag, was) {
|
||||
out.after = builds.installed();
|
||||
out.reloaded = settle(ctx, out.before, out.after, was);
|
||||
builds.record(source, tag, out.after, { prev_gen: was.gen, prev_core: was.core, reloaded: out.reloaded });
|
||||
if (!out.reloaded)
|
||||
ctx.log(_('The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot.'));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The first source that publishes every package for this firmware. */
|
||||
function pick(fw) {
|
||||
for (let id in builds.ORDER) {
|
||||
let r = null;
|
||||
try {
|
||||
r = gh.release(builds.SOURCES[id].repo, fw.tag);
|
||||
}
|
||||
catch (e) {}
|
||||
if (r && length(filter(builds.PKGS, (p) => index(r.assets, builds.asset(fw, p)) >= 0)) == length(builds.PKGS))
|
||||
return id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** arg: [auto|slava|grey][:ru] | rollback */
|
||||
export function install(ctx, arg) {
|
||||
let before = builds.installed();
|
||||
let was = builds.module_now(before['kmod-amneziawg']);
|
||||
let out = { from: before['amneziawg-tools'], to: null, before };
|
||||
let fw = builds.firmware();
|
||||
if (!fw)
|
||||
die(_('Cannot detect the firmware target'));
|
||||
if (arg == 'rollback') {
|
||||
let k = upd.kept('amneziawg');
|
||||
if (!k)
|
||||
die(_('No previous AmneziaWG build is kept on the router'));
|
||||
if (k.firmware && k.firmware != fw.postfix)
|
||||
die(_('The kept AmneziaWG build was made for another firmware: it would not load on this one'));
|
||||
out.to = k.version;
|
||||
out.build = k.build;
|
||||
ctx.versions(out.from, out.to);
|
||||
ctx.phase(sprintf(_('Rolling back to %s'), k.version));
|
||||
if (!pkg.install_files(k.files, true, ctx.log))
|
||||
die(_('Package installation failed'));
|
||||
upd.forget('amneziawg');
|
||||
return finish(ctx, out, k.build, fw.tag, was);
|
||||
}
|
||||
let parts = split(arg ?? '', ':');
|
||||
let id = parts[0] || 'auto';
|
||||
let want_ru = parts[1] == 'ru';
|
||||
if (id == 'auto') {
|
||||
id = pick(fw);
|
||||
if (!id)
|
||||
die(sprintf(_('No AmneziaWG build for OpenWrt %s (%s) yet'), substr(fw.tag, 1), fw.postfix));
|
||||
}
|
||||
let src = builds.SOURCES[id];
|
||||
if (!src)
|
||||
die(sprintf(_('Unknown AmneziaWG build %s'), id));
|
||||
out.build = id;
|
||||
let files = [];
|
||||
for (let p in [ ...builds.PKGS, ...(want_ru ? [ builds.RU ] : []) ]) {
|
||||
ctx.phase(sprintf(_('Downloading %s from %s'), p, src.repo));
|
||||
let f = fetch(ctx, fw, p, id, ctx.work);
|
||||
if (!f)
|
||||
die(sprintf(_('No %s build for OpenWrt %s in %s, or it could not be verified'), p, substr(fw.tag, 1), src.repo));
|
||||
push(files, f);
|
||||
}
|
||||
out.to = pkg.file_version(files[1]);
|
||||
ctx.versions(out.from, out.to);
|
||||
// The build being replaced, for Roll back: from another source that still publishes it.
|
||||
if (ctx.pol.keep && out.from && out.to != out.from) {
|
||||
let dir = `${ctx.work}/keep`;
|
||||
system(`mkdir -p '${dir}'`);
|
||||
let kept = null;
|
||||
for (let sid in builds.ORDER) {
|
||||
if (sid == id || kept)
|
||||
continue;
|
||||
let f = fetch(ctx, fw, 'amneziawg-tools', sid, dir);
|
||||
if (f && pkg.file_version(f) == out.from)
|
||||
kept = sid;
|
||||
}
|
||||
if (kept) {
|
||||
ctx.phase(sprintf(_('Keeping AmneziaWG %s for rollback'), out.from));
|
||||
let keepf = filter(map(builds.PKGS, (p) => fetch(ctx, fw, p, kept, dir)), (x) => x);
|
||||
if (length(keepf) == length(builds.PKGS))
|
||||
upd.keep('amneziawg', out.from, keepf, kept, fw.postfix);
|
||||
}
|
||||
else
|
||||
ctx.log(_('Warning: the installed build is no longer published, nothing to keep for rollback'));
|
||||
}
|
||||
ctx.phase(_('Refreshing package lists'));
|
||||
pkg.refresh(ctx.log);
|
||||
ctx.phase(sprintf(_('Installing the %s build'), src.label));
|
||||
if (!pkg.install_files(files, true, ctx.log))
|
||||
die(_('Package installation failed'));
|
||||
if (!want_ru && pkg.version(builds.RU))
|
||||
pkg.remove([ builds.RU ], ctx.log);
|
||||
return finish(ctx, out, id, fw.tag, was);
|
||||
};
|
||||
@@ -0,0 +1,94 @@
|
||||
// Dawnline updater: the OpenWrt packages Dawnline adds — the home-like link
|
||||
// (ip-full, kmod-veth) and HTTPS plus certificates for the personal portal —
|
||||
// checked against and updated from the OpenWrt feeds.
|
||||
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
|
||||
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
import { _, N_ } from 'dawnline.i18n';
|
||||
|
||||
/** What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the stock system). */
|
||||
export const NAMES = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ];
|
||||
|
||||
// Packages released together with each of the above, updated as a set so OpenSSL never ends up
|
||||
// half old and half new.
|
||||
const FAMILY = [
|
||||
[ /^ip-full$/, /^ip-/ ],
|
||||
[ /^(libustream-openssl|openssl-util)$/, /^(libustream-openssl|libopenssl|openssl-util$)/ ],
|
||||
[ /^(acme|luci-app-acme$)/, /^acme/ ],
|
||||
];
|
||||
|
||||
function family(p) {
|
||||
for (let f in FAMILY)
|
||||
if (match(p, f[0]))
|
||||
return f[1];
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The packages to update for these names: each one plus its upgradable family. */
|
||||
function with_family(names, up) {
|
||||
let set = {};
|
||||
for (let n in names) {
|
||||
if (up[n])
|
||||
set[n] = true;
|
||||
let f = family(n);
|
||||
if (f)
|
||||
for (let u in keys(up))
|
||||
if (match(u, f))
|
||||
set[u] = true;
|
||||
}
|
||||
return sort(keys(set));
|
||||
}
|
||||
|
||||
/** refresh: update the package lists first (a check by hand or on schedule). */
|
||||
export function check(ctx, refresh) {
|
||||
if (refresh ?? true) {
|
||||
ctx.phase(_('Refreshing package lists'));
|
||||
pkg.refresh();
|
||||
}
|
||||
let up = pkg.upgradable();
|
||||
let res = {}, all = {};
|
||||
for (let p in NAMES) {
|
||||
let v = pkg.version(p);
|
||||
let set = v ? with_family([ p ], up) : [];
|
||||
res[p] = { installed: v, latest: v && up[p] ? up[p] : null, with: filter(set, (x) => x != p) };
|
||||
for (let x in set)
|
||||
all[x] = true;
|
||||
}
|
||||
let n = length(keys(all));
|
||||
ctx.log(n ? sprintf(N_(n, '%d package update in the feeds: %s', '%d package updates in the feeds: %s'), n, join(', ', sort(keys(all))))
|
||||
: _('System packages are up to date'));
|
||||
return { pkgs: res, updates: n, status: n ? 'outdated' : 'latest' };
|
||||
};
|
||||
|
||||
/** arg: name,name,… (only names Dawnline manages): missing ones are installed, present ones updated with their family. */
|
||||
export function install(ctx, arg) {
|
||||
let names = filter(split(arg ?? '', ','), (x) => x != '');
|
||||
for (let n in names)
|
||||
if (index(NAMES, n) < 0)
|
||||
die(sprintf(_('%s is not a package Dawnline manages'), n));
|
||||
if (!length(names))
|
||||
die(_('Nothing to install'));
|
||||
ctx.phase(_('Refreshing package lists'));
|
||||
pkg.refresh(ctx.log);
|
||||
let missing = filter(names, (n) => pkg.version(n) == null);
|
||||
let have = with_family(filter(names, (n) => pkg.version(n) != null), pkg.upgradable());
|
||||
if (length(have)) {
|
||||
ctx.phase(sprintf(_('Updating %s'), join(', ', have)));
|
||||
if (!pkg.upgrade(have, ctx.log))
|
||||
die(_('Update failed'));
|
||||
}
|
||||
if (length(missing)) {
|
||||
ctx.phase(sprintf(_('Installing %s'), join(', ', missing)));
|
||||
if (!pkg.add(missing, ctx.log))
|
||||
die(_('Installation failed'));
|
||||
}
|
||||
// The portal's HTTPS runs in uhttpd; a piece that just arrived lets the portal or the home-like link start.
|
||||
let touched = [ ...missing, ...have ];
|
||||
if (length(filter(missing, (n) => match(n, /^(openssl-util|libustream|ip-full|kmod-veth)/)))) {
|
||||
ctx.after('apply');
|
||||
ctx.after('uhttpd');
|
||||
}
|
||||
else if (length(filter(touched, (n) => match(n, /^(libustream|libopenssl)/))))
|
||||
ctx.after('uhttpd');
|
||||
return { updated: have, installed: missing, check: check(ctx, false) };
|
||||
};
|
||||
@@ -0,0 +1,233 @@
|
||||
// Dawnline — what the Components tab, the updater and the agent share: the
|
||||
// update policy (Settings → Updates), when an automatic run is due, the one
|
||||
// update job at a time (a kernel lock), the history for Activity, and the
|
||||
// versions kept for rollback. GitHub and the package manager live in
|
||||
// dawnline.github and dawnline.pkg.
|
||||
|
||||
import { open, stat } from 'fs';
|
||||
import { q, read_json, write_json, ensure_dir, RUN_DIR, DATA_DIR } from 'dawnline.util';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
export const JOB_FILE = `${RUN_DIR}/update-job.json`;
|
||||
export const CHECK_FILE = `${RUN_DIR}/update-check.json`;
|
||||
/** Held (flock) by the updater for the whole job: busy() and stale jobs come from it, not from pids. */
|
||||
export const LOCK_FILE = `${RUN_DIR}/update.lock`;
|
||||
/** Automatic runs: when the last check and the last scheduled install happened. */
|
||||
export const AUTO_FILE = `${DATA_DIR}/update-auto.json`;
|
||||
/** What happened: updates (by hand or automatic), failures, checks that found something. */
|
||||
export const HISTORY_FILE = `${DATA_DIR}/update-history.json`;
|
||||
/** The version each component had before its last update (Keep the previous version). */
|
||||
export const KEEP_DIR = `${DATA_DIR}/keep`;
|
||||
|
||||
export const INTERVALS = { '6h': 6 * 3600, '12h': 12 * 3600, '1d': 86400, '7d': 7 * 86400 };
|
||||
export const TARGETS = [ 'app', 'amneziawg', 'packages' ];
|
||||
|
||||
function on(v, dflt) {
|
||||
if (v == null || v == '')
|
||||
return dflt;
|
||||
return v == '1' || v == 'true' || v == 'on' || v == 'yes';
|
||||
}
|
||||
|
||||
/** The update policy from raw UCI settings (core.load puts it in m.settings.updates). */
|
||||
export function policy(s) {
|
||||
s ??= {};
|
||||
let t = type(s.update_targets) == 'array' ? s.update_targets : s.update_targets ? [ s.update_targets ] : null;
|
||||
let time_ok = match(s.update_time ?? '', /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/);
|
||||
return {
|
||||
check: on(s.update_check, true),
|
||||
interval: INTERVALS[s.update_interval] ? s.update_interval : '1d',
|
||||
auto: on(s.update_auto, true),
|
||||
mode: s.update_mode == 'immediate' ? 'immediate' : 'scheduled',
|
||||
time: time_ok ? s.update_time : '04:00',
|
||||
// AmneziaWG is left out by default: a new kernel module restarts every tunnel.
|
||||
targets: t ? filter(t, (x) => index(TARGETS, x) >= 0) : [ 'app', 'packages' ],
|
||||
keep: on(s.update_keep, false),
|
||||
mirrors: on(s.update_mirrors, true),
|
||||
};
|
||||
};
|
||||
|
||||
/* ---------- schedule ---------- */
|
||||
|
||||
/** The scheduled time on the day of `ts` (router local time), in seconds since the epoch. */
|
||||
function scheduled_on(pol, ts) {
|
||||
let t = localtime(ts);
|
||||
let hm = split(pol.time, ':');
|
||||
return ts - (t.hour * 3600 + t.min * 60 + t.sec) + int(hm[0]) * 3600 + int(hm[1]) * 60;
|
||||
}
|
||||
|
||||
function day_of(ts) {
|
||||
let t = localtime(ts);
|
||||
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
|
||||
}
|
||||
|
||||
/** The scheduled slot `now` is in (up to an hour after the set time, also across midnight), or null. */
|
||||
function slot(pol, now) {
|
||||
for (let at in [ scheduled_on(pol, now), scheduled_on(pol, now - 86400) ])
|
||||
if (now >= at && now - at < 3600)
|
||||
return at;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What an automatic run should do now: 'install' (the scheduled window, at
|
||||
* most an hour after the set time, once per slot), 'check' (the interval has
|
||||
* passed), or null.
|
||||
*/
|
||||
export function due(pol, st, now) {
|
||||
now ??= time();
|
||||
st ??= {};
|
||||
if (pol.auto && pol.mode == 'scheduled' && length(pol.targets)) {
|
||||
let at = slot(pol, now);
|
||||
if (at != null && st.install_day != day_of(at))
|
||||
return 'install';
|
||||
}
|
||||
if (pol.check && now - (st.check ?? 0) >= INTERVALS[pol.interval])
|
||||
return 'check';
|
||||
return null;
|
||||
};
|
||||
|
||||
export function auto_state() {
|
||||
return read_json(AUTO_FILE, {});
|
||||
};
|
||||
|
||||
export function auto_save(st) {
|
||||
ensure_dir(DATA_DIR);
|
||||
write_json(AUTO_FILE, st, 0o600);
|
||||
};
|
||||
|
||||
/** Record that the scheduled slot `now` is in has run (the slot's own day, not today's after midnight). */
|
||||
export function mark_day(pol, st, now) {
|
||||
now ??= time();
|
||||
st.install_day = day_of(slot(pol, now) ?? now);
|
||||
return st;
|
||||
};
|
||||
|
||||
/* ---------- one job at a time ---------- */
|
||||
|
||||
/**
|
||||
* Take the update lock without waiting: the open file (keep it for the whole
|
||||
* job; the kernel releases it when the process ends), or null when another
|
||||
* job holds it.
|
||||
*/
|
||||
export function try_lock() {
|
||||
ensure_dir(RUN_DIR);
|
||||
let f = open(LOCK_FILE, 'a');
|
||||
if (f && f.lock('xn'))
|
||||
return f;
|
||||
f?.close();
|
||||
return null;
|
||||
};
|
||||
|
||||
/** A job is running: someone holds the update lock. */
|
||||
export function busy() {
|
||||
let f = try_lock();
|
||||
if (!f)
|
||||
return true;
|
||||
f.close();
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* The last job; a "running" one whose worker is gone (the lock is free) reads
|
||||
* as failed. Its phases, log and error are in the language of whoever started
|
||||
* it (English for automatic runs); only the stopped-job error is made here.
|
||||
*/
|
||||
export function job() {
|
||||
let j = read_json(JOB_FILE, null);
|
||||
if (j?.state == 'running' && !busy()) {
|
||||
j.state = 'failed';
|
||||
j.error = _('The update stopped unexpectedly.');
|
||||
j.finished = j.finished ?? time();
|
||||
}
|
||||
return j;
|
||||
};
|
||||
|
||||
/* ---------- history (Components → Activity) ---------- */
|
||||
|
||||
export function history() {
|
||||
let h = read_json(HISTORY_FILE, []);
|
||||
return type(h) == 'array' ? h : [];
|
||||
};
|
||||
|
||||
/** Newest first, the last 30 kept on flash. */
|
||||
export function history_add(e) {
|
||||
let h = history();
|
||||
unshift(h, { ts: time(), ...e });
|
||||
ensure_dir(DATA_DIR);
|
||||
write_json(HISTORY_FILE, slice(h, 0, 30), 0o600);
|
||||
};
|
||||
|
||||
/* ---------- Dawnline versions ---------- */
|
||||
|
||||
/**
|
||||
* Compare Dawnline release versions (0.3.2, v0.4.0-rc1): -1, 0 or 1. Numbers
|
||||
* compare as numbers; a pre-release (-rc1, -beta) comes before its release.
|
||||
*/
|
||||
export function version_cmp(a, b) {
|
||||
let parse = (v) => {
|
||||
let m = match(replace(`${v}`, /^v/, ''), /^([0-9.]+)([-~]([0-9A-Za-z.]+))?/);
|
||||
return m ? { nums: map(split(m[1], '.'), (x) => int(x)), pre: m[3] } : { nums: [ 0 ], pre: `${v}` };
|
||||
};
|
||||
let x = parse(a), y = parse(b);
|
||||
for (let i = 0; i < length(x.nums) || i < length(y.nums); i++) {
|
||||
let p = x.nums[i] ?? 0, r = y.nums[i] ?? 0;
|
||||
if (p != r)
|
||||
return p < r ? -1 : 1;
|
||||
}
|
||||
if (x.pre == y.pre)
|
||||
return 0;
|
||||
if (x.pre == null)
|
||||
return 1;
|
||||
if (y.pre == null)
|
||||
return -1;
|
||||
// rc1 < rc2 < rc10: compare the number runs as numbers.
|
||||
let px = match(x.pre, /^([^0-9]*)([0-9]*)/), py = match(y.pre, /^([^0-9]*)([0-9]*)/);
|
||||
if (px[1] != py[1])
|
||||
return px[1] < py[1] ? -1 : 1;
|
||||
return int(px[2] || 0) < int(py[2] || 0) ? -1 : int(px[2] || 0) > int(py[2] || 0) ? 1 : 0;
|
||||
};
|
||||
|
||||
/* ---------- kept previous versions ---------- */
|
||||
|
||||
/** { version, build?, firmware?, files: [paths], saved } of the kept version, or null. */
|
||||
export function kept(component) {
|
||||
let k = read_json(`${KEEP_DIR}/${component}/meta.json`, null);
|
||||
if (!k?.version || !length(k.files ?? []))
|
||||
return null;
|
||||
for (let f in k.files)
|
||||
if (!stat(f))
|
||||
return null;
|
||||
return k;
|
||||
};
|
||||
|
||||
/** What the Components tab shows; firmware: the current one (a kept AmneziaWG build is for one firmware only). */
|
||||
export function kept_all(firmware) {
|
||||
let out = {};
|
||||
for (let c in [ 'app', 'amneziawg' ]) {
|
||||
let k = kept(c);
|
||||
if (k && c == 'amneziawg' && k.firmware && firmware && k.firmware != firmware)
|
||||
k = null;
|
||||
out[c] = k ? { version: k.version, build: k.build ?? null, saved: k.saved ?? null } : null;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Replace the kept version of a component with these files (copied in). */
|
||||
export function keep(component, version, files, build, firmware) {
|
||||
let dir = `${KEEP_DIR}/${component}`;
|
||||
system(`rm -rf ${q(dir)}; mkdir -p ${q(dir)}; chmod 700 ${q(KEEP_DIR)} ${q(dir)}`);
|
||||
let saved = [];
|
||||
for (let f in files) {
|
||||
let to = `${dir}/${replace(f, /^.*\//, '')}`;
|
||||
if (system(`cp ${q(f)} ${q(to)}`) == 0)
|
||||
push(saved, to);
|
||||
}
|
||||
if (length(saved) == length(files))
|
||||
write_json(`${dir}/meta.json`, { version, build, firmware, files: saved, saved: time() }, 0o600);
|
||||
else
|
||||
system(`rm -rf ${q(dir)}`);
|
||||
};
|
||||
|
||||
export function forget(component) {
|
||||
system(`rm -rf ${q(KEEP_DIR + '/' + component)}`);
|
||||
};
|
||||
@@ -1,9 +1,11 @@
|
||||
// Dawnline — small helpers shared by the rpcd plugin, the CLI, the agent and
|
||||
// the portal CGI. Nothing in here touches configuration.
|
||||
// the portal CGI. Nothing in here loads or commits configuration (the uci
|
||||
// helpers work on a cursor the caller owns).
|
||||
|
||||
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
export const VERSION = '0.1.1';
|
||||
export const VERSION = '0.15.1';
|
||||
/** GitHub repository with Dawnline releases (updates and the installer). */
|
||||
export const REPO = 'tickcount/luci-app-dawnline';
|
||||
export const RUN_DIR = '/var/run/dawnline';
|
||||
@@ -91,15 +93,27 @@ export function read_json(path, fallback) {
|
||||
}
|
||||
};
|
||||
|
||||
/** Atomic write (temp file + rename). `mode` defaults to 0600. */
|
||||
/**
|
||||
* Atomic write (temp file + rename). `mode` defaults to 0600. A short write
|
||||
* (flash full) leaves the old file in place and returns false.
|
||||
*/
|
||||
export function write_file(path, data, mode) {
|
||||
let tmp = `${path}.tmp${rand_hex(3)}`;
|
||||
let f = open(tmp, 'w', mode ?? 0o600);
|
||||
if (!f)
|
||||
return false;
|
||||
f.write(data);
|
||||
f.close();
|
||||
return rename(tmp, path);
|
||||
data = `${data ?? ''}`;
|
||||
let n = length(data) ? f.write(data) : 0;
|
||||
let closed = f.close();
|
||||
if (n != length(data) || !closed) {
|
||||
unlink(tmp);
|
||||
return false;
|
||||
}
|
||||
if (!rename(tmp, path)) {
|
||||
unlink(tmp);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
export function write_json(path, data, mode) {
|
||||
@@ -126,10 +140,239 @@ export function unlock(f) {
|
||||
}
|
||||
};
|
||||
|
||||
// Locks this process holds through with_lock (flock does not nest: a second
|
||||
// open of the same lock file in one process would wait for itself).
|
||||
let held = {};
|
||||
|
||||
/**
|
||||
* Run fn() holding the named lock and return what it returns. Nested calls
|
||||
* for the same name in one process run fn() directly. Anything fn throws
|
||||
* releases the lock and is rethrown with the same message.
|
||||
*/
|
||||
export function with_lock(name, fn) {
|
||||
if (held[name])
|
||||
return fn();
|
||||
let l = lock(name);
|
||||
held[name] = true;
|
||||
try {
|
||||
let r = fn();
|
||||
delete held[name];
|
||||
unlock(l);
|
||||
return r;
|
||||
}
|
||||
catch (e) {
|
||||
delete held[name];
|
||||
unlock(l);
|
||||
die(e.message ?? `${e}`);
|
||||
}
|
||||
};
|
||||
|
||||
/* ---------- uci (on the caller's cursor) ---------- */
|
||||
|
||||
/** Set an option only when it differs (null, '' or [] delete it); true if something changed. */
|
||||
export function uci_put(c, conf, sec, opt, val) {
|
||||
let cur = c.get(conf, sec, opt);
|
||||
if (val == null || val == '' || (type(val) == 'array' && !length(val))) {
|
||||
if (cur != null) {
|
||||
c.delete(conf, sec, opt);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (type(val) == 'array') {
|
||||
if (type(cur) == 'array' && join('\n', cur) == join('\n', val))
|
||||
return false;
|
||||
}
|
||||
else if (cur == `${val}`)
|
||||
return false;
|
||||
c.set(conf, sec, opt, type(val) == 'array' ? val : `${val}`);
|
||||
return true;
|
||||
};
|
||||
|
||||
/** Make `sec` a section of type `stype` (recreated when its type differs); true if it changed. */
|
||||
export function uci_section(c, conf, sec, stype) {
|
||||
if (c.get(conf, sec) == stype)
|
||||
return false;
|
||||
if (c.get(conf, sec) != null)
|
||||
c.delete(conf, sec);
|
||||
c.set(conf, sec, stype);
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* After committing a config ourselves (and applying it), record its new
|
||||
* checksum so a later `reload_config` does not treat it as changed and
|
||||
* restart unrelated services that reload on any network change.
|
||||
*/
|
||||
export function ack_config(confs) {
|
||||
let md5f = '/var/run/config.md5';
|
||||
if (!stat(md5f))
|
||||
return;
|
||||
let lines = split(trim(readfile(md5f) ?? ''), '\n');
|
||||
for (let conf in confs) {
|
||||
let path = `/var/run/config.check/${conf}`;
|
||||
let sum = sh_out(`uci show ${q(conf)} | md5sum | cut -d' ' -f1`);
|
||||
if (!sum)
|
||||
continue;
|
||||
let found = false;
|
||||
for (let i = 0; i < length(lines); i++)
|
||||
if (substr(lines[i], -length(path) - 2) == ` ${path}`) {
|
||||
lines[i] = `${sum} ${path}`;
|
||||
found = true;
|
||||
}
|
||||
if (!found)
|
||||
push(lines, `${sum} ${path}`);
|
||||
}
|
||||
writefile(md5f, join('\n', lines) + '\n');
|
||||
};
|
||||
|
||||
/* ---------- service log ---------- */
|
||||
|
||||
/*
|
||||
* Tunnel and service starts and stops, watchdog repairs and errors: one JSON
|
||||
* object per line in tmpfs (appends from several processes stay whole), a
|
||||
* copy on flash that the agent refreshes hourly, and a line in syslog.
|
||||
* src: awg | dawnline | portal; level: info | up | down | repair | error.
|
||||
*/
|
||||
export const SLOG = `${RUN_DIR}/service.log`;
|
||||
export const SLOG_SAVED = `${DATA_DIR}/service.log`;
|
||||
const SLOG_KEEP = 300;
|
||||
|
||||
export function slog(src, level, msg, detail, who, extra) {
|
||||
let e = { ts: time(), src, level, msg };
|
||||
// The subject, shown first and bold: a server's name, "Personal portal", "Dawnline".
|
||||
if (who)
|
||||
e.who = `${who}`;
|
||||
// The admin's own changes: { by: 'admin', kind: 'server', note: 'port 50115' }
|
||||
// read "You <msg> <kind> <who> · <note>".
|
||||
for (let k in [ 'by', 'kind', 'note' ])
|
||||
if (extra?.[k])
|
||||
e[k] = `${extra[k]}`;
|
||||
if (detail)
|
||||
e.detail = substr(trim(`${detail}`), 0, 2000);
|
||||
ensure_dir(RUN_DIR);
|
||||
let f = open(SLOG, 'a', 0o600);
|
||||
if (f) {
|
||||
f.write(sprintf('%J\n', e));
|
||||
f.close();
|
||||
}
|
||||
let line = e.by == 'admin' ? join(' ', filter([ 'admin', msg, e.kind, who, e.note ? '· ' + e.note : null ], (x) => x)) : who ? `${who} ${msg}` : msg;
|
||||
system(`logger -t dawnline${level == 'error' ? ' -p user.err' : ''} ${q(line)}`);
|
||||
};
|
||||
|
||||
/** A change the admin made in LuCI, for the service log. */
|
||||
export function admin_log(src, msg, kind, who, note, detail) {
|
||||
slog(src, 'info', msg, detail, who, { by: 'admin', kind, note });
|
||||
};
|
||||
|
||||
/*
|
||||
* Why Dawnline itself is about to take a tunnel down, so the hotplug log can
|
||||
* tell that from a tunnel that stopped on its own. reason: settings | off |
|
||||
* removed | update. Kept for two minutes.
|
||||
*/
|
||||
const INTENT = `${RUN_DIR}/iface-intent.json`;
|
||||
|
||||
export function iface_intent(ifname, reason, name) {
|
||||
let all = read_json(INTENT, {});
|
||||
let now = time();
|
||||
for (let k, v in all)
|
||||
if (now - v.ts >= 120)
|
||||
delete all[k];
|
||||
all[ifname] = { reason, name, ts: now };
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(INTENT, all, 0o600);
|
||||
};
|
||||
|
||||
/**
|
||||
* The note for a stop of `ifname`, or null. netifd may report one stop more
|
||||
* than once (the interface, then its device): the note covers every report
|
||||
* within 15 s of the first, then it is spent.
|
||||
*/
|
||||
export function take_iface_intent(ifname) {
|
||||
let all = read_json(INTENT, {});
|
||||
let it = all[ifname];
|
||||
let now = time();
|
||||
if (!it || now - it.ts >= 120 || (it.used && now - it.used >= 15))
|
||||
return null;
|
||||
if (!it.used) {
|
||||
it.used = now;
|
||||
write_json(INTENT, all, 0o600);
|
||||
}
|
||||
return it;
|
||||
};
|
||||
|
||||
/** Newest first. */
|
||||
export function slog_read(limit) {
|
||||
let lines = split(readfile(SLOG) ?? readfile(SLOG_SAVED) ?? '', '\n');
|
||||
let out = [];
|
||||
for (let i = length(lines) - 1; i >= 0 && length(out) < (limit ?? SLOG_KEEP); i--) {
|
||||
if (lines[i] == '')
|
||||
continue;
|
||||
try {
|
||||
let e = json(lines[i]);
|
||||
if (type(e) == 'object' && e.ts)
|
||||
push(out, e);
|
||||
}
|
||||
catch (err) {}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Keep the last entries only, and save them to flash when asked. */
|
||||
export function slog_trim(save) {
|
||||
let lines = filter(split(readfile(SLOG) ?? '', '\n'), (l) => l != '');
|
||||
if (length(lines) > SLOG_KEEP + 50) {
|
||||
lines = slice(lines, -SLOG_KEEP);
|
||||
write_file(SLOG, join('\n', lines) + '\n');
|
||||
}
|
||||
if (save && length(lines) && stat(SLOG)?.mtime > (stat(SLOG_SAVED)?.mtime ?? 0)) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_file(SLOG_SAVED, join('\n', lines) + '\n');
|
||||
}
|
||||
};
|
||||
|
||||
/** Remove entries (all, or older than `days`); returns how many went. */
|
||||
export function slog_clear(days) {
|
||||
let keep = [], removed = 0, cut = days > 0 ? time() - days * 86400 : null;
|
||||
for (let l in split(readfile(SLOG) ?? readfile(SLOG_SAVED) ?? '', '\n')) {
|
||||
if (l == '')
|
||||
continue;
|
||||
let e = null;
|
||||
try {
|
||||
e = json(l);
|
||||
}
|
||||
catch (err) {}
|
||||
if (cut != null && e?.ts >= cut)
|
||||
push(keep, l);
|
||||
else
|
||||
removed++;
|
||||
}
|
||||
let data = length(keep) ? join('\n', keep) + '\n' : '';
|
||||
ensure_dir(RUN_DIR);
|
||||
write_file(SLOG, data);
|
||||
if (stat(SLOG_SAVED))
|
||||
write_file(SLOG_SAVED, data);
|
||||
return removed;
|
||||
};
|
||||
|
||||
/** After a reboot tmpfs is empty: continue the log saved on flash. */
|
||||
export function slog_restore() {
|
||||
if (!stat(SLOG) && stat(SLOG_SAVED)) {
|
||||
ensure_dir(RUN_DIR);
|
||||
write_file(SLOG, readfile(SLOG_SAVED) ?? '');
|
||||
}
|
||||
};
|
||||
|
||||
/* ---------- IPv4 ---------- */
|
||||
|
||||
// Module constants, compiled once: a regex literal is compiled again each
|
||||
// time it runs (rules/backend.md), and these run for every address and every
|
||||
// network in a list (status, the portal, the agent's checks).
|
||||
const IPV4 = /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/;
|
||||
const CIDR = /^([0-9.]+)(\/([0-9]+))?$/;
|
||||
|
||||
export function ip2int(ip) {
|
||||
let m = match(ip, /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/);
|
||||
let m = match(ip, IPV4);
|
||||
if (!m)
|
||||
return null;
|
||||
let n = 0;
|
||||
@@ -146,6 +389,35 @@ export function int2ip(n) {
|
||||
return sprintf('%d.%d.%d.%d', (n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255);
|
||||
};
|
||||
|
||||
/**
|
||||
* "a.b.c.d[/len]" with any prefix 0-32 (a bare address is a /32) →
|
||||
* { net, prefix, size, ip }; null for anything else. Routes, rules and
|
||||
* allowed networks use this; parse_cidr is the stricter one for subnets.
|
||||
*/
|
||||
export function cidr_any(s) {
|
||||
let m = match(s ?? '', CIDR);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
|
||||
if (ip == null || prefix > 32)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
return { net: ip - ip % size, prefix, size, ip };
|
||||
};
|
||||
|
||||
/** The first of `nets` (CIDR strings, any prefix) that holds `ip` (a string or an int), or null. */
|
||||
export function in_nets(ip, nets) {
|
||||
let n = type(ip) == 'int' ? ip : ip2int(ip);
|
||||
if (n == null)
|
||||
return null;
|
||||
for (let s in nets) {
|
||||
let c = cidr_any(s);
|
||||
if (c && n >= c.net && n < c.net + c.size)
|
||||
return s;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// Cloudflare's published ranges (https://www.cloudflare.com/ips/).
|
||||
const CF_V4 = [ '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18',
|
||||
'108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17',
|
||||
@@ -161,21 +433,15 @@ export function cloudflare_ip(a) {
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
for (let c in CF_V4) {
|
||||
let m = match(c, /^([0-9.]+)\/([0-9]+)$/);
|
||||
let size = 1 << (32 - +m[2]), net = ip2int(m[1]);
|
||||
if (n >= net && n < net + size)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return in_nets(n, CF_V4) != null;
|
||||
};
|
||||
|
||||
/** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */
|
||||
export function parse_cidr(cidr) {
|
||||
let m = match(cidr ?? '', /^([0-9.]+)\/([0-9]+)$/);
|
||||
if (!m)
|
||||
let m = match(cidr ?? '', CIDR);
|
||||
if (!m || m[3] == null)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = +m[2];
|
||||
let ip = ip2int(m[1]), prefix = +m[3];
|
||||
if (ip == null || prefix < 8 || prefix > 30)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
@@ -196,38 +462,261 @@ export function in_cidr(ip, c) {
|
||||
return n != null && n >= c.net && n < c.net + c.size;
|
||||
};
|
||||
|
||||
/* ---------- text ---------- */
|
||||
|
||||
/** Characters in a UTF-8 string (length() counts bytes: "Мама" is 8 of them). */
|
||||
export function ulength(s) {
|
||||
let n = 0;
|
||||
for (let i = 0; i < length(s); i++)
|
||||
if ((ord(s, i) & 0xc0) != 0x80)
|
||||
n++;
|
||||
return n;
|
||||
};
|
||||
|
||||
/** The first `n` characters of a UTF-8 string, never cut inside one. */
|
||||
export function ucut(s, n) {
|
||||
let i = 0, c = 0;
|
||||
while (i < length(s)) {
|
||||
if ((ord(s, i) & 0xc0) != 0x80) {
|
||||
if (c == n)
|
||||
break;
|
||||
c++;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return substr(s, 0, i);
|
||||
};
|
||||
|
||||
// Cyrillic (Russian, Ukrainian) to Latin: а-я by code point from U+0430, then
|
||||
// ё, і, ї, є, ґ; the rest of a string passes as it is.
|
||||
const CYR_A = 0x430;
|
||||
const CYRILLIC = [ 'a', 'b', 'v', 'g', 'd', 'e', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u',
|
||||
'f', 'kh', 'ts', 'ch', 'sh', 'shch', '', 'y', '', 'e', 'yu', 'ya' ];
|
||||
const CYRILLIC_MORE = { '1105': 'yo', '1110': 'i', '1111': 'yi', '1108': 'ye', '1169': 'g' };
|
||||
|
||||
/**
|
||||
* Cyrillic letters written in Latin ("Мама" → "mama", "Юля" → "yulya"):
|
||||
* ids, hostnames and file names are ASCII, and a person should recognise
|
||||
* their own in them. Other characters are left alone.
|
||||
*/
|
||||
export function translit(s) {
|
||||
let out = '', i = 0, n = length(s);
|
||||
while (i < n) {
|
||||
let b = ord(s, i);
|
||||
if (b < 0x80) {
|
||||
out += substr(s, i, 1);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
let cp = 0, len = 1;
|
||||
if ((b & 0xe0) == 0xc0 && i + 1 < n) {
|
||||
cp = ((b & 0x1f) << 6) | (ord(s, i + 1) & 0x3f);
|
||||
len = 2;
|
||||
}
|
||||
else if ((b & 0xf0) == 0xe0 && i + 2 < n) {
|
||||
cp = ((b & 0x0f) << 12) | ((ord(s, i + 1) & 0x3f) << 6) | (ord(s, i + 2) & 0x3f);
|
||||
len = 3;
|
||||
}
|
||||
else if ((b & 0xf8) == 0xf0 && i + 3 < n)
|
||||
len = 4;
|
||||
// Upper case to lower: А-Я, Ё, І, Ї, Є, Ґ.
|
||||
if (cp >= 0x410 && cp <= 0x42f)
|
||||
cp += 0x20;
|
||||
else if (cp == 0x401)
|
||||
cp = 0x451;
|
||||
else if (cp == 0x406)
|
||||
cp = 0x456;
|
||||
else if (cp == 0x407)
|
||||
cp = 0x457;
|
||||
else if (cp == 0x404)
|
||||
cp = 0x454;
|
||||
else if (cp == 0x490)
|
||||
cp = 0x491;
|
||||
let t = cp >= CYR_A && cp < CYR_A + length(CYRILLIC) ? CYRILLIC[cp - CYR_A] : CYRILLIC_MORE[`${cp}`];
|
||||
out += t != null ? t : substr(s, i, len);
|
||||
i += len;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/* ---------- validation ---------- */
|
||||
|
||||
export function valid_slug(s) {
|
||||
return type(s) == 'string' && match(s, /^[a-z0-9][a-z0-9-]{0,30}[a-z0-9]$|^[a-z0-9]$/) != null;
|
||||
};
|
||||
|
||||
/** A name people see: 1-48 characters (not bytes), none of < > " \ or control characters. */
|
||||
export function valid_name(s) {
|
||||
return type(s) == 'string' && length(trim(s)) > 0 && length(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
|
||||
return type(s) == 'string' && ulength(trim(s)) > 0 && ulength(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
|
||||
};
|
||||
|
||||
/** What valid_name wants, for the admin (in the admin's language). */
|
||||
export function name_rule() {
|
||||
return _('Enter a name: up to 48 characters, without < > " or \\.');
|
||||
};
|
||||
|
||||
// Character sets for checks written without a regex: ucode compiles a regex
|
||||
// literal each time it runs, and musl's regcomp takes milliseconds for a
|
||||
// bounded repeat (rules/backend.md). ltrim stops at a NUL byte, so a string
|
||||
// with one fails these checks (a regex looks only up to it).
|
||||
const ASCII_ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
const B64 = `${ASCII_ALNUM}+/`;
|
||||
|
||||
/**
|
||||
* The longest name a device takes, in characters: ordinary words fill a portal card's line about as far as its
|
||||
* status ("Return to save, Esc to cancel"), and fit the server list in the AmneziaVPN app. Names set before the rule stay as they are; it holds when a name is set.
|
||||
*/
|
||||
export const DEVICE_NAME_MAX = 20;
|
||||
// What a device's name may hold of ASCII: letters, digits, spaces and - _ . It goes into configurations, file
|
||||
// names and the AmneziaVPN key: nothing there to escape.
|
||||
const DEVICE_NAME_CHARS = `${ASCII_ALNUM} ._-`;
|
||||
// Past ASCII, letters of any language are welcome; these blocks are not: symbols, punctuation, arrows, maths,
|
||||
// emoji and invisibles (code point ranges, both ends in; web/src/shared/format.ts NAME_SYMBOLS is the same list,
|
||||
// and the page asks Unicode besides that a character is a letter or a digit).
|
||||
const NAME_SYMBOLS = [
|
||||
[ 0x80, 0xbf ], [ 0xd7, 0xd7 ], [ 0xf7, 0xf7 ], [ 0x2000, 0x2bff ], [ 0x3000, 0x303f ], [ 0xd800, 0xf8ff ],
|
||||
[ 0xfe00, 0xfe0f ], [ 0xfe30, 0xfe4f ], [ 0xfeff, 0xfeff ], [ 0xfff0, 0xffff ], [ 0x1f000, 0x1fbff ],
|
||||
[ 0xe0000, 0xe007f ]
|
||||
];
|
||||
|
||||
function name_symbol(cp) {
|
||||
for (let r in NAME_SYMBOLS)
|
||||
if (cp >= r[0] && cp <= r[1])
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's name (trimmed by the caller): 1-DEVICE_NAME_MAX characters, not blank, each one of
|
||||
* DEVICE_NAME_CHARS or past ASCII outside NAME_SYMBOLS. Read by code points: broken UTF-8, and an
|
||||
* ASCII character spelled long (0xC0 0xAF for "/"), are refused.
|
||||
*/
|
||||
export function valid_device_name(s) {
|
||||
if (type(s) != 'string' || length(trim(s)) == 0 || ulength(s) > DEVICE_NAME_MAX)
|
||||
return false;
|
||||
let i = 0, n = length(s);
|
||||
while (i < n) {
|
||||
let b = ord(s, i), cp, len;
|
||||
if (b < 0x80) {
|
||||
if (index(DEVICE_NAME_CHARS, substr(s, i, 1)) < 0)
|
||||
return false;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if ((b & 0xe0) == 0xc0) {
|
||||
len = 2;
|
||||
cp = b & 0x1f;
|
||||
}
|
||||
else if ((b & 0xf0) == 0xe0) {
|
||||
len = 3;
|
||||
cp = b & 0x0f;
|
||||
}
|
||||
else if ((b & 0xf8) == 0xf0) {
|
||||
len = 4;
|
||||
cp = b & 0x07;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
if (i + len > n)
|
||||
return false;
|
||||
for (let k = 1; k < len; k++) {
|
||||
let c = ord(s, i + k);
|
||||
if ((c & 0xc0) != 0x80)
|
||||
return false;
|
||||
cp = (cp << 6) | (c & 0x3f);
|
||||
}
|
||||
if (cp < 0xc0 || cp > 0x10ffff || name_symbol(cp))
|
||||
return false;
|
||||
i += len;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
// 32 bytes are 43 base64 characters: the last holds four bits of the key and two zero bits.
|
||||
const KEY_LAST = 'AEIMQUYcgkosw048';
|
||||
|
||||
/**
|
||||
* A (Amnezia)WireGuard key: 32 bytes in base64, 43 characters and "=", the
|
||||
* same as /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/ without its 1.7 ms
|
||||
* compile on the WR3000P: the agent's watcher checks two keys per line of
|
||||
* `awg show <ifname> dump` every second. This takes about 0.03 ms.
|
||||
*/
|
||||
export function valid_key(s) {
|
||||
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
|
||||
return type(s) == 'string' && length(s) == 44 && substr(s, 43) == '=' &&
|
||||
index(KEY_LAST, substr(s, 42, 1)) >= 0 && ltrim(substr(s, 0, 42), B64) == '';
|
||||
};
|
||||
|
||||
/** An IPv6 address in its usual spelling (no zone, no brackets). */
|
||||
export function is_ip6(s) {
|
||||
return type(s) == 'string' && match(s, /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/) != null && match(s, /:::/) == null;
|
||||
};
|
||||
|
||||
const LABEL = `${ASCII_ALNUM}-`;
|
||||
|
||||
/**
|
||||
* Dot-separated labels of 1-63 letters, digits and dashes, none starting or
|
||||
* ending with a dash: the same as
|
||||
* /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/
|
||||
* without its 10 ms compile on the WR3000P.
|
||||
*/
|
||||
function host_name(s) {
|
||||
for (let l in split(s, '.'))
|
||||
if (length(l) < 1 || length(l) > 63 || ltrim(l, LABEL) != '' ||
|
||||
index(ASCII_ALNUM, substr(l, 0, 1)) < 0 || index(ASCII_ALNUM, substr(l, -1)) < 0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A host name or an IP address, as a public address or the portal's name may be given. */
|
||||
export function valid_host(s) {
|
||||
return type(s) == 'string' && length(s) <= 253 &&
|
||||
(match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null ||
|
||||
ip2int(s) != null || match(s, /^[0-9a-fA-F:]+$/) != null);
|
||||
return type(s) == 'string' && length(s) <= 253 && (host_name(s) || ip2int(s) != null || is_ip6(s));
|
||||
};
|
||||
|
||||
/** YYYY-MM-DD, and a day that exists (2026-02-30 does not). */
|
||||
export function valid_date(s) {
|
||||
return type(s) == 'string' && match(s, /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/) != null;
|
||||
let m = type(s) == 'string' ? match(s, /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/) : null;
|
||||
if (!m)
|
||||
return false;
|
||||
let l = localtime(timelocal({ year: +m[1], mon: +m[2], mday: +m[3], hour: 12, min: 0, sec: 0 }));
|
||||
return l.year == +m[1] && l.mon == +m[2] && l.mday == +m[3];
|
||||
};
|
||||
|
||||
/** Turn a display name into a portal slug candidate. */
|
||||
// Runs of other characters become one dash. Module constants: host_label and
|
||||
// tunnel_name run for every device of a status or a portal answer.
|
||||
const NOT_LC_ALNUM = /[^a-z0-9]+/g, NOT_ALNUM = /[^A-Za-z0-9]+/g;
|
||||
// Names Windows keeps for devices: no file may be called that, whatever the case.
|
||||
const WIN_DEVICES = [ 'con', 'prn', 'aux', 'nul', 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',
|
||||
'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9' ];
|
||||
|
||||
/** Turn a display name into a portal slug candidate ("Мама Таня" → "mama-tanya"). */
|
||||
export function slugify(s) {
|
||||
let out = lc(trim(`${s ?? ''}`));
|
||||
out = replace(out, /[^a-z0-9]+/g, '-');
|
||||
out = replace(out, /^-+|-+$/g, '');
|
||||
let out = lc(translit(trim(`${s ?? ''}`)));
|
||||
out = replace(out, NOT_LC_ALNUM, '-');
|
||||
out = trim(out, '-');
|
||||
return substr(out, 0, 32) || 'user';
|
||||
};
|
||||
|
||||
/**
|
||||
* A device's name as a DNS label ("Galaxy S24" → "galaxy-s24", "Телефон" →
|
||||
* "telefon"): at most 40 characters, "device" when nothing is left.
|
||||
*/
|
||||
export function host_label(s) {
|
||||
let l = replace(lc(translit(`${s ?? ''}`)), NOT_LC_ALNUM, '-');
|
||||
l = rtrim(substr(trim(l, '-'), 0, 40), '-');
|
||||
return l || 'device';
|
||||
};
|
||||
|
||||
/**
|
||||
* A server's name as a tunnel name ("Outline Home" → "Outline-Home"): the
|
||||
* AmneziaWG and WireGuard apps name the tunnel after the file, and Android and
|
||||
* wg-quick refuse anything but [a-zA-Z0-9_=+.-] up to 15 characters; Windows
|
||||
* refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left.
|
||||
*/
|
||||
export function tunnel_name(s) {
|
||||
let l = replace(translit(`${s ?? ''}`), NOT_ALNUM, '-');
|
||||
l = rtrim(substr(trim(l, '-'), 0, 15), '-');
|
||||
return l && index(WIN_DEVICES, lc(l)) < 0 ? l : 'dawnline';
|
||||
};
|
||||
|
||||
/* ---------- time ---------- */
|
||||
|
||||
/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */
|
||||
@@ -253,6 +742,16 @@ export function day_key(ts) {
|
||||
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
|
||||
};
|
||||
|
||||
/**
|
||||
* The day key `days` days before `ts` (default now). Counted from local noon,
|
||||
* so a 23- or 25-hour day around a DST change neither skips nor repeats a day.
|
||||
*/
|
||||
export function day_key_ago(days, ts) {
|
||||
let t = localtime(ts ?? time());
|
||||
let noon = timelocal({ year: t.year, mon: t.mon, mday: t.mday, hour: 12, min: 0, sec: 0 });
|
||||
return day_key(noon - (days ?? 0) * 86400);
|
||||
};
|
||||
|
||||
export function uniq(arr) {
|
||||
let seen = {}, out = [];
|
||||
for (let v in arr)
|
||||
@@ -274,3 +773,30 @@ export function remove(path) {
|
||||
export function now() {
|
||||
return time();
|
||||
};
|
||||
|
||||
const IFACE = `${ASCII_ALNUM}_.@-`;
|
||||
|
||||
/**
|
||||
* A netifd interface name (network.interface.<name>, a person's home network):
|
||||
* 1-32 letters, digits and _ . @ -, the same as /^[A-Za-z0-9_.@-]{1,32}$/
|
||||
* without its 3 ms compile on the WR3000P (iface_status runs several times for
|
||||
* the Overview's status, and in the agent's minute checks).
|
||||
*/
|
||||
export function valid_iface(s) {
|
||||
return type(s) == 'string' && length(s) >= 1 && length(s) <= 32 && ltrim(s, IFACE) == '';
|
||||
};
|
||||
|
||||
/** netifd's view of an interface (ubus network.interface.<name> status), or null. */
|
||||
export function iface_status(ifname) {
|
||||
if (!valid_iface(ifname))
|
||||
return null;
|
||||
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
|
||||
if (!s)
|
||||
return null;
|
||||
try {
|
||||
return json(s);
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -3,31 +3,71 @@
|
||||
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import { day_key, month_key } from 'dawnline.util';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import { day_key_ago, month_key } from 'dawnline.util';
|
||||
|
||||
/** Daily totals (rx+tx) for the last `n` days, oldest first. */
|
||||
/** Each day's [rx, tx] for the last `n` days, oldest first: the charts draw what came and what went apart. */
|
||||
export function spark(rec, n) {
|
||||
let out = [], ts = time();
|
||||
let out = [];
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
let v = rec?.days?.[day_key(ts - i * 86400)];
|
||||
push(out, v ? v[0] + v[1] : 0);
|
||||
let v = rec?.days?.[day_key_ago(i)];
|
||||
push(out, v ? [ v[0], v[1] ] : [ 0, 0 ]);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Each day's [rx, tx] from the 1st of this month to today, oldest first (the portal's month chart). */
|
||||
export function month_days(rec) {
|
||||
return spark(rec, +substr(day_key_ago(0), 8, 2));
|
||||
};
|
||||
|
||||
/** The device holds an older configuration than the one it would get now. */
|
||||
function config_stale(m, d) {
|
||||
m._issued ??= core.issued();
|
||||
m._issued ??= awg.issued();
|
||||
let was = m._issued[d.id];
|
||||
return was != null && was != core.config_fingerprint(m, d);
|
||||
return was != null && was != awg.config_fingerprint(m, d);
|
||||
}
|
||||
|
||||
/**
|
||||
* The device a page request came from (`devs`: one person's device views):
|
||||
* through the tunnel, by its tunnel address; outside it, the one online device
|
||||
* whose tunnel comes from the request's address. The apps route the VPN's own
|
||||
* address around their tunnel, and the portal shares it, so a device on the VPN
|
||||
* opens the page from where its tunnel comes from. Two such devices behind one
|
||||
* address (one NAT): neither.
|
||||
*/
|
||||
export function device_here(devs, peer) {
|
||||
peer = replace(peer ?? '', /^::ffff:/, '');
|
||||
if (!peer)
|
||||
return null;
|
||||
let near = [];
|
||||
for (let d in devs) {
|
||||
if (d.address == peer)
|
||||
return d.id;
|
||||
if (d.online && d.endpoint == peer)
|
||||
push(near, d.id);
|
||||
}
|
||||
return length(near) == 1 ? near[0] : null;
|
||||
};
|
||||
|
||||
export function device_view(m, d, usage, dmp) {
|
||||
let u = usage.devices?.[d.id];
|
||||
let peer = dmp.peers[d.public_key];
|
||||
let ts = time();
|
||||
let hs = peer?.handshake || u?.handshake || 0;
|
||||
// Set up again (Reconnect): a handshake from before it does not count.
|
||||
m._reconnect ??= awg.reconnects();
|
||||
let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]);
|
||||
let p = m.people[d.person];
|
||||
return {
|
||||
let srv = m.servers[p?.server];
|
||||
// The same label /tmp/hosts carries (core.device_labels), so what is shown resolves.
|
||||
let label = '';
|
||||
if (m.settings.hostnames && p) {
|
||||
m._labels ??= {};
|
||||
m._labels[p.id] ??= core.device_labels(m, p);
|
||||
label = m._labels[p.id][d.id] ?? 'device';
|
||||
}
|
||||
let online = hs > 0 && live.online(dmp, d.id, peer);
|
||||
let v = {
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
kind: d.kind,
|
||||
@@ -35,18 +75,34 @@ export function device_view(m, d, usage, dmp) {
|
||||
disabled: d.disabled,
|
||||
created: d.created,
|
||||
created_by: d.created_by,
|
||||
online: !!(peer && peer.handshake > 0 && ts - peer.handshake < live.ONLINE_WINDOW),
|
||||
online,
|
||||
handshake: hs,
|
||||
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
|
||||
active: !!peer,
|
||||
month: live.month(u),
|
||||
total: u?.total ?? [ 0, 0 ],
|
||||
spark: spark(u, 7),
|
||||
hostname: m.settings.hostnames && p ? `${replace(replace(lc(d.name), /[^a-z0-9]+/g, '-'), /^-+|-+$/g, '') || 'device'}.${p.id}.${m.settings.domain}` : '',
|
||||
hostname: label ? `${label}.${p.id}.${m.settings.domain}` : '',
|
||||
browser_key: d.private_key == '',
|
||||
// Its configuration changed since it was last shown or downloaded.
|
||||
config_stale: config_stale(m, d),
|
||||
// How it connects: its own local network outside the tunnel, its own MTU
|
||||
// and keep-alive (0 / null: the server's) and what its configuration carries.
|
||||
lan_bypass: d.lan_bypass,
|
||||
mtu: d.mtu,
|
||||
keepalive: d.keepalive,
|
||||
mtu_used: srv ? core.device_mtu(srv, d) : null,
|
||||
keepalive_used: srv ? core.device_keepalive(srv, d) : null,
|
||||
// Its link failing in a named way, as the agent's watcher shows it
|
||||
// (dawnline.link): { state, since }, or null.
|
||||
link: dmp.link?.[d.id] ?? null,
|
||||
// What its link does right now, for the set-up sheet (dawnline.link
|
||||
// setup_state): { state: 'trying' | 'flowing' | 'nodata', since }, or null.
|
||||
// Without the agent nobody tells data from a bare handshake: a session
|
||||
// that lives counts as data flowing, so the sheet still sees it arrive.
|
||||
setup: dmp.setup != null ? (dmp.setup[d.id] ?? null) : online ? { state: 'flowing', since: hs } : null,
|
||||
};
|
||||
return v;
|
||||
};
|
||||
|
||||
export function person_view(m, p, usage, dmp, states, opts) {
|
||||
@@ -85,12 +141,15 @@ export function person_view(m, p, usage, dmp, states, opts) {
|
||||
if (d.handshake > v.last_seen)
|
||||
v.last_seen = d.handshake;
|
||||
if (opts.admin) {
|
||||
v.code = p.code;
|
||||
v.link = core.portal_url(m, p);
|
||||
v.links = core.portal_urls(m, p);
|
||||
// The code and links themselves are person_links' (admins only): the
|
||||
// code opens the person's portal and their devices' configurations.
|
||||
v.has_link = core.portal_url(m, p) != null;
|
||||
v.note = p.note;
|
||||
v.services = p.services;
|
||||
v.home_nets = p.home_nets;
|
||||
v.circle = p.circle;
|
||||
v.created = p.created;
|
||||
v.code_set = p.code_set;
|
||||
}
|
||||
return v;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
// Dawnline — watchdog. The agent runs it every minute: it checks what keeps
|
||||
// people connected and repairs what it can, waiting longer after each repair
|
||||
// that did not help. What it finds goes to the service log (English, as
|
||||
// logged); its state to RUN_DIR for the Health page, whose chip names are put
|
||||
// in the admin's language when they are read (view()). A cron job
|
||||
// (libexec/dawnline/heartbeat) looks after the agent itself.
|
||||
|
||||
import { stat } from 'fs';
|
||||
import { _, L_ } from 'dawnline.i18n';
|
||||
import { sh_out, q, read_json, write_json, slog, slog_read, RUN_DIR } from 'dawnline.util';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as nft from 'dawnline.nft';
|
||||
import * as netifd from 'dawnline.netifd';
|
||||
import * as upd from 'dawnline.updates';
|
||||
|
||||
export const STATE = `${RUN_DIR}/watchdog.json`;
|
||||
/** The agent writes the time here on every tick. */
|
||||
export const BEAT = `${RUN_DIR}/agent.beat`;
|
||||
// Seconds before the next repair, by the number of repairs so far.
|
||||
const WAIT = [ 0, 120, 600, 1800, 3600 ];
|
||||
// Good minutes in a row before a repaired target's count of repairs is
|
||||
// forgotten: one good minute between two failures is still flapping.
|
||||
const SETTLED = 10;
|
||||
|
||||
/** Why a tunnel is down (AmneziaWG; kept here for older callers). */
|
||||
export function iface_errors(ifname) {
|
||||
return awg.iface_errors(ifname);
|
||||
};
|
||||
|
||||
function restart_services() {
|
||||
// procd keeps unchanged instances (the agent running this) and starts missing ones.
|
||||
system('/etc/init.d/dawnline start >/dev/null 2>&1');
|
||||
}
|
||||
|
||||
/**
|
||||
* What to look at: { id (= the Health check id), src, name (chip, stored in English: view()
|
||||
* shows names() by id), who (the log's subject), ok,
|
||||
* problem, back, detail?, repair: { what, run }? }. The log reads "<who> <problem> - <what>"; its
|
||||
* words are L_(): English in the log, translated where it is shown.
|
||||
*/
|
||||
function probes(m) {
|
||||
let out = [];
|
||||
// The tunnels check themselves: AmneziaWG (packages, kernel module, netifd) and each server's interface.
|
||||
let tunnels = awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) });
|
||||
push(out, ...tunnels);
|
||||
// A tunnel's interface edited outside Dawnline (LuCI, uci) keeps that until
|
||||
// the next apply: set up again with Dawnline's settings. Only while
|
||||
// AmneziaWG itself works (its target comes first, and is fixed first).
|
||||
if (filter(tunnels, (p) => p.id == 'awg')[0]?.ok)
|
||||
for (let id, diff in netifd.drift(m)) {
|
||||
let srv = m.servers[id];
|
||||
push(out, {
|
||||
id: `cfg_${id}`, src: 'awg', name: `${srv.name} · interface settings`, who: srv.name, ok: !length(diff),
|
||||
problem: sprintf(L_('interface %s was changed outside Dawnline'), srv.ifname),
|
||||
back: sprintf(L_("interface %s has Dawnline's settings again"), srv.ifname),
|
||||
// Option names only: their values hold the server's private key.
|
||||
detail: () => sprintf(L_('Changed: %s.'), join(', ', diff)),
|
||||
repair: { what: L_('setting it up again'), run: () => apply.apply() },
|
||||
});
|
||||
}
|
||||
if (length(m.servers))
|
||||
push(out, {
|
||||
id: 'nft', src: 'dawnline', name: 'Access rules', who: L_('Access rules'), ok: nft.present(),
|
||||
problem: L_('are missing'), back: L_('are loaded again'),
|
||||
repair: { what: L_('loading them again'), run: () => apply.apply() },
|
||||
});
|
||||
|
||||
if (length(filter(values(m.servers), (x) => x.private_key))) {
|
||||
let fw = apply.firewall_drift(m);
|
||||
push(out, {
|
||||
id: 'fw', src: 'dawnline', name: 'Firewall', who: L_('Firewall'), ok: fw == null,
|
||||
problem: fw == 'off' ? L_("isn't running on this router (fw4): tunnels and the portal are closed")
|
||||
: fw == 'changed' ? L_("rules for Dawnline were changed or removed") : L_("rules for Dawnline aren't loaded"),
|
||||
back: L_('rules for Dawnline are in place again'),
|
||||
// fw4 stopped on purpose is the admin's call: report it, do not start it.
|
||||
repair: fw == 'off' ? null : { what: L_('restoring them'), run: () => { apply.apply(); system('fw4 -q reload'); } },
|
||||
});
|
||||
}
|
||||
|
||||
let s = m.settings;
|
||||
if (s.portal_enabled && !length(health.needs().https) && !length(health.tcp_port_owners(s.portal_port)))
|
||||
push(out, {
|
||||
id: 'portal', src: 'portal', name: 'Portal', who: L_('Personal portal'), ok: health.tcp_listening(s.portal_port),
|
||||
problem: sprintf(L_("isn't answering on port %d"), s.portal_port), back: L_('answers again'),
|
||||
detail: () => sh_out("logread -l 400 2>/dev/null | grep 'uhttpd' | grep -iE 'error|fail|cert|key|bind|address' | tail -n 4"),
|
||||
repair: { what: L_('restarting it'), run: restart_services },
|
||||
});
|
||||
|
||||
// Only while a server is on: with all of them off it idles on loopback.
|
||||
if (stat(loop.RESOLVER.conf) && length(filter(values(m.servers), (x) => x.enabled && x.private_key)))
|
||||
push(out, {
|
||||
id: 'resolver', src: 'dawnline', name: 'Resolver', who: L_('DNS for Home-only devices'), ok: loop.resolver_running(),
|
||||
problem: L_("isn't running"), back: L_('runs again'),
|
||||
repair: { what: L_('restarting it'), run: restart_services },
|
||||
});
|
||||
|
||||
push(out, {
|
||||
id: 'rpc', src: 'dawnline', name: 'LuCI link', who: 'LuCI', ok: system('ubus list luci.dawnline >/dev/null 2>&1') == 0,
|
||||
problem: L_("can't reach Dawnline (luci.dawnline is missing in rpcd)"), back: L_('reaches Dawnline again'),
|
||||
detail: () => sh_out('logread -l 400 2>/dev/null | grep rpcd | tail -n 4'),
|
||||
// A reload keeps LuCI logins; a restart (second try) signs everyone out —
|
||||
// and after three it stops: restarting rpcd every hour for good would
|
||||
// sign every admin out for good.
|
||||
repair: { what: L_('reloading rpcd'), max: 3, run: (n) => system(n > 1 ? '/etc/init.d/rpcd restart >/dev/null 2>&1' : '/etc/init.d/rpcd reload >/dev/null 2>&1') },
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** One pass. With repairs off it only reports. */
|
||||
export function run(m) {
|
||||
let now = time();
|
||||
let fix = m.settings.watchdog;
|
||||
// An update is replacing packages or restarting tunnels: what looks broken
|
||||
// meanwhile is being worked on; repairs would only get in its way.
|
||||
let busy = upd.busy();
|
||||
let st = read_json(STATE, {});
|
||||
let t = type(st.targets) == 'object' ? st.targets : {};
|
||||
let repairs = filter(st.repairs ?? [], (r) => now - r.ts < 86400);
|
||||
let seen = {};
|
||||
for (let p in probes(m)) {
|
||||
seen[p.id] = true;
|
||||
let x = t[p.id] ??= { bad: 0, tries: 0, next: 0 };
|
||||
x.name = p.name;
|
||||
x.ok = p.ok;
|
||||
if (p.ok) {
|
||||
if (x.reported)
|
||||
slog(p.src, 'up', x.stuck ? sprintf(L_('%s · restored'), p.back)
|
||||
: x.tries ? sprintf(x.tries > 1 ? L_('%s (after %d repairs)') : L_('%s (after %d repair)'), p.back, x.tries) : p.back, null, p.who);
|
||||
x.bad = 0;
|
||||
x.next = 0;
|
||||
x.reported = false;
|
||||
x.stuck = false;
|
||||
// The repairs so far are forgotten only once it has stayed up a while:
|
||||
// a target that fails every other minute keeps its back-off.
|
||||
x.good = (x.good ?? 0) + 1;
|
||||
if (x.good >= SETTLED) {
|
||||
x.tries = 0;
|
||||
x.good = 0;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
x.good = 0;
|
||||
// One bad minute can be a restart in progress.
|
||||
if (++x.bad < 2)
|
||||
continue;
|
||||
if (busy)
|
||||
continue;
|
||||
if (p.repair?.max && x.tries >= p.repair.max && !x.reported) {
|
||||
slog(p.src, 'error', sprintf(L_("%s - not repaired again (%d repairs didn't help)"), p.problem, p.repair.max), p.detail?.(), p.who);
|
||||
x.reported = true;
|
||||
continue;
|
||||
}
|
||||
if (!fix || !p.repair || (p.repair.max && x.tries >= p.repair.max)) {
|
||||
if (!x.reported)
|
||||
slog(p.src, 'error', p.problem, p.detail?.(), p.who);
|
||||
x.reported = true;
|
||||
continue;
|
||||
}
|
||||
// Three repairs did not help: say so once, in red, and from then on keep
|
||||
// trying quietly until it works again (that is logged).
|
||||
if (x.tries >= 3 && !x.stuck && now - (x.last ?? 0) >= 50) {
|
||||
x.stuck = true;
|
||||
slog(p.src, 'error', sprintf(L_("%s - %d repairs didn't help"), p.problem, x.tries), p.detail?.(), p.who);
|
||||
}
|
||||
if (now < x.next)
|
||||
continue;
|
||||
x.tries++;
|
||||
x.last = now;
|
||||
x.next = now + WAIT[min(x.tries, length(WAIT) - 1)];
|
||||
x.reported = true;
|
||||
if (!x.stuck)
|
||||
slog(p.src, 'repair', sprintf(L_('%s - %s'), p.problem, p.repair.what), p.detail?.(), p.who);
|
||||
try {
|
||||
p.repair.run(x.tries);
|
||||
}
|
||||
catch (e) {
|
||||
if (!x.stuck)
|
||||
slog(p.src, 'error', sprintf(L_("couldn't be repaired: %s"), e.message), null, p.who);
|
||||
}
|
||||
if (!x.stuck)
|
||||
push(repairs, { ts: now, id: p.id, name: p.name });
|
||||
}
|
||||
for (let id in keys(t))
|
||||
if (!seen[id])
|
||||
delete t[id];
|
||||
write_json(STATE, { last: now, targets: t, repairs }, 0o644);
|
||||
};
|
||||
|
||||
/**
|
||||
* The chip names of probes() by target id, in the language of the call. The
|
||||
* others (AmneziaWG's, "Home · AmneziaWG") are names only and stay as stored.
|
||||
*/
|
||||
function names() {
|
||||
return {
|
||||
agent: _('Agent'), nft: _('Access rules'), fw: _('Firewall'), portal: _('Portal'),
|
||||
resolver: _('Resolver'), rpc: _('LuCI link'),
|
||||
};
|
||||
}
|
||||
|
||||
/** A target's chip name in the language of the call: names(), a server's interface settings, else as stored. */
|
||||
function chip_name(m, n, id, stored) {
|
||||
if (n[id])
|
||||
return n[id];
|
||||
let srv = substr(id, 0, 4) == 'cfg_' ? m.servers[substr(id, 4)] : null;
|
||||
return srv ? sprintf(_('%s · interface settings'), srv.name) : stored;
|
||||
}
|
||||
|
||||
/**
|
||||
* For the Health page: the watchdog's state and the newest log entries. Target
|
||||
* and repair names in the language of the call; the log as it was written.
|
||||
*/
|
||||
export function view(m) {
|
||||
let st = read_json(STATE, {});
|
||||
let beat = +(read_json(BEAT, 0) ?? 0);
|
||||
let n = names();
|
||||
// The agent itself: fine while it ticks (cron restarts it after 5 minutes without).
|
||||
let targets = [ { id: 'agent', name: n.agent, ok: beat > 0 && time() - beat < 180, tries: 0 } ];
|
||||
for (let id, x in (type(st.targets) == 'object' ? st.targets : {}))
|
||||
push(targets, { id, name: chip_name(m, n, id, x.name), ok: !!x.ok, tries: x.tries ?? 0 });
|
||||
return {
|
||||
watchdog: {
|
||||
enabled: m.settings.watchdog, last: st.last ?? null, beat: beat || null, now: time(),
|
||||
targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: chip_name(m, n, r.id, r.name) })),
|
||||
},
|
||||
log: slog_read(200),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
# Backend (ucode on the router)
|
||||
|
||||
Read with `code-standards.md`. Everything here runs on a small router (2 × Cortex-A53 on the reference Cudy WR3000P): cost is part of correctness.
|
||||
|
||||
## Layers
|
||||
|
||||
- `util`, `schema` (validation) → `core` (model, allocation) → `store` (the only writer of `/etc/config/dawnline`) → domain modules (`net`, `nft`, `fw`, `netifd`, `awg`, `loop`, `resolver`, `live`, `health`, `backup`, …) → `apply` (reconciliation) → entry points (`rpc/*`, `portal`, the `dawnline` CLI, the agent, the updater).
|
||||
- Read models for the UI live in `view`; RPC modules translate arguments and call down, they hold no business logic.
|
||||
- The updater is a thin dispatcher over `upd_app` / `upd_awg` / `upd_pkgs`, with GitHub in `github`, the package manager in `pkg`, policy/locks/history in `updates`.
|
||||
- Live state: the agent's watcher owns who is online (`live.PRESENCE`); readers ask `live.online()`, never re-derive it from handshake ages. Online means the WireGuard session lives (`live.online_window()`: 190 s, longer for a device with a long keep-alive): traffic silence is no signal, a phone asleep is silent too. A device's link trouble (trying, shared, dropped, unstable) is the watcher's too (`dawnline.link`, `live.LINK`).
|
||||
|
||||
## ucode
|
||||
|
||||
- `'use strict'` in entry points; modules `import { … } from 'fs'` / `'dawnline.x'`. Subdirectories map to dots (`dawnline.rpc.status` → `dawnline/rpc/status.uc`).
|
||||
- Exported functions end with `};` (the compiler requires it). No destructuring. Regexes are POSIX (no `(?:)`, `\s\S` classes, lazy quantifiers); anchor them.
|
||||
- Modules with `export` cannot be loaded with `require()`: imports are static and compiled on every start of the script.
|
||||
- Doc comments (`/** … */`) on every export: what it returns, including the null/empty case.
|
||||
- Shell out through one small helper per module (`run()`/`sh()`), with `2>&1` captured and the exit code checked.
|
||||
- Messages people read (`die()` texts, check titles and details, phases) go through `_()` / `N_()` of `dawnline.i18n`, inside functions, with `sprintf()` for values (`i18n.md`).
|
||||
- nft changes load as one script (`nft.load()`, a transaction); tables Dawnline owns are named `dawnline*` and rebuilt whole (`table X` + `delete table X` + the table).
|
||||
|
||||
## Cost on the router
|
||||
|
||||
- **The portal is CGI:** every request starts ucode and compiles the module graph, about 140 ms of CPU before any work (a full `state` answer about 180 ms). No periodic polling from the portal; one request per user action. A person's answers read only their server's tunnel (`live.dump(m, sid)`: one `awg` process, however many servers).
|
||||
- **rpcd keeps the admin backend loaded:** LuCI RPC calls are cheap, so the admin UI may poll small methods often (`rev`), and the heavy ones (`status`) only on change or rarely.
|
||||
- **Code on the agent's 1-second watcher stays in the low milliseconds:** one `awg show <ifname> dump` per Dawnline tunnel, never `all` (another AmneziaWG interface's peers are not Dawnline's; about 4 ms with process start, 1 ms to parse), the model cached by the config file's mtime/inode (`core.load()` is about 4 ms), files written only when something changed. Slow work (geo lookups, apply) runs only on a transition.
|
||||
- **A regex literal is compiled every time it runs:** ucode calls regcomp for `/…/` each time the expression is evaluated, and musl's regcomp grows with the pattern. Bounded repeats are copied out (`{42}` about 1.7 ms on the WR3000P, `[A-Za-z0-9_.@-]{1,32}` 3 ms, two `{0,61}` 10 ms), alternations and classes add up (`/^(PrivateKey|Jc|Jmin|Jmax) /` 0.11 ms, `/^[0-9]+$/` 0.02 ms); matching a compiled regex takes 0.01–0.1 ms. In a loop or on a hot path, hoist the regex into a module `const` (compiled once, when the module loads — every portal request pays that too) or check with `length`/`substr`/`ltrim` (`util.valid_key`, `valid_host`, `valid_iface`).
|
||||
- Measure before and after on the router (a loop of 20–200 calls, `/proc/self/stat` CPU ticks, system busy from `/proc/stat`) when adding anything periodic.
|
||||
|
||||
## Checks
|
||||
|
||||
- `scripts/lint-ucode.py` and `scripts/ucode-container.sh` (compiles and runs `tests/ucode` in the OpenWrt rootfs containers; `scripts/check-ucode.sh` compiles on the router instead) pass before any deploy; new directories and entry points are added to `lint-ucode.py` and `scripts/compile-ucode.sh`, and executables to the mode check in `.github/workflows/ci.yml`.
|
||||
- Pure functions get a case in `tests/ucode/<module>.test.uc`; what reads the clock takes an optional `ts` so a test can pass one.
|
||||