Compare commits

12 Commits
Author SHA1 Message Date
Aemeath 2388603322 Dawnline 0.16.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- The personal page loads faster and costs the router less: its script
  and styles come compressed, stay in the browser until the next update,
  and the icon comes with the page instead of a request of its own
- The page uses the system's own font (SF Pro on Apple devices, Segoe UI
  on Windows, Roboto on Android) instead of downloading one
- The top of the page shows the server's name alone, so it fits on a
  phone
- Text can be selected only where it is there to be copied (addresses,
  file names, the configuration), with the name field's own selection:
  a soft highlight with handles that glides after the pointer
- Sheets scroll without a scrollbar
- Red buttons (Remove) light up under the pointer, as the others do
- Demo: "Demo" and GitHub are one button; on a phone it floats at the
  bottom of the screen, and switching scenarios no longer makes the
  edge fades jump
2026-10-24 21:33:48 +03:00
Aemeath 750564ab7e Dawnline 0.15.1
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Dropdowns (the ⋯ menu, the language picker, the page's QR card) open
  on a softer spring: they grow in without the wobble at the end
- Renaming a device on its card: the hint under the name and a refusal
  take the status's place as whole words, and after a save the status
  comes back the same way
- Cancelling a rename started while the status was still changing puts
  back what it said, not a mix of its old and new letters
2026-10-22 18:01:01 +03:00
dependabot[bot] 3fadee87d3 Bump vitest from 3.2.4 to 5.0.5 in /web
Closes the open Dependabot alerts for vitest, @vitest/mocker and tinypool (dev dependencies only; tinypool is no longer pulled in).
2026-10-22 17:58:11 +03:00
Aemeath ba231e7187 Dawnline 0.15.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- The device menu (⋯) is an iOS-style menu on frosted glass: the copy
  actions show the address they copy, Rename, Reconnect and Remove sit
  under them, and one highlight glides from row to row
- The language picker shows flags; pick a language with a click, or
  press the pill and slide onto one. The flag and the code change in
  place
- The page's QR code opens as a small card under its button, with Copy
  link and Share
- All dropdowns look and behave the same: frosted glass, one open at a
  time, and a press outside, Escape or the button again closes them
- Setting a device up: when it can't finish connecting or connects but
  passes no data, the sheet keeps just the status and what it means.
  No data now says the router drops its traffic because the address
  doesn't match, and the device's card says "Connected, but no data"
  right away instead of "Connected"
- Setting a phone up from another device: Download and Copy for the
  connection sit on its row, next to the arrow
- On iPhone and iPad the caret shows as soon as a field is focused, the
  page no longer zooms on a pinch or a double tap, and sheets and their
  animations run smoother
- A press near the edge of a button or a card always counts, even as it
  shrinks under the pointer
- Animations settle without a jump at the end
- New green, orange and red
- The focus ring shows only while moving around with the keyboard
2026-10-22 04:02:54 +03:00
Aemeath a1915f070b Dawnline 0.14.1
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- The updater started without a command, with one it doesn't know, or
  with an install of nothing prints its usage and exits. It no longer
  counts that as a failed update: nothing goes into the service log,
  Activity or the update history, and Components shows no failed job.
  `updater --help` prints the same usage
2026-10-22 00:20:51 +03:00
Aemeath dc0f159447 Dawnline 0.14.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- A device is renamed where its name stands on its card: a click on the
  name, Return or Space on it, or Rename in the ⋯ menu turns it into a
  field with the name selected. Return saves, and the words shimmer until
  the router answers. Esc or a click elsewhere puts the old name back. The
  rename window is gone, and the page no longer redraws under a name being
  edited
- Device names take up to 20 characters: letters of any language, digits,
  spaces and - _ . The router refuses anything else when a device is added
  or renamed, so a name can't carry symbols into configurations, file
  names or the AmneziaVPN key. The portal and the admin turn a character
  like that away as it is typed: the field shakes, its outline goes red
  and a short line says why. Suggested names (a phone's model, "Phone 2")
  are stripped of such characters and cut to fit. Names set before this
  stay as they are
- LAN Bypass: Add a device, in the portal and in the admin, has a switch
  that keeps the device's own local network (printer, TV, NAS) reachable
  while it is connected. It is off by default and stays as chosen; the
  admin's device drawer shows it. With home and internet access the switch
  says which addresses still lead to the home network
- Health warns when a server's home network is on one of the subnets home
  routers come with (192.168.0.x, 192.168.1.x and others). People with
  home access who connect from a network on the same addresses reach your
  home instead of their own, LAN Bypass or not
- The router tells when a device can't connect properly. After the problem
  lasts three minutes, the portal card and the admin drawer name it:
  can't finish connecting (the network may block it), connected but no
  data (an outdated configuration, and the card offers Reconnect), on two
  devices at once, or a connection that keeps dropping. Activity lists
  these under Problems, one line per device per hour, and says when the
  device connects normally again
- The set-up sheet's connection line follows what the device does:
  waiting, can't finish, connected, or connected but no data. The sheet
  closes by itself only once data comes through. On the device itself and
  for a router, the steps regroup to what fixes the problem: "Set it up
  again" when the handshake never finishes, "Add the connection again"
  ("Import the configuration again" for a router) when no data comes
- Set-up in the portal: a QR code too long for a camera to read gives its
  place to a code that opens the set-up link (a LAN Bypass configuration
  or a long AmneziaVPN key can be that long). A TV, box or NAS added from
  a phone gets the steps for setting up from another device. Back from
  "Open on the device" keeps the kind, LAN Bypass and the name typed. The
  packet-size note under the kinds is gone
- The portal on phones keeps its place: nothing jumps when an access row
  opens or folds, a notice comes or goes, or Safari redraws the cards. A
  reload, or coming back from the VPN app, opens where the page was. Cards
  glide to their new height, and an animation interrupted half-way goes on
  from where it is instead of snapping. A double click no longer closes
  the sheet it just opened
- In the admin, a device's drawer has its own MTU and keep-alive (empty
  means the server's), each with a Change dialog. A change touches only
  that device's configuration and restarts nothing on the router. Opening
  the drawer no longer counts as handing out the configuration: "Update
  config" stays until the new configuration is shown as a QR code,
  downloaded or copied ("Show the new configuration"). New keys set the
  device up again, as the portal's Reconnect does
- "Speed now" on a server's Overview is live: one point a second over the
  last two minutes, all there as soon as the Overview opens. The agent
  keeps those two minutes in memory and writes them out only while someone
  is looking
- Disguise values that AmneziaWG refuses or crashes on are stopped before
  they reach the kernel. That covers overlapping H1-H4, Jmin above Jmax,
  broken I1-I5 tags, padding under 12 with header protection, and more.
  Import and restore refuse them. After a hand edit in uci, the server's
  tunnel stays down and Health and the service log say why and what to do.
  Errors are full sentences in the reader's language
- The header protection key no longer shows in the status that read-only
  users can see: the Server page says only that the key is set, and each
  device's configuration still has it. The server no longer turns off
  WireGuard's protection against handshake floods (devices keep
  DisableCookies). A device can't be added with a server's own key
- An AmneziaWG update whose kernel module can't be swapped (another
  AmneziaWG interface holds the old one) no longer fails. It is installed,
  the tunnels come back on the old module, and Health and Components say
  the update starts after a reboot. On apk firmware, an install that apk
  left at the old version counts as failed. A module installed by hand is
  recorded, so after a firmware upgrade Health can tell that it is gone
- Dawnline reads only its own tunnels, each one separately. Another
  AmneziaWG interface on the router no longer slows the agent's
  once-a-second check, has its keys read or breaks Dawnline's reads. A
  portal request reads only that person's server: one process however many
  servers there are
- Fewer false disconnects: a tunnel that netifd sets up again no longer
  logs everyone as leaving and coming back, and a device with a long
  keep-alive stays online between handshakes. One configuration on two
  devices isn't logged as roaming every few seconds, and new keys end the
  old session at once. A tunnel that is missing devices is synced within a
  minute, and traffic across a tunnel restart is no longer undercounted
- Renaming a server no longer restarts its tunnel. If a tunnel's interface
  is edited outside Dawnline (LuCI, uci), the watchdog sets it up again
  with Dawnline's settings and names only the changed options. The routing
  rules for "Internet like a home device" change one at a time, new ones
  first, so traffic never falls between them. Health and the Server page
  warn when the address's AAAA record isn't this router's, or the router
  has no public IPv6: devices that prefer IPv6 fail to connect
- The README screenshots come in English and Russian; the portal's are
  taken from its demo. The demo has a switch beside × in the set-up sheet
  to show each state of the connection line. In Russian, long labels in
  the admin's wide option buttons wrap under their icon. DESIGN.md
  describes the switch, renaming on the card, the shimmer, the shake and
  how the portal scrolls. New tests cover link states, the meter, access,
  Health, firewall rules, network settings and packages
2026-10-22 00:11:50 +03:00
Aemeath 58492be021 Dawnline 0.13.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- "Internet like a home device" starts off on new servers: sending the
  tunnel through the home network costs speed. Both server wizards (the
  first one and "Add server") have the switch, and on it says what it
  costs. Servers that have it on keep it
- With it off, Server → Access says what that means: DNS still goes
  through the router, its proxies and filters see the tunnel only once its
  interface is added to their source interfaces, and sites the router's
  DNS answers with proxy addresses won't open
- With it on, established connections skip the second pass through
  netfilter in Dawnline's network namespace (a software flowtable): about
  12% less router CPU per packet, and about a quarter more speed through a
  proxy on the router. Without kmod-nft-offload the old rules load and the
  service log says so
- Its address at home stays the same when it is turned off and on again;
  it moved down by one each time (.254, .253, .252)
- Less CPU for the same work: the background agent's once-a-second look at
  the tunnels, Status, Health and the portal no longer compile the same
  patterns again for each line, address and device. At idle the agent uses
  about a quarter of the CPU it did; a portal request 5-10 ms less
- On LuCI's Bootstrap themes the admin looks as it does on Outline: cards
  and menus a step above the page, icon tiles that keep their colour,
  Outline's status colours in dark mode. The choices in Settings → Logs &
  history and Updates are LuCI's own controls in every theme
- "Add from devices at home" keeps a device's name readable in a narrow
  window: its ports go under the name
- DESIGN.md describes the portal's look, components and motion, and the
  rules send portal work there first. lint-ucode no longer ends a function
  at a brace inside a template literal
2026-10-21 01:42:23 +03:00
Aemeath db9657c01c Dawnline 0.12.1
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Device cards on a computer keep "↓ 3.2 GB ↑ 557 MB" on one line, clear of
  the week's bars (0.12.0 let them run together in the two columns). A
  narrow card gets slightly smaller numbers and thinner bars, with the bars
  in the middle of the row; resizing the window, the card glides between
  its two shapes
- A device whose settings changed shows one big Reconnect button, the same
  as Connect on a device not set up yet, in place of its week and the
  orange Update pill. It opens the same question as Reconnect in the ⋯ menu
2026-10-20 21:54:42 +03:00
Aemeath fb73ac3a9f Dawnline 0.12.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- The portal's traffic charts show what came down and what went up apart.
  A device's last 7 days and "Data this month" draw each day both ways:
  downloads rise above a thin line, uploads hang below it, on one scale.
  Beside them "↓ 3.2 GB ↑ 557 MB" instead of one total; hover a day for
  its own, its date where "left" stands
- Charts answer the pointer between their bars too, in the portal and in
  the admin's daily charts (a device's week, a device card's 30 days, the
  last 30 days): the figures no longer blink back to the total
- The calendar under "Access until" plays its days in only when the row is
  opened, not again each time the page refreshes with it open
- On a phone the page comes in from the top down: "Your access" first,
  then the devices
- "Show key" on a router's set-up morphs to "Hide key" with its icon, and
  brings the keys themselves into focus (it blurred the field names)
2026-10-20 20:58:36 +03:00
Aemeath 2f2aaf6c34 Dawnline 0.11.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Russian translation. The admin pages, the LuCI menu and the router's
  messages (errors, Health checks, update steps, the service log) come in
  Russian with the new luci-i18n-dawnline-ru package, released beside the
  app. LuCI shows it when its language is Russian, or "auto" with a Russian
  browser
- The translation installs with install.sh when LuCI is in Russian (or with
  --lang ru), follows every Dawnline update and rollback, and can be added
  or removed in Components → Dawnline → Translation
- The portal speaks the visitor's language: it opens in the system's
  language and switches between English and Russian in place, from the
  language pill beside its QR code. It carries its own translation and needs
  no package
- Set-up steps quote the apps' own menus word for word, in Russian too:
  AmneziaVPN is "+ → Insert → Continue" (it has no "Add server"), and the
  Mac and Windows menus of WireGuard and AmneziaWG have their real names
- Questions in the portal (Reconnect, Remove) read from the left edge and
  close with Cancel, without ×
- Numbers, sizes and dates follow the page's language. A server that can't
  start says why in one sentence; event details and service log lines read
  as whole sentences
- README in Russian (README_ru.md). rules/i18n.md: how strings are written
  and translated; CI checks the catalogs (npm run i18n:check)
2026-10-20 19:33:52 +03:00
Aemeath caed976e63 Portal demo for Vercel
- The real portal over a router that lives in the page
  (web/src/portal/demo): "User" on "Dawnline Preview", ten scenarios
  (first visit, settings changed, out of data, outside the hours, paused,
  ended, plain HTTP, plain WireGuard, no free slots), devices kept per
  visitor in localStorage. Keys are random and the server's address never
  resolves: nothing is installed and nothing connects
- A "Demo" chip after the breadcrumb opens a drawer with the scenarios and
  Start over; a new device "connects" a few seconds after its settings
- A GitHub pill beside the page's QR knob; on a phone, where the names
  need the room, a GitHub button in the drawer instead
- npm run build:demo builds the static site into web/dist/demo;
  web/vercel.json deploys it with the portal's CSP and headers, and builds
  only commits on main that change web/
- README links to the live demo (dawnline-demo.vercel.app)
- Tests for the demo router (tests/demo.test.ts)
2026-10-19 23:08:06 +03:00
Aemeath 8e7c15ad56 README: fix the Development link; social preview image
- The Development heading's emoji carried a variation selector, which
  GitHub keeps in the heading's anchor, so the top link to #-development
  went nowhere
- docs/social-preview.png: the repository's social preview, in the
  screenshots' panel style
2026-10-19 21:19:16 +03:00
302 changed files with 44141 additions and 5696 deletions

No files matched your search

+15 -13
View File
@@ -1,8 +1,9 @@
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
# 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.
@@ -32,7 +33,7 @@ jobs:
version: ${{ steps.version.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
@@ -62,14 +63,14 @@ jobs:
- { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3@sha256:6d832008ddd1b8ec4edc84f5e6e0bf22a13ba2d6888083a8e69fa26d752c276f' }
steps:
- name: Checkout
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '22'
node-version: '26'
cache: npm
cache-dependency-path: web/package-lock.json
@@ -86,10 +87,11 @@ jobs:
run: scripts/build-packages.sh ${{ matrix.type }}
- name: Upload
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
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
@@ -103,7 +105,7 @@ jobs:
steps:
# The whole history and the tags: the notes list the commits since the previous tag.
- name: Checkout
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
fetch-depth: 0
@@ -114,7 +116,7 @@ jobs:
cat notes.md
- name: Download packages
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: package-*
path: release
@@ -123,11 +125,11 @@ 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@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
with:
name: Dawnline ${{ github.ref_name }}
tag_name: ${{ github.ref_name }}
+37 -11
View File
@@ -24,14 +24,14 @@ jobs:
working-directory: web
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '22'
node-version: '26'
cache: npm
cache-dependency-path: web/package-lock.json
@@ -51,21 +51,44 @@ jobs:
id: types
run: npm run --silent typecheck
# oxlint's correctness rules: what the types let through (a stray expression, a needless escape).
- name: Lint
id: lint
run: npm run --silent lint
# Exports nobody imports, files nobody reaches, dependencies used but not listed (or listed but unused).
- name: Unused code
id: knip
run: |
if ! npm run --silent knip; then
echo "::error::knip found unused code or a dependency problem: remove it, or drop the export when only its own file uses it."
exit 1
fi
# 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
# The bundles under package/ are not committed (build.yml builds them
# before packaging): a build must touch no tracked file and leave every
# output it writes ignored by .gitignore, so none ends up in a commit.
- name: Build bundles and check they stay out of git
id: build
run: |
npm run --silent build
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."
echo "::error::The build changed a tracked file under package/ or wrote one .gitignore does not cover."
exit 1
fi
@@ -79,6 +102,9 @@ jobs:
echo "|---|---|"
echo "| Formatting | ${{ steps.format.outcome }} |"
echo "| Types | ${{ steps.types.outcome }} |"
echo "| Lint | ${{ steps.lint.outcome }} |"
echo "| Unused code | ${{ steps.knip.outcome }} |"
echo "| Translations | ${{ steps.i18n.outcome }} |"
echo "| Tests | ${{ steps.tests.outcome }} |"
echo "| Bundles | ${{ steps.build.outcome }} |"
} >> "$GITHUB_STEP_SUMMARY"
@@ -88,7 +114,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
@@ -117,7 +143,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
@@ -164,7 +190,7 @@ jobs:
release: ['24.10', '25.12']
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+3
View File
@@ -2,3 +2,6 @@ node_modules/
dist/
.DS_Store
web/coverage/
# The web bundles: web/ builds them (npm run build), CI before packaging.
package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/
package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/
+6 -3
View File
@@ -9,13 +9,16 @@ Guidance for coding agents working in this repository (`tickcount/luci-app-dawnl
- `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/` — TypeScript sources of the admin UI (`src/admin`) and the portal (`src/portal`), shared code in `src/shared`; `npm run build` writes the bundles under `package/` (git-ignored: CI builds them before packaging). `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`.
@@ -24,7 +27,7 @@ This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its r
- `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 test`, `npm run build` — and commit the rebuilt bundles (CI fails on a changed or new file under `package/`).
- In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm run lint` (oxlint), `npm run knip` (unused exports and dependencies), `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 catalogs (the bundles stay out of git; CI fails when the build leaves a file under `package/` that `.gitignore` does not cover).
- `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`).
@@ -33,6 +36,6 @@ This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its r
- 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` and `sha256sums.txt`.
- 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).
+1493
View File
File diff suppressed because it is too large. Load diff
+35 -13
View File
@@ -18,7 +18,9 @@
<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) &nbsp;·&nbsp; [Features](#-features) &nbsp;·&nbsp; [How it works](#-how-it-works) &nbsp;·&nbsp; [Screenshots](#-a-closer-look) &nbsp;·&nbsp; [FAQ](#-faq) &nbsp;·&nbsp; [Development](#-development)
[**Quick start**](#-quick-start) &nbsp;·&nbsp; [**Live demo**](https://dawnline-demo.vercel.app) &nbsp;·&nbsp; [Features](#-features) &nbsp;·&nbsp; [How it works](#-how-it-works) &nbsp;·&nbsp; [Screenshots](#-a-closer-look) &nbsp;·&nbsp; [FAQ](#-faq) &nbsp;·&nbsp; [Development](#-development)
**English** &nbsp;·&nbsp; [Русский](README_ru.md)
</div>
@@ -31,9 +33,10 @@ computers** and connect with AmneziaVPN, AmneziaWG or WireGuard. You decide
**for how long, how much and when**.
<p align="center">
<img src="docs/screenshots/portal.png" alt="The personal portal: devices and access, and adding a phone in three steps" width="860">
<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.</sub>
<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?
@@ -106,7 +109,7 @@ follows a modern design.
<tr>
<td valign="top">
<h3>🏠 Internet like a home device</h3>
<p>People's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too.</p>
<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>
@@ -123,6 +126,13 @@ follows a modern design.
<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
@@ -186,7 +196,8 @@ 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 and checks that LuCI can reach it.
missing, then installs Dawnline (with its Russian translation when LuCI is in
Russian) and checks that LuCI can reach it.
> [!NOTE]
> Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
@@ -207,6 +218,7 @@ wget -O /tmp/dawnline-install.sh https://raw.githubusercontent.com/tickcount/luc
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
```
| Option | |
@@ -215,8 +227,9 @@ sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey
| `-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 → Updates**). `DAWNLINE_AWG` does the same |
| `--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>
@@ -247,9 +260,12 @@ opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # Open
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
```
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`).
</details>
**Upgrade** from <kbd>Dawnline</kbd> › <kbd>Updates</kbd>, or run the installer
**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
@@ -362,7 +378,7 @@ 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/
@@ -373,7 +389,9 @@ package/luci-app-dawnline/
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
```
@@ -382,19 +400,23 @@ 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, lint, unused code, 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/capture-screenshots.mjs --demo # README screenshots from a router, a demo cast in place of its people
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 are built, not committed (`npm run build` before
`scripts/build-packages.sh`); the catalogs are committed, and 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`.
---
+433
View File
@@ -0,0 +1,433 @@
<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>
[**Быстрый старт**](#-быстрый-старт) &nbsp;·&nbsp; [**Демо**](https://dawnline-demo.vercel.app) &nbsp;·&nbsp; [Возможности](#-возможности) &nbsp;·&nbsp; [Как это работает](#-как-это-работает) &nbsp;·&nbsp; [Скриншоты](#-как-это-выглядит) &nbsp;·&nbsp; [Вопросы](#-вопросы-и-ответы) &nbsp;·&nbsp; [Разработка](#-разработка)
[English](README.md) &nbsp;·&nbsp; **Русский**
</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
```
Бандлы не лежат в репозитории, они собираются (`npm run build` перед
`scripts/build-packages.sh`); каталоги лежат, и 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
+8 -4
View File
@@ -1,7 +1,7 @@
# Builds luci-app-dawnline with the OpenWrt SDK.
# docker build -f build/Dockerfile --build-arg SDK_IMAGE=itdoginfo/openwrt-sdk-ipk:24.10.6 .
# The web bundles (htdocs/.../app.js, portal assets) are built by npm first and
# committed; the SDK only packs files, so the package is the same on every arch.
# The web bundles (htdocs/.../app.js, portal assets) are built by npm first
# (not committed); the SDK only packs files, so the package is the same on every arch.
ARG SDK_IMAGE=itdoginfo/openwrt-sdk-ipk:24.10.6
FROM ${SDK_IMAGE}
@@ -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/ \;
Binary file not shown.

After

Width:  |  Height:  |  Size: 446 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 419 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 436 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 403 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 363 KiB

After

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 423 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 395 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 412 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 187 KiB

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 KiB

+144 -13
View File
@@ -9,7 +9,8 @@
# sh /tmp/dawnline-install.sh [options] [version]
#
# Installs AmneziaWG built for this firmware when it is missing, then the
# Dawnline package with its dependencies from the OpenWrt feeds. Settings and
# Dawnline package with its dependencies from the OpenWrt feeds, and the admin's
# translation when LuCI speaks that language (--lang). Settings and
# keys survive reinstalls and upgrades. A recovery snapshot of the configs it
# may touch is taken first and restored if anything fails. `--help` lists the
# options.
@@ -18,6 +19,8 @@ INSTALLER_VERSION="1.0.0"
REPO="${DAWNLINE_REPO:-tickcount/luci-app-dawnline}"
PKG_NAME="luci-app-dawnline"
AWG_PKGS="kmod-amneziawg amneziawg-tools luci-proto-amneziawg"
# The admin's translations a release has: luci-i18n-dawnline-<lang>.
I18N_LANGS="ru"
CONNECT_TIMEOUT=15
METADATA_TIMEOUT=60
@@ -43,6 +46,7 @@ VERBOSE=0
QUIET=0
TAG=""
AWG_SOURCE="${DAWNLINE_AWG:-auto}"
I18N_CHOICE="${DAWNLINE_LANG:-auto}"
LOG_READY=0
TMP_DIR=""
@@ -67,6 +71,11 @@ WAS_ENABLED=0
WAS_RUNNING=0
MODE="install"
I18N_LANG=""
I18N_PKG=""
I18N_ASSET=""
I18N_FILE=""
AWG_ACTION="keep"
AWG_CANDIDATES=""
AWG_REPO=""
@@ -175,12 +184,18 @@ Usage: sh install.sh [options] [version]
grey 2Grey/awg-openwrt
skip do not install it (add it later in Dawnline → Components)
--no-awg Same as --awg skip
--lang LANG The admin's translation (luci-i18n-dawnline-LANG):
auto when LuCI is set to that language or has its
LuCI translation installed (default)
ru Russian
none add none (an installed one is kept up to date)
--version Print the installer version
-h, --help Show this help
Environment:
DAWNLINE_REPO=owner/name GitHub repository with the releases ($REPO)
DAWNLINE_AWG=SOURCE Same as --awg (the option wins)
DAWNLINE_LANG=LANG Same as --lang (the option wins)
DAWNLINE_SNAPSHOT_KEEP=N Recovery snapshots to keep (default 3)
Log: $LOG_FILE
@@ -214,6 +229,17 @@ set_awg() {
esac
}
set_lang() {
for _l in auto none $I18N_LANGS; do
[ "$1" = "$_l" ] && {
I18N_CHOICE="$1"
return 0
}
done
err "Unknown language: $1 (auto, none or one of: $I18N_LANGS)"
return 1
}
parse_args() {
while [ "$#" -gt 0 ]; do
case "$1" in
@@ -240,6 +266,15 @@ parse_args() {
;;
--awg=*) set_awg "${1#*=}" || return 2 ;;
--no-awg) AWG_SOURCE="skip" ;;
--lang)
[ "$#" -gt 1 ] || {
err "--lang needs a language (auto, none or one of: $I18N_LANGS)"
return 2
}
shift
set_lang "$1" || return 2
;;
--lang=*) set_lang "${1#*=}" || return 2 ;;
--version)
printf 'dawnline-installer %s\n' "$INSTALLER_VERSION"
exit 0
@@ -268,6 +303,7 @@ parse_args() {
return 2
fi
set_awg "$AWG_SOURCE" || return 2
set_lang "$I18N_CHOICE" || return 2
return 0
}
@@ -895,6 +931,68 @@ resolve_release() {
fi
}
lang_name() {
case "$1" in
ru) printf 'Russian' ;;
*) printf '%s' "$1" ;;
esac
}
# LuCI's language, when Dawnline has a translation for it: its setting, or with
# "auto" (the browser's) a LuCI translation that is installed (base.<lang>.lmo).
luci_lang() {
_ll="$(uci -q get luci.main.lang)"
for _l in $I18N_LANGS; do
case "$_ll" in "$_l" | "$_l"[_-]*)
printf '%s' "$_l"
return 0
;;
esac
done
case "$_ll" in '' | auto) ;; *) return 0 ;; esac
for _l in $I18N_LANGS; do
[ -f "/usr/lib/lua/luci/i18n/base.$_l.lmo" ] && {
printf '%s' "$_l"
return 0
}
done
return 0
}
# The admin's translation: an installed one is kept (it must match the app's
# version), else --lang or LuCI's own language decides.
resolve_i18n() {
I18N_LANG=""
for _l in $I18N_LANGS; do
pkg_is_installed "luci-i18n-dawnline-$_l" && I18N_LANG="$_l"
done
if [ -z "$I18N_LANG" ]; then
case "$I18N_CHOICE" in
none) ;;
auto) I18N_LANG="$(luci_lang)" ;;
*) I18N_LANG="$I18N_CHOICE" ;;
esac
fi
[ -n "$I18N_LANG" ] || return 0
I18N_PKG="luci-i18n-dawnline-$I18N_LANG"
I18N_ASSET="$I18N_PKG-$VERSION.$EXT"
_rj="$TMP_DIR/release.json"
if [ -s "$_rj" ]; then
_size="$(jsonfilter -i "$_rj" -e "@.assets[@.name='$I18N_ASSET'].size" 2>/dev/null | head -n 1)"
if [ -z "$_size" ]; then
# Releases before the translations have none.
warn "Release $VERSION has no $(lang_name "$I18N_LANG") translation: Dawnline stays in English"
I18N_LANG=""
I18N_PKG=""
I18N_ASSET=""
return 0
fi
DOWNLOAD_BYTES=$((DOWNLOAD_BYTES + _size))
else
DOWNLOAD_BYTES=$((DOWNLOAD_BYTES + 262144))
fi
}
# AmneziaWG packages are built per firmware version and target by the
# awg-openwrt projects: <name>_v<release>_<arch>_<target>_<subtarget>.<ext>
awg_postfix() {
@@ -981,6 +1079,11 @@ print_plan() {
downgrade) msg " Dawnline: downgrade $WAS_VERSION → $VERSION (a backup is made first)" ;;
esac
msg " Package manager: $PKG_MANAGER ($ASSET)"
if [ -n "$I18N_PKG" ]; then
msg " Translation: $(lang_name "$I18N_LANG") ($I18N_PKG)"
else
msg " Translation: none (Russian: --lang ru)"
fi
case "$AWG_ACTION" in
keep) msg " AmneziaWG: keep the installed one" ;;
skip) msg " AmneziaWG: skip (install it later from Dawnline → Components)" ;;
@@ -1011,28 +1114,37 @@ confirm() {
# ---------- download phase ----------
download_dawnline() {
# download_release_file NAME: one file of the release into $TMP_DIR, verified.
download_release_file() {
_name="$1"
_sums="$TMP_DIR/sha256sums.txt"
ASSET_FILE="$TMP_DIR/$ASSET"
# The checksum: GitHub's own (API), else the release's sha256sums.txt straight from github.com.
_want="$(asset_digest "$TMP_DIR/release.json" "$ASSET")"
_want="$(asset_digest "$TMP_DIR/release.json" "$_name")"
if [ -z "$_want" ]; then
download "$ASSET_BASE/sha256sums.txt" "$_sums" sha256sums.txt || {
[ -s "$_sums" ] || download "$ASSET_BASE/sha256sums.txt" "$_sums" sha256sums.txt || {
err "Download failed: sha256sums.txt (does release $VERSION exist?)"
return 1
}
_want="$(awk -v f="$ASSET" '$2 == f || $2 == "*" f { print $1; exit }' "$_sums")"
_want="$(awk -v f="$_name" '$2 == f || $2 == "*" f { print $1; exit }' "$_sums")"
[ -n "$_want" ] || {
err "sha256sums.txt has no entry for $ASSET: not installing an unverified package"
err "sha256sums.txt has no entry for $_name: not installing an unverified package"
return 1
}
fi
download "$ASSET_BASE/$ASSET" "$ASSET_FILE" "$ASSET" "$_want" || {
err "Download failed: $ASSET"
download "$ASSET_BASE/$_name" "$TMP_DIR/$_name" "$_name" "$_want" || {
err "Download failed: $_name"
return 1
}
verify_archive "$ASSET_FILE" || return 1
ok "$ASSET verified (sha256, package format)"
verify_archive "$TMP_DIR/$_name" || return 1
ok "$_name verified (sha256, package format)"
}
download_dawnline() {
download_release_file "$ASSET" || return 1
ASSET_FILE="$TMP_DIR/$ASSET"
[ -n "$I18N_ASSET" ] || return 0
download_release_file "$I18N_ASSET" || return 1
I18N_FILE="$TMP_DIR/$I18N_ASSET"
}
download_awg() {
@@ -1156,11 +1268,16 @@ install_dawnline() {
_force=0
case "$MODE" in reinstall | downgrade) _force=1 ;; esac
if [ "$DRY_RUN" -eq 1 ]; then
dry "$MODE Dawnline $VERSION ($ASSET)"
dry "$MODE Dawnline $VERSION ($ASSET${I18N_ASSET:+, $I18N_ASSET})"
return 0
fi
msg "Installing Dawnline $VERSION"
pkg_install_files dawnline "$_force" "$ASSET_FILE"
# The translation in the same transaction: it depends on this very version.
if [ -n "$I18N_FILE" ]; then
pkg_install_files dawnline "$_force" "$ASSET_FILE" "$I18N_FILE"
else
pkg_install_files dawnline "$_force" "$ASSET_FILE"
fi
}
healthcheck() {
@@ -1201,6 +1318,9 @@ healthcheck() {
if [ "$_r" != true ]; then
warn "The Dawnline agent is not running yet (see Dawnline → Diagnostics)"
fi
if [ -n "$I18N_PKG" ] && [ "$(pkg_version "$I18N_PKG")" != "$VERSION" ]; then
warn "$I18N_PKG $VERSION is not installed: Dawnline shows in English"
fi
ok "Healthcheck passed: $PKG_NAME $VERSION, LuCI backend answers"
}
@@ -1215,6 +1335,15 @@ keep_service_intent() {
return 0
}
# LuCI reads a language's catalogs once per web server process: a new or
# replaced translation needs a fresh one.
reload_luci() {
[ "$DRY_RUN" -eq 0 ] && [ -n "$I18N_FILE" ] || return 0
msg "Restarting the web server so LuCI reads the translation"
/etc/init.d/uhttpd restart >/dev/null 2>&1 ||
warn "uhttpd did not restart: the translation shows after a reboot"
}
commit_transaction() {
TX_COMMITTED=1
TX_ACTIVE=0
@@ -1328,6 +1457,7 @@ main() {
select_release
resolve_release || fail "Could not resolve the Dawnline release"
resolve_i18n
resolve_awg || fail "AmneziaWG is not available for this firmware"
check_tmp_space || fail "Not enough free memory for the downloads"
print_plan
@@ -1348,6 +1478,7 @@ main() {
healthcheck || fail "The installed Dawnline did not pass the healthcheck"
keep_service_intent
commit_transaction
reload_luci
trap on_hup HUP
_took=$(($(date +%s 2>/dev/null || echo "$START_TS") - START_TS))
+4 -1
View File
@@ -6,9 +6,12 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.10.0
PKG_VERSION:=0.16.0
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
@@ -1,29 +0,0 @@
// Generated from dawnline/web — do not edit by hand.
'use strict';
'require baseclass';
'require dom';
'require poll';
'require rpc';
'require ui';
var vi=Object.create;var Po=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var wi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var ki=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var $i=(n,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of xi(e))!yi.call(n,a)&&a!==r&&Po(n,a,{get:()=>e[a],enumerable:!(o=bi(e,a))||o.enumerable});return n};var Ci=(n,e,r)=>(r=n!=null?vi(wi(n)):{},$i(e||!n||!n.__esModule?Po(r,"default",{value:n,enumerable:!0}):r,n));var Wo=ki((Uo,Go)=>{"use strict";var jo=(function(){var n=function(C,k){var y=236,w=17,b=C,H=r[k],f=null,g=0,M=null,T=[],z={},W=function(A,N){g=b*4+17,f=(function(S){for(var O=new Array(S),_=0;_<S;_+=1){O[_]=new Array(S);for(var j=0;j<S;j+=1)O[_][j]=null}return O})(g),q(0,0),q(g-7,0),q(0,g-7),V(),I(),de(A,N),b>=7&&Q(A),M==null&&(M=F(b,H,T)),ee(M,N)},q=function(A,N){for(var S=-1;S<=7;S+=1)if(!(A+S<=-1||g<=A+S))for(var O=-1;O<=7;O+=1)N+O<=-1||g<=N+O||(0<=S&&S<=6&&(O==0||O==6)||0<=O&&O<=6&&(S==0||S==6)||2<=S&&S<=4&&2<=O&&O<=4?f[A+S][N+O]=!0:f[A+S][N+O]=!1)},Z=function(){for(var A=0,N=0,S=0;S<8;S+=1){W(!0,S);var O=a.getLostPoint(z);(S==0||A>O)&&(A=O,N=S)}return N},I=function(){for(var A=8;A<g-8;A+=1)f[A][6]==null&&(f[A][6]=A%2==0);for(var N=8;N<g-8;N+=1)f[6][N]==null&&(f[6][N]=N%2==0)},V=function(){for(var A=a.getPatternPosition(b),N=0;N<A.length;N+=1)for(var S=0;S<A.length;S+=1){var O=A[N],_=A[S];if(f[O][_]==null)for(var j=-2;j<=2;j+=1)for(var Y=-2;Y<=2;Y+=1)j==-2||j==2||Y==-2||Y==2||j==0&&Y==0?f[O+j][_+Y]=!0:f[O+j][_+Y]=!1}},Q=function(A){for(var N=a.getBCHTypeNumber(b),S=0;S<18;S+=1){var O=!A&&(N>>S&1)==1;f[Math.floor(S/3)][S%3+g-8-3]=O}for(var S=0;S<18;S+=1){var O=!A&&(N>>S&1)==1;f[S%3+g-8-3][Math.floor(S/3)]=O}},de=function(A,N){for(var S=H<<3|N,O=a.getBCHTypeInfo(S),_=0;_<15;_+=1){var j=!A&&(O>>_&1)==1;_<6?f[_][8]=j:_<8?f[_+1][8]=j:f[g-15+_][8]=j}for(var _=0;_<15;_+=1){var j=!A&&(O>>_&1)==1;_<8?f[8][g-_-1]=j:_<9?f[8][15-_-1+1]=j:f[8][15-_-1]=j}f[g-8][8]=!A},ee=function(A,N){for(var S=-1,O=g-1,_=7,j=0,Y=a.getMaskFunction(N),J=g-1;J>0;J-=2)for(J==6&&(J-=1);;){for(var ue=0;ue<2;ue+=1)if(f[O][J-ue]==null){var xe=!1;j<A.length&&(xe=(A[j]>>>_&1)==1);var te=Y(O,J-ue);te&&(xe=!xe),f[O][J-ue]=xe,_-=1,_==-1&&(j+=1,_=7)}if(O+=S,O<0||g<=O){O-=S,S=-S;break}}},B=function(A,N){for(var S=0,O=0,_=0,j=new Array(N.length),Y=new Array(N.length),J=0;J<N.length;J+=1){var ue=N[J].dataCount,xe=N[J].totalCount-ue;O=Math.max(O,ue),_=Math.max(_,xe),j[J]=new Array(ue);for(var te=0;te<j[J].length;te+=1)j[J][te]=255&A.getBuffer()[te+S];S+=ue;var De=a.getErrorCorrectPolynomial(xe),Ae=s(j[J],De.getLength()-1),So=Ae.mod(De);Y[J]=new Array(De.getLength()-1);for(var te=0;te<Y[J].length;te+=1){var To=te+So.getLength()-Y[J].length;Y[J][te]=To>=0?So.getAt(To):0}}for(var _o=0,te=0;te<N.length;te+=1)_o+=N[te].totalCount;for(var Gn=new Array(_o),Qt=0,te=0;te<O;te+=1)for(var J=0;J<N.length;J+=1)te<j[J].length&&(Gn[Qt]=j[J][te],Qt+=1);for(var te=0;te<_;te+=1)for(var J=0;J<N.length;J+=1)te<Y[J].length&&(Gn[Qt]=Y[J][te],Qt+=1);return Gn},F=function(A,N,S){for(var O=l.getRSBlocks(A,N),_=d(),j=0;j<S.length;j+=1){var Y=S[j];_.put(Y.getMode(),4),_.put(Y.getLength(),a.getLengthInBits(Y.getMode(),A)),Y.write(_)}for(var J=0,j=0;j<O.length;j+=1)J+=O[j].dataCount;if(_.getLengthInBits()>J*8)throw"code length overflow. ("+_.getLengthInBits()+">"+J*8+")";for(_.getLengthInBits()+4<=J*8&&_.put(0,4);_.getLengthInBits()%8!=0;)_.putBit(!1);for(;!(_.getLengthInBits()>=J*8||(_.put(y,8),_.getLengthInBits()>=J*8));)_.put(w,8);return B(_,O)};z.addData=function(A,N){N=N||"Byte";var S=null;switch(N){case"Numeric":S=c(A);break;case"Alphanumeric":S=p(A);break;case"Byte":S=u(A);break;case"Kanji":S=x(A);break;default:throw"mode:"+N}T.push(S),M=null},z.isDark=function(A,N){if(A<0||g<=A||N<0||g<=N)throw A+","+N;return f[A][N]},z.getModuleCount=function(){return g},z.make=function(){if(b<1){for(var A=1;A<40;A++){for(var N=l.getRSBlocks(A,H),S=d(),O=0;O<T.length;O++){var _=T[O];S.put(_.getMode(),4),S.put(_.getLength(),a.getLengthInBits(_.getMode(),A)),_.write(S)}for(var j=0,O=0;O<N.length;O++)j+=N[O].dataCount;if(S.getLengthInBits()<=j*8)break}b=A}W(!1,Z())},z.createTableTag=function(A,N){A=A||2,N=typeof N>"u"?A*4:N;var S="";S+='<table style="',S+=" border-width: 0px; border-style: none;",S+=" border-collapse: collapse;",S+=" padding: 0px; margin: "+N+"px;",S+='">',S+="<tbody>";for(var O=0;O<z.getModuleCount();O+=1){S+="<tr>";for(var _=0;_<z.getModuleCount();_+=1)S+='<td style="',S+=" border-width: 0px; border-style: none;",S+=" border-collapse: collapse;",S+=" padding: 0px; margin: 0px;",S+=" width: "+A+"px;",S+=" height: "+A+"px;",S+=" background-color: ",S+=z.isDark(O,_)?"#000000":"#ffffff",S+=";",S+='"/>';S+="</tr>"}return S+="</tbody>",S+="</table>",S},z.createSvgTag=function(A,N,S,O){var _={};typeof arguments[0]=="object"&&(_=arguments[0],A=_.cellSize,N=_.margin,S=_.alt,O=_.title),A=A||2,N=typeof N>"u"?A*4:N,S=typeof S=="string"?{text:S}:S||{},S.Line truncated
`}return S%2&&A>0?Ae.substring(0,Ae.length-S-1)+Array(S+1).join("▀"):Ae.substring(0,Ae.length-1)};return z.createASCII=function(A,N){if(A=A||1,A<2)return pe(N);A-=1,N=typeof N>"u"?A*2:N;var S=z.getModuleCount()*A+N*2,O=N,_=S-N,j,Y,J,ue,xe=Array(A+1).join("██"),te=Array(A+1).join(" "),De="",Ae="";for(j=0;j<S;j+=1){for(J=Math.floor((j-O)/A),Ae="",Y=0;Y<S;Y+=1)ue=1,O<=Y&&Y<_&&O<=j&&j<_&&z.isDark(J,Math.floor((Y-O)/A))&&(ue=0),Ae+=ue?xe:te;for(J=0;J<A;J+=1)De+=Ae+`
`}return De.substring(0,De.length-1)},z.renderTo2dContext=function(A,N){N=N||2;for(var S=z.getModuleCount(),O=0;O<S;O++)for(var _=0;_<S;_++)A.fillStyle=z.isDark(O,_)?"black":"white",A.fillRect(O*N,_*N,N,N)},z};n.stringToBytesFuncs={default:function(C){for(var k=[],y=0;y<C.length;y+=1){var w=C.charCodeAt(y);k.push(w&255)}return k}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(C,k){var y=(function(){for(var b=m(C),H=function(){var I=b.read();if(I==-1)throw"eof";return I},f=0,g={};;){var M=b.read();if(M==-1)break;var T=H(),z=H(),W=H(),q=String.fromCharCode(M<<8|T),Z=z<<8|W;g[q]=Z,f+=1}if(f!=k)throw f+" != "+k;return g})(),w=63;return function(b){for(var H=[],f=0;f<b.length;f+=1){var g=b.charCodeAt(f);if(g<128)H.push(g);else{var M=y[b.charAt(f)];typeof M=="number"?(M&255)==M?H.push(M):(H.push(M>>>8),H.push(M&255)):H.push(w)}}return H}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={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},a=(function(){var C=[[],[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,y=7973,w=21522,b={},H=function(f){for(var g=0;f!=0;)g+=1,f>>>=1;return g};return b.getBCHTypeInfo=function(f){for(var g=f<<10;H(g)-H(k)>=0;)g^=k<<H(g)-H(k);return(f<<10|g)^w},b.getBCHTypeNumber=function(f){for(var g=f<<12;H(g)-H(y)>=0;)g^=y<<H(g)-H(y);return f<<12|g},b.getPatternPosition=function(f){return C[f-1]},b.getMaskFunction=function(f){switch(f){case o.PATTERN000:return function(g,M){return(g+M)%2==0};case o.PATTERN001:return function(g,M){return g%2==0};case o.PATTERN010:return function(g,M){return M%3==0};case o.PATTERN011:return function(g,M){return(g+M)%3==0};case o.PATTERN100:return function(g,M){return(Math.floor(g/2)+Math.floor(M/3))%2==0};case o.PATTERN101:return function(g,M){return g*M%2+g*M%3==0};case o.PATTERN110:return function(g,M){return(g*M%2+g*M%3)%2==0};case o.PATTERN111:return function(g,M){return(g*M%3+(g+M)%2)%2==0};default:throw"bad maskPattern:"+f}},b.getErrorCorrectPolynomial=function(f){for(var g=s([1],0),M=0;M<f;M+=1)g=g.multiply(s([1,i.gexp(M)],0));return g},b.getLengthInBits=function(f,g){if(1<=g&&g<10)switch(f){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:"+f}else if(g<27)switch(f){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:"+f}else if(g<41)switch(f){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:"+f}else throw"type:"+g},b.getLostPoint=function(f){for(var g=f.getModuleCount(),M=0,T=0;T<g;T+=1)for(var z=0;z<g;z+=1){for(var W=0,q=f.isDark(T,z),Z=-1;Z<=1;Z+=1)if(!(T+Z<0||g<=T+Z))for(var I=-1;I<=1;I+=1)z+I<0||g<=z+I||Z==0&&I==0||q==f.isDark(T+Z,z+I)&&(W+=1);W>5&&(M+=3+W-5)}for(var T=0;T<g-1;T+=1)for(var z=0;z<g-1;z+=1){var V=0;f.isDark(T,z)&&(V+=1),f.isDark(T+1,z)&&(V+=1),f.isDark(T,z+1)&&(V+=1),f.isDark(T+1,z+1)&&(V+=1),(V==0||V==4)&&(M+=3)}for(var T=0;T<g;T+=1)for(var z=0;z<g-6;z+=1)f.isDark(T,z)&&!f.isDark(T,z+1)&&f.isDark(T,z+2)&&f.isDark(T,z+3)&&f.isDark(T,z+4)&&!f.isDark(T,z+5)&&f.isDark(T,z+6)&&(M+=40);for(var z=0;z<g;z+=1)for(var T=0;T<g-6;T+=1)f.isDark(T,z)&&!f.isDark(T+1,z)&&f.isDark(T+2,z)&&f.isDark(T+3,z)&&f.isDark(T+4,z)&&!f.isDark(T+5,z)&&f.isDark(T+6,z)&&(M+=40);for(var Q=0,z=0;z<g;z+=1)for(var T=0;T<g;T+=1)f.isDark(T,z)&&(Q+=1);var de=Math.abs(100*Q/g/g-50)/5;return M+=de*10,M},b})(),i=(function(){for(var C=new Array(256),k=new Array(256),y=0;y<8;y+=1)C[y]=1<<y;for(var y=8;y<256;y+=1)C[y]=C[y-4]^C[y-5]^C[y-6]^C[y-8];for(var y=0;y<255;y+=1)k[C[y]]=y;var w={};return w.glog=function(b){if(b<1)throw"glog("+b+")";return k[b]},w.gexp=function(b){for(;b<0;)b+=255;for(;b>=256;)b-=255;return C[b]},w})();function s(C,k){if(typeof C.length>"u")throw C.length+"/"+k;var y=(function(){for(var b=0;b<C.length&&C[b]==0;)b+=1;for(var H=new Array(C.length-b+k),f=0;f<C.length-b;f+=1)H[f]=C[f+b];return H})(),w={};return w.getAt=function(b){return y[b]},w.getLength=function(){return y.length},w.multiply=function(b){for(var H=new Array(w.getLength()+b.getLength()-1),f=0;f<w.getLength();f+=1)for(var g=0;g<b.getLength();g+=1)H[f+g]^=i.gexp(i.glog(w.getAt(f))+i.glog(b.getAt(g)));return s(H,0)},w.mod=function(b){if(w.getLength() Line truncated
`)}function qi(n){let e=new Map(n.people.map(o=>[o.id,o.name])),r=new Map(n.people.flatMap(o=>o.devices.map(a=>[a.id,a.name])));return{people:e,devices:r}}function Fe(n,e,r,o="",a=[]){let i=qi(n),s=[...e.map(p=>({ts:p.ts,category:It(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Ne(p)??""})),...a.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
${p.detail}`:""}`,where:Bt[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${o?`-${o}`:""}-${l}.${r}`;if(r==="json"){Te(d,JSON.stringify(s,null,2),"application/json");return}Te(d,dr(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Ki=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],cr=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function et(n,e,r,o,a,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...Lt.map(d=>t("option",{value:d,selected:d===a?"selected":null},ut[d])),i?t("option",{value:"system",selected:a==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Ki.map(([d,c])=>t("option",{value:d},c)));oe(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[ie()," ",D("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await P.logsClear({...r,category:s.value,older_days:l.value})).removed}catch(c){U(be(c),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await P.serviceLogClear(l.value)).removed}catch(c){ae(),U(`${s.value==="system"?"":`Activity: ${cr(d).toLowerCase()}. `}The service log was not cleared: ${be(c)}`,"error",1e4),o();return}ae(),U(cr(d),"success",3e3),o()},"negative")])}function Mt(n,e,r,o){let a=n==="device"?`Clears ${r}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${r}'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.";oe(n==="all"?"Reset all traffic history?":`Reset traffic history for ${r}?`,[t("p",{class:"dl-muted"},a)],[ie()," ",D("Reset",async()=>{await G(()=>P.usageClear(n,e),"Traffic history reset")&&(ae(),o())},"negative")])}function ve(n,e,r){let o=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let a=!o.classList.contains("on");eo(o,a),r?.(a)}},t("i"));return o}function eo(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Pe=n=>n.classList.contains("on");function we(n,e,r={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let o=t("div",{class:`dl-seg${r.cls?` ${r.cls}`:""}`,role:"radiogroup","aria-label":r.label??null,"data-value":e}),a=()=>o.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===o.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)o.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==o.dataset.value&&(r.optimistic!==!1&&(o.dataset.value=i,a()),r.onChange?.(i))}},s));return a(),o}function qe(n,e,r,o={}){return t("button",{type:"button",...o,class:`dl-chipbtn${e?" on":""}${o.class?` ${o.class}`:""}`,"aria-pressed":e?"true":"false",click:r},n)}function hn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function le(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Vi={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Ji={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 Yi(n){let e={};for(let[r,o]of Object.entries(Ji))n[r]!=null&&n[r]!==""&&(e[o]=String(n[r]));return e}function Zi(n,e){let r=n.amnezia,o=r.obfuscation??{},a=d=>o[d]!=null&&o[d]!==""?String(o[d]):Vi[d],i=r.host.replace(/^\[(.*)\]$/,"$1"),s={H1:a("h1"),H2:a("h2"),H3:a("h3"),H4:a("h4"),I1:a("i1"),I2:a("i2"),I3:a("i3"),I4:a("i4"),I5:a("i5"),Jc:a("jc"),Jmin:a("jmin"),Jmax:a("jmax"),S1:a("s1"),S2:a("s2"),S3:a("s3"),S4:a("s4"),...Yi(o),allowed_ips:r.allowed_ips,client_ip:r.client_ip,client_priv_key:r.client_priv_key,client_pub_key:r.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(r.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return r.dns[0]&&(l.dns1=r.dns[0]),r.dns[1]&&(l.dns2=r.dns[1]),l}function Qi(n){let e="";for(let r=0;r<n.length;r+=32768)e+=String.fromCharCode(...n.subarray(r,r+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Xi(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let r=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(r).arrayBuffer()),a=new Uint8Array(4+o.length);return new DataView(a.buffer).setUint32(0,n.length,!1),a.set(o,4),a}catch{return null}}async function to(n,e,r=!0){let o=new TextEncoder().encode(JSON.stringify(Zi(n,e))),a=r?await Xi(o):null;return`vpn://${Qi(a??o)}`}var ur=[{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"}],Ot=n=>ur.find(e=>e.id===n),fn=n=>n.v3?"max":n.v2?"balanced":"off",jt=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,es={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},ts={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function pr(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(r=>t("i",{class:r<n?"on":""})))])}function gn(n,e,r,o,a=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,ur.map(l=>{let d=!l.needs||n[l.needs],c=l.id===e;return t("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,s(),r(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===o?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[pr(l.stealth,"Stealth"),pr(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},d?[v(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[v("alert"),t("span",{},(a?es:ts)[l.needs])])])}));return s(),i}function mr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var hr=[["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 ns(n){let e=c=>n[c]!=null&&n[c]!=="",r=hr.filter(([c])=>e(c));if(!r.length)return null;let o=(c,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},c==="header_protection_key"?`${n[c].slice(0,6)}••••`:n[c])]),a=(c,p,u,x)=>{let $=hr.filter(([h])=>x.includes(h)&&e(h));return $.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},$.map(([h,m])=>o(h,m)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=r.map(([c,p])=>`${p} = ${n[c]}`).join(`
`),d=t("div",{class:"dl-pgrid"},[a("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),a("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),a("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),a("Signatures","globe",s,["i1","i2","i3","i4","i5"]),a("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"]),a("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 t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(r.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:c=>{c.preventDefault(),me(l,"Parameters copied")}},"Copy as config")]),d])}function fr(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let r=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!r)return document.createTextNode(n);let o=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},r[1])," ",o&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):r[2]])}function os(n){let e=!1,r=t("pre",{class:"dl-conf"}),o=()=>dom.content(r,n.conf.split(`
`).flatMap((s,l)=>l?[`
`,fr(s,e)]:[fr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[v(e?"x":"key"),e?"Hide key":"Show key"]),o()}},[v("key"),"Show key"]);o();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes`)]),D([v("download")," Download"],()=>Te(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),me(n.conf,"Configuration copied")}},[v("copy"),"Copy"])]),r])])}function no(n){let e=n.amnezia.obfuscation??{},r={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([o,a])=>a==null||a===""||a===(r[o]??"0"))}async function rs(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let r=await to(n,n.server),o={qr:()=>t("div",{class:"dl-qr-pane"},[an(n.conf),t("span",{class:"dl-sub"},no(n)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},r),D("Copy",()=>me(r,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>os(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(a,o[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function as(n,e,r,o){let a=Ot(r),s=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await se(o?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${r==="max"?" They need an app with AmneziaWG 3.1.":r==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}${n.st.servers.length===1&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,o?"Generate and apply":"Switch and apply",!0)&&await G(()=>P.serverObfuscation(e.id,r),o?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function is(n,e){let r=n.st,o=le(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=le(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=le(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=Ot(e.preset)?e.preset:void 0,l=s??fn(r.awg),d=D("",()=>as(n,e,l,l===s),"neutral"),c=()=>dom.content(d,l===s?[v("reset")," Generate new values"]:[`Switch to ${Ot(l).title}`]);c();let p=r.awg_state?.tools!==!1,u=[],x=ge("UDP port",o,()=>Rt(Number(o.value),u,`Opened on the WAN firewall automatically.${Number(o.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));P.serverPorts(e.id).then(m=>{u=m.udp_taken??[],x.refresh()}).catch(()=>{});let $=ge("MTU",a,()=>Zo(a.value,e.mtus)),h=ge("Keep-alive",i,()=>Qo(i.value));return Nt("",[mr("AmneziaWG",e.ifname),fe("globe","Listening","Where devices reach this core from the internet",[x]),fe("file","In every device configuration","Changing these marks devices “Update config” until they import again",[$,h]),fe("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[jt(e.preset)?ct("warn",[t("b",{},jt(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",gn(r.awg,l,m=>{l=m,c()},s,p),p&&!r.awg.v3?ct("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",ns(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ce("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ce("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ce("Server public key",t("span",{c Line truncated
`),"Log copied"))]),p,u]),[x],"wide"),h([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},a?"Checking…":"Working…")]);let E=r??null,R=r?.id,C,k=0,y=f=>{R!==f.id&&(R=f.id,e.onJob?.(f))};if(r)e.onJob?.(r);else try{let f=await P.updatesStatus().catch(()=>null);C=f?.job?.id,k=f?.now??0;let g=await P.updatesRun(n);g.job&&g.job.state==="running"&&g.job.id!==C&&(E=g.job,y(g.job))}catch(f){return $=[be(f)],p.textContent=$[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},be(f))])),h([m(!0)]),U(be(f),"error"),null}let w=null,b=0;for(;;){if(await ia(1e3),w=await P.updatesStatus().catch(()=>null),!w){if(++b>60)break;continue}b=0;let f=w.job;if(!f||!aa(f,R,C,k)){if(Date.now()-i>15e3)break;continue}if(y(f),E=f,f.log.length){$=f.log;let g=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=$.join(`
`),g&&(p.scrollTop=p.scrollHeight)}if(l.textContent=oa(f,e.version??""),!l.isConnected&&l.textContent&&s.after(l),c.textContent=na((f.finished??w.now)-f.started),f.state==="running"){d.hidden=!f.phase,d.textContent=f.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!E||E.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),h([m()]),e.onDone?.(w),E;if(E.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},E.error??"Operation failed"),a?"":". Nothing else was changed."])])),h([D("Copy log",()=>me($.join(`
`),"Log copied")),m(!0)]),U(`${Mn[o]??"Update"}: ${E.error??"failed"}`,"error"),e.onDone?.(w),E;if(d.className="dl-pill ok",d.textContent="Finished",a&&w){let f=ra(w,o);if(dom.content(u,t("div",{class:`dl-comp-status ${f.tone}`},[v(f.tone==="ok"?"check":f.tone==="warn"?"alert":"download"),t("span",{},f.text)])),U(f.text,f.tone==="warn"?"warning":"success"),e.onDone?.(w),f.update&&e.onUpdate){let g=w;h([m(),D(`Update to ${f.update}`,()=>e.onUpdate(g),"positive")])}else h([m()]),f.tone==="ok"&&setTimeout(()=>u.isConnected&&ae(),1200);return E}if(o==="app"&&E.to){let f=E.to,g=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},`Dawnline ${f} is installed. `),g])]));let M=()=>{ui.menu?.flushCache(),location.reload()};h([m(),D("Reload now",M,"positive")]),U(`Dawnline updated to ${f}`,"success",6e3);for(let T=1;T<=30;T++)if(g.textContent=`Waiting for the router to restart its services (${T} of 30)…`,await ia(1500),(await P.updatesStatus().catch(()=>null))?.version===f)return g.textContent="Services are back. Reloading…",setTimeout(M,800),E;return g.textContent="Services restarted. Reload the page to use the new version.",E}let H=o==="pkgs"?`Updated ${[...E.result?.pkgs?.updated??[],...E.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:o==="amneziawg"?`AmneziaWG${E.to?` ${E.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},H)])),h([m()]),U(H,"success"),e.onDone?.(w),E}var Ds={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function sa(n,e,r,o){return!await se(`Install ${e}?`,r,"Install")||(await Vt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>o?.(),4e3),!0)}function Tn(n){return sa("amneziawg:auto","AmneziaWG","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.",n)}async function Jt(n,e,r){return n==="awg"?Tn(r):e.length?sa(`pkgs:${e.join(",")}`,Ds[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,r):!0}async function la(n,e){if(n==="awg")return Tn(e);let r=await G(()=>P.updatesStatus());return r?Jt(n,r.needs?.[n]??[],e):!1}var As=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Hs={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function da(n,e,r){let o=n.id,a=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",c=!0,p=!0,u="all",x=!1,$=Xr(a,o,r),h=new Set,m="",E=()=>JSON.stringify([p,l,l?"":d,c,[...h].sort()]),R=()=>s.detected.lan||s.saved.lan||"",C=()=>(l?s.detected.wan||s.saved.wan:d)||"",k=()=>new Map(s.devices.map(I=>[I.name,I])),y=()=>{let I=k();return[...c&&R()?[R()]:[],...[...h].filter(Q=>Q!==R())].filter(Q=>Q!==C()).map(Q=>I.get(Q)??{name:Q,nets:[],missing:!0})},w=(I,V)=>{s=I,V&&(l=I.config.auto_wan,d=I.config.wan_device||I.detected.wan||I.saved.wan||"",c=I.config.auto_lan,p=I.config.lan_like,u=I.config.mesh??(I.config.device_mesh?"all":"off"),h=new Set(I.config.lan_devices),m=E()),q()},b=async I=>{let V=await P.interfaces(o).catch(Q=>(U(Q.message,"error"),null));V&&w(V,I)};function H(I){let V=c&&I.name===R(),Q=!!I.own||!!I.master||I.name===C()||V;return V||h.has(I.name)||!Q&&(I.nets.length>0||!!I.missing)}function f(I){let V=c&&I.name===R(),Q=I.name===C(),de=!V&&h.has(I.name),B=!(!!I.own||!!I.master||Q||V)&&(I.nets.length>0||de||!!I.missing),F=(de||V)&&!I.zone&&!I.missing,ne=I.missing?"Not present right now":I.own?"This server":I.master?`Port of ${I.master}`:Q?`Internet${I.zone?` · zone ${I.zone}`:""}`:I.nets.length?I.nets.join(", "):"No IPv4 network",pe=t("button",{type:"button",class:`dl-if${de?" sel":""}${V?" auto":""}${!B&&!de&&!V?" off":""}${F?" warn":""}`,"aria-pressed":de||V?"true":"false","aria-disabled":B?null:"true",click:()=>{B&&(h.has(I.name)?h.delete(I.name):h.add(I.name),q())}},[t("span",{class:"dl-if-ic"},v(Hs[I.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},I.name),t("span",{class:"dl-if-sub"},ne)]),V?t("span",{class:"dl-if-badge ok"},"Auto"):de?t("span",{class:"dl-if-check"},v("check")):""]);return he(pe,()=>[t("div",{class:"dl-tip-title"},I.name),t("div",{class:"dl-muted"},[I.logical?`Interface ${I.logical}`:"No netifd interface",I.zone?` · zone ${I.zone}`:" · no firewall zone"]),I.members.length?t("div",{class:"dl-muted"},`Ports: ${I.members.join(", ")}`):"",I.nets.length?t("div",{class:"dl-mono"},I.nets.join(", ")):"",F?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",I.master?t("div",{class:"dl-muted"},`Choose ${I.master} to include it.`):""]),pe}function g(){let I=s.like_home;return!p||!s.config.lan_li Line truncated
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(e.push(t("pre",{},i.join(`
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(s(),e.push(t("h5",{},r(c[2])))):p?(a.length&&s(),o||(o=t("ul",{}),e.push(o)),o.appendChild(t("li",{},r(p[1])))):d.trim()?(o&&(o=null),a.push(d.trim())):s()}return i&&e.push(t("pre",{},i.join(`
`))),s(),e}function Ma(n){let e=[],r=!1;for(let o of n.replace(/\r/g,"").split(`
`)){let a=/^#{1,6}\s+(.*)$/.exec(o);if(a){if(r=/^install\b/i.test(a[1].trim()),/^what.s new$/i.test(a[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(o)&&(r=!1);r||e.push(o)}return e.join(`
`).replace(/\n{3,}/g,`
`).trim()}async function Zt(n,e,r,o){let a=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";oe(r,[i,a],[D([v("copy")," Copy"],()=>me(s,"Release notes copied"))," ",ie("Close")],"wide");try{let l=await P.updatesNotes(n,e,o??"");s=Ma(l.body||"");let d=Ea(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ue(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),d?t("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",v("open")]):""]),dom.content(a,s.trim()?La(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(a,t("p",{class:"dl-muted"},be(l)))}}var Sa={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Co=n=>n?Ue(n):"";function Js(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function _a(n,e){let r=n.st,o=r.policy,a=r.kept?.app,i=e?.update&&e.tag?e.tag:r.version,s=x=>()=>Zt("app",x,`What’s new in Dawnline ${x.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Ys(n,e.tag,e.update?r.version:""):null,d=e?.tag??i,c=o.check&&r.auto?.check?r.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[o.interval]??24)*3600:0,p=(x,$)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},x),t("span",{class:"dl-comp-side-v"},$)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${r.repo}`,"_blank","noopener")},null,{label:`Reinstall ${r.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",r.version)},a?{label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back to Dawnline ${a.version}?`,`The copy kept on the router replaces ${r.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",r.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",r.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[r.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Co(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Co(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(x=>t("li",{},x))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",r.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",Zs(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[v("globe"),t("a",{href:`https://github.com/${r.repo}`,target:"_blank",rel:"noopener"},r.repo)]),p("Auto-update",[o.auto?Ee("ok","On"):Ee("","Off"),t("span",{class:"dl-muted"},o.auto?o.mode==="immediate"?"as soon as found":`${Sa[o.interval]==="weekly"?"weekly":"daily"} at ${o.time}`:o.check?`checks ${Sa[o.interval]}`:"checks off")]),p("Last check",r.check?[re(r.check.time,r.now),c>r.now?t("span",{class:"dl-faint"},`· next in ${xt(c-r.now)}`):""]:["Never"]),p("Rollback",a?[t("span",{class:"dl-mono"},a.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},o.keep?"Kept after the next update":"Off")])])])}function Ys(n,e,r){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let o=a=>a.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await P.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await P.updatesChanges(r,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Js(o(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Zs(n){let e=t("div",{class:"dl-params-body"}),r=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return r.addEventListener("toggle",()=>{n.versOpen=r.open,n.versOpen&&Nn(n,e)}),n.versOpen&&Nn(n,e),r}async function Nn(n,e){let r=le("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),o=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return U("Enter a release tag like 0.3.1","warning");Ta(n,p)};r.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),o(r.value))});let a=t("div",{class:"dl-comp-tag"},[r,D("Install",()=>o(r.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),Nn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(e,[a,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await P.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[a,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${be(p)}`),D("Try again",()=>Nn(n,e))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[a,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let c=n.st.version;dom.content(e,[a,...d.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Co(p.published)),p.prerelease?Ee("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},Le("file","What’s new",()=>Zt("app",p.tag,`What’s new in Dawnline ${u}`))),u===c?Ee("ok","Installed"):D("Install",()=>Ta(n,p.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function Ta(n,e){let r=e.replace(/^v/,"");r.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await se(`Install Dawnline ${r}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${r}`,n.st.version)}function Pa(n,e){let r=n.st,o=r.kept?.amneziawg,a=e?.sources??{},i=Object.keys(a),s=e?.current??null,l=s?a[s]:void 0,d=!!e?.ru,c=r.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",p)}),o&&u.push({label:`Roll back to ${o.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back AmneziaWG to ${o.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let x=[e?.release?{label:"What’s new",ic:"file",run:()=>Zt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"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((f,g,M)=>f!==null||g>0&&M[g-1]!==null),$=r.tunnels??[],h=$.length?`Switching restarts ${$.length===1?"the tunnel":`${$.length} tunnels`} for a few seconds: ${$.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",m=$.length>1?`${$.slice(0,-1).join(", ")} and ${$[$.length-1]}`:$[0],E=$.length?`Switching restarts ${m} for a few seconds.`:"Switching takes a few seconds.",R=async f=>{let g=a[f];await se(p?`Switch to AmneziaWG ${g.gen}?`:`Install AmneziaWG ${g.gen}?`,`The ${g.label} build, ${g.version}. ${h}${g.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${f}${d?":ru":""}`,p?`Switching to AmneziaWG ${g.gen}`:"Installing AmneziaWG",p??void 0)},C=f=>{let g=a[f],M=s===f&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},g.gen?`AmneziaWG ${g.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${g.label} · ${g.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},g.version??"none yet"),t("span",{class:"dl-comp-bact"},M?Ee("ok","Active"):g.version?D(p?"Switch":"Install",()=>R(f),p?"neutral":"positive",{disabled:n.busy}):Ee("","No build"))])},k=i.map(f=>a[f]?.newer?`${a[f].label} moves to ${a[f].newer.gen} with OpenWrt ${a[f].newer.tag.replace( Line truncated
`)}a.push(p),l+=c-1}let s=D([v("more")],()=>Ce(s,[{label:"Export CSV",icon:v("download"),run:()=>Fe(r,o,"csv",e.id)},{label:"Export JSON",icon:v("download"),run:()=>Fe(r,o,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:v("trash"),danger:!0,run:()=>et(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},o.length>10?`latest 10 of ${o.length}`:""),t("span",{class:"dl-spacer"}),s]),a.length?a:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var In=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[r,o,a]=await Promise.all([P.status(30),e?P.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?P.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:r,ev:o?.events??null,use:a}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let r=this.st.people.find(s=>s.id===this.id);if(!r)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=r;for(let s of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let o=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let a=new URLSearchParams(location.search),i=a.get("device")&&r.devices.find(s=>s.id===a.get("device"));return i?setTimeout(()=>Ge(this.p,i,this.deviceOpts()),50):a.get("add")&&setTimeout(()=>nt(this.p,this.deviceOpts()),50),this.poller=ot({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>o.isConnected,apply:(s,l)=>this.apply(s,l)}),o}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,r){this.take(e);let o=this.st.people.find(a=>a.id===this.id);if(!o){r||(location.href=_t(this.p?.server));return}this.p=o,this.paint(r),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,r){var i;this.poller?.claim();let o=await G(()=>P.personUpdate(this.p.id,e),r);if(!o)return!1;this.poller?.claim();let a=this.st.people.findIndex(s=>s.id===this.p.id);return(i=o.person).rate??(i.rate=this.p.rate),a>=0&&(this.st.people[a]=o.person),this.p=o.person,this.paint(),!0}get today(){return Ie(this.series.length?this.series:this.st.series)}get core(){return St(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,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 t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:_t(e.server)},this.st.servers.find(r=>r.id===e.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:_t(e.server)},"People"),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Se(this.parts.crumbs,this.crumbs(),e),Se(this.parts.head,ja(this),e),Se(this.parts.traffic,Ua(this),e),Se(this.parts.devices,Ga(this),e),Se(this.parts.limits,Ya(this),e),this.paintPlaces(e),Se(this.parts.activity,Qa(this),e)}paintPlaces(e=!1){let r=Za(this);r&&Se(this.parts.places,r,e&&!this.mapOpen)}};var sl={ok:"check",warn:"alert",error:"x",skip:"pause"},Bn=class{constructor(e,r,o,a){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=r,this.events=o,this.toLog=a,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(r,o)}async run(e){let r=e?await An(e):await P.health().catch(()=>null);r&&(this.take(r),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,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let r=e.filter(s=>s.status==="error").length,o=e.filter(s=>s.status==="warn").length;dom.content(this.summary,r?ct("error",`${r} problem${r>1?"s":""} need attention.`):o?ct("warn",`${o} warnLine truncated
`);function fi(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=El,n}function ht(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async o=>{let a=await e.render(o),i=document.createElement("div");return i.className="dl-root",i.append(fi(),a),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var C1=ht(Yt),E1=ht(mt),L1=ht(Yt),M1=ht(zn),S1=ht(In),T1=ht(Un),_1=ht(Rn);function gi(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var P1=gi(""),D1=gi("log");return baseclass.extend({ activity: D1, diagnostics: T1, health: P1, overview: C1, people: E1, person: S1, server: L1, settings: M1, updates: _1 });
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -13,6 +13,7 @@ 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';
@@ -139,7 +140,7 @@ function ifup_failed(ifname, who) {
return out;
});
if (r)
slog('awg', 'error', r.n > 1 ? `couldn't start · ${r.n} failed attempts in ${r.mins} min` : "couldn't start",
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);
}
@@ -308,16 +309,16 @@ try {
if (args[1] == 'ifup') {
ifup_ok(ifname);
let port = sh_out(`awg show ${q(ifname)} listen-port 2>/dev/null`);
slog('awg', 'up', port ? `started · accepting connections on port ${port}` : 'started', null, who);
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', 'restarting for the AmneziaWG update', null, who);
slog('awg', 'info', L_('restarting for the AmneziaWG update'), null, who);
else if (!it)
slog('awg', 'down', 'stopped unexpectedly', join('\n', filter([
"Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.",
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);
}
@@ -2,7 +2,11 @@
// 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). Every minute it:
// 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
@@ -26,6 +30,10 @@ 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;
@@ -54,6 +62,12 @@ 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(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 rev = +(presence.rev ?? 0);
@@ -122,6 +136,8 @@ 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;
@@ -165,22 +181,104 @@ function named(e) {
/* ---------- 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).
let last_hs = {};
// The model, read again only when the config file changes (the watcher runs every second).
let wm = null, wm_sig = null;
// (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.
let st = stat(CONFIG_FILE);
let sig = st ? `${st.mtime}/${st.inode}` : null;
// 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;
}
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++;
@@ -302,43 +400,89 @@ function place_of(ip) {
/*
* One look at the tunnels. Connects (a new handshake from a device that was
* away), disconnects (its session expired: no handshake for 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 from a complete read: a failed one says nothing about anyone.
* 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 d = awg.dump();
if (!d.ok)
return;
let m = watch_model();
let d = awg.dump(wm_ifnames);
let now = time();
let events = [], people = {}, ips = [];
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.
else
// 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] < live.ONLINE_WINDOW;
let on = last_hs[id] > 0 && now - last_hs[id] < (wm_windows[id] ?? live.ONLINE_WINDOW);
let was = last_online[id];
// 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);
}
// 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 (!on && was)
push(events, { type: 'disconnect', person: dev.person, device: id });
else if (on && ep && last_endpoint[id] && ep != last_endpoint[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]))
if (on != !!was || (ep && ep != last_endpoint[id] && !flapping))
people[dev.person] = true;
last_online[id] = on;
if (ep)
@@ -349,7 +493,29 @@ function watch() {
delete last_online[id];
delete last_endpoint[id];
delete last_hs[id];
delete last_key[id];
}
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));
@@ -423,7 +589,7 @@ function check_cert(m) {
let c = pc.portal_cert(m.settings);
let mt = stat(c.cert)?.mtime;
if (cert_mtime != null && mt != null && mt != cert_mtime) {
slog('portal', 'up', `certificate renewed · valid until ${cert_end(c.cert) ?? '?'}`, null, 'Personal portal');
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;
@@ -432,8 +598,9 @@ function check_cert(m) {
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) {
slog('portal', 'error', `certificate expires ${cert_end(c.cert) ?? 'within 7 days'}`,
'Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.', 'Personal portal');
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);
}
}
@@ -454,10 +621,13 @@ function check_wan(m) {
return;
let stuck = map(filter(values(m.servers), (x) => core.endpoint_host(m, x) == was), (x) => x.name);
if (length(stuck))
slog('dawnline', 'error', `public address changed · ${was} → ${ip}`,
`${join(', ', stuck)} still give${length(stuck) == 1 ? 's' : ''} devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.`, 'Router');
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', `public address changed · ${was} → ${ip}`, null, 'Router');
slog('dawnline', 'info', sprintf(L_('public address changed · %s → %s'), was, ip), null, L_('Router'));
}
let last_backup_day = null;
@@ -476,7 +646,7 @@ function nightly_backup() {
}
catch (e) {
// Tried again tomorrow; meanwhile the admin should know (a full flash, mostly).
slog('dawnline', 'error', `nightly backup failed: ${e.message}`, null, 'Backup');
slog('dawnline', 'error', sprintf(L_('nightly backup failed: %s'), e.message), null, L_('Backup'));
}
}
}
@@ -510,8 +680,9 @@ function check_usage_reset(m) {
* 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), or
* every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
* 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.
@@ -520,13 +691,32 @@ function sync_runtime(t) {
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())) {
apply.sync(t.m, usage);
last_peers = apply.sync(t.m, usage).peers ?? {};
last_sync = time();
}
conf_mtime = mt;
last_states = t.states;
}
/*
* 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
@@ -545,7 +735,7 @@ function check_network(t) {
return;
}
pending_net = null;
slog('dawnline', 'info', 'network changed — Dawnline set itself up again', null, 'Router');
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());
}
@@ -561,33 +751,36 @@ const STEPS = [
t.m = core.load();
t.pol = live.policy(t.m.settings.retention);
} },
{ who: 'Traffic', run: (t) => {
{ who: L_('Traffic'), run: (t) => {
t.reset = check_usage_reset(t.m);
live.collect(t.m, usage, live.dump(t.m));
t.dmp = live.dump(t.m);
live.collect(t.m, usage, t.dmp);
} },
{ who: 'Speed', quiet: true, run: (t) => record_rate(t.m) },
{ who: 'People', run: (t) => {
{ 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: 'Access rules', run: (t) => {
if (t.states)
sync_runtime(t);
{ 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: 'Activity', run: (t) => {
{ 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: 'Internet like a home device', run: (t) => apply.sync_loop(t.m, usage) },
{ who: 'Router', run: check_network },
{ who: 'Watchdog', run: (t) => watchdog.run(core.load()) },
{ who: 'Personal portal', run: (t) => check_cert(t.m) },
{ who: 'Router', quiet: true, run: (t) => check_wan(t.m) },
{ who: 'Backup', run: (t) => nightly_backup() },
{ 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) },
];
@@ -603,7 +796,7 @@ function step(i, s, fn) {
catch (e) {
system(`logger -t dawnline-agent ${q(`${s.who}: ${e.message}`)}`);
if (!s.quiet && step_err[i] != e.message)
slog('dawnline', 'error', `failed: ${e.message}`, e.stacktrace?.[0]?.context, s.who);
slog('dawnline', 'error', sprintf(L_('failed: %s'), e.message), e.stacktrace?.[0]?.context, s.who);
step_err[i] = e.message;
}
}
@@ -619,13 +812,13 @@ function tick() {
}
else if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
usage = live.load_usage();
let t = { m: null, pol: null, reset: false, events: [] };
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: 'Traffic' }, () => {
step('save', { who: L_('Traffic') }, () => {
live.save_usage(usage, persist);
if (persist) {
last_flush = time();
@@ -633,7 +826,7 @@ function tick() {
}
});
step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist));
step('events', { who: 'Activity' }, () => {
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);
@@ -647,6 +840,8 @@ function shutdown() {
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);
}
@@ -667,20 +862,23 @@ slog_restore();
let rolled = trim(readfile(`${RUN_DIR}/update-rolled-back`) ?? '');
unlink(`${RUN_DIR}/update-rolled-back`);
if (rolled)
slog('dawnline', 'error', `update to ${rolled} failed its check — rolled back to ${VERSION}`,
'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');
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', `updated · ${was} → ${VERSION}`, null, 'Dawnline');
slog('dawnline', 'up', sprintf(L_('updated · %s → %s'), was, VERSION), null, 'Dawnline');
else if (crashed)
slog('dawnline', 'repair', 'stopped unexpectedly — started again',
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', `restarted · version ${VERSION}`, null, 'Dawnline');
slog('dawnline', 'info', sprintf(L_('restarted · version %s'), VERSION), null, 'Dawnline');
else if (live.uptime() < 600)
slog('dawnline', 'info', `started with the router · version ${VERSION}`, null, 'Dawnline');
slog('dawnline', 'info', sprintf(L_('started with the router · version %s'), VERSION), null, 'Dawnline');
else
slog('dawnline', 'info', `started · version ${VERSION}`, null, 'Dawnline');
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();
@@ -690,14 +888,14 @@ timer = uloop.timer(1000, function() {
tick();
}
catch (e) {
slog('dawnline', 'error', `background check failed: ${e.message}`, e.stacktrace?.[0]?.context, 'Dawnline');
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: 'Connections' }, watch);
step('watch', { who: L_('Connections') }, watch);
watcher.set(WATCH);
});
@@ -12,6 +12,9 @@ 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
@@ -21,12 +21,37 @@ 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 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
`;
// 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 };
const WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages', packages: 'System packages' };
// 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 = {
id: `${time()}-${PID}`, action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null,
@@ -82,6 +107,24 @@ const ctx = {
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');
}
/** 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');
}
/* ---------- check results ---------- */
function checks_file() {
@@ -98,7 +141,10 @@ function save_check(res) {
write_json(upd.CHECK_FILE, c, 0o644);
}
/** What a check found, as short names ("Dawnline 0.3.3", "2 system packages"). */
/**
* 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)
@@ -106,19 +152,19 @@ function found_in(res) {
if (res.amneziawg?.update && res.amneziawg.installed)
push(found, `AmneziaWG ${res.amneziawg.latest}`);
if (res.packages?.updates)
push(found, `${res.packages.updates} system package${res.packages.updates == 1 ? '' : 's'}`);
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 ${WHO[name]}`);
phase(checking(name));
try {
res[name] = CHECKS[name](ctx);
}
catch (e) {
log(`Error: ${e.message}`);
log(sprintf(_('Error: %s'), e.message));
res[name] = { error: e.message, status: '' };
}
}
@@ -132,7 +178,7 @@ function note_found(res, st, auto) {
let sig = join(', ', found);
if (length(found) && sig != st.announced) {
if (auto)
slog('dawnline', 'info', `updates available · ${sig}`, null, 'Components');
slog('dawnline', 'info', sprintf(L_('updates available · %s'), sig), null, L_('Components'));
upd.history_add({ kind: 'found', items: found, auto });
}
st.announced = sig;
@@ -142,14 +188,14 @@ function note_found(res, st, auto) {
/** A line in the service log for each finished update (Dawnline's own is logged by the new agent). */
function log_update(name, r) {
let how = job.auto ? ' automatically' : '';
if (name == 'amneziawg') {
let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg'];
slog('awg', 'up', b && a && b != a ? `updated${how} · ${b} → ${a}`
: `installed the ${r?.build ?? ''} build${a ? ' · ' + a : ''}`, null, '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', `updated${how} · ${join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])}`, null, 'System packages');
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) {
@@ -172,9 +218,9 @@ function install(what) {
for (let w in what) {
let t = split_target(w), name = t[0], arg = t[1];
if (!INSTALLS[name])
die(`Unknown component ${name}`);
die(sprintf(_('Unknown component %s'), name));
job.current = name;
phase(`Updating ${WHO[name]}`);
phase(updating(name));
let r = INSTALLS[name](ctx, arg);
job.result[name] = r;
log_update(name, r);
@@ -228,7 +274,7 @@ function auto() {
if (a.current && !a.gen_change)
push(todo, `amneziawg:${a.current}${a.ru ? ':ru' : ''}`);
else
slog('awg', 'info', `${a.latest ?? 'a new build'} needs a manual switch in Components`, null, 'AmneziaWG');
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');
@@ -239,7 +285,7 @@ function auto() {
job.component = join(' ', todo);
job.auto = true;
job.log = [];
log(`Automatic update: ${join(', ', todo)}`);
log(sprintf(_('Automatic update: %s'), join(', ', todo)));
install(todo);
}
@@ -257,7 +303,8 @@ function restarts() {
let cmds = [];
if (after.apply)
push(cmds, '/usr/bin/dawnline apply');
if (after.uhttpd)
// 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');
@@ -265,6 +312,46 @@ function restarts() {
system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`);
}
/** 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 {
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) {
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 });
}
}
/* ---------- main ---------- */
ensure_dir(RUN_DIR);
@@ -279,43 +366,7 @@ if (!LOCK)
exit(0);
fs.mkdir(ctx.work, 0o700);
save();
try {
if (job.action == 'check') {
let which = job.component ? [ job.component ] : upd.TARGETS;
for (let w in which)
if (!CHECKS[w])
die(`Unknown component ${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: updater check [app|amneziawg|packages] | install <what> | auto');
job.state = 'done';
phase('Finished');
}
catch (e) {
quiet = false;
job.state = 'failed';
job.error = e.message;
log(`Error: ${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 ? 'automatic ' : ''}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 });
}
main();
system(`rm -rf '${ctx.work}'`);
job.finished = time();
@@ -1,3 +0,0 @@
Geist and Geist Mono are licensed under the SIL Open Font License, Version 1.1.
Copyright (c) 2023 Vercel, in collaboration with basement.studio.
https://github.com/vercel/geist-font/blob/main/OFL.txt
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><style>.t{fill:#0a0a0a}.g{fill:#fff}@media (prefers-color-scheme:dark){.t{fill:#fff}.g{fill:#0a0a0a}}</style><rect class="t" width="64" height="64" rx="16"/><path class="g" d="M14 38a18 18 0 0 1 36 0z"/><rect class="g" x="12" y="43" width="40" height="4" rx="2" opacity=".5"/></svg>

Before

Width:  |  Height:  |  Size: 343 B

@@ -1 +0,0 @@
@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: #57d64b;--ok-soft: rgba(87, 214, 75, .14);--warn: #ff8a3d;--bad: #ff5c5c;--bad-soft: rgba(255, 92, 92, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--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: #3aa32c;--t-red-a: #ffadad;--t-red-b: #dc3a3a;--t-orange-a: #ffc08f;--t-orange-b: #ec6a12;--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: #33a328;--ok-soft: rgba(51, 163, 40, .12);--warn: #ee6a12;--bad: #e5484d;--bad-soft: rgba(229, 72, 77, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--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: #2e8a22;--t-red-a: #ff9090;--t-red-b: #c92a2a}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable}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}: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(--t-grey-a);--tb: var(--t-grey-b)}.gi.t-blue{--ta: var(--t-blue-a);--tb: var(--t-blue-b)}.gi.t-green{--ta: var(--t-green-a);--tb: var(--t-green-b)}.gi.t-red{--ta: var(--t-red-a);--tb: var(--t-red-b)}.gi.t-orange{--ta: var(--t-orange-a);--tb: var(--t-orange-b)}.gi .ta{stop-color:var(--ta)}.gi .tb{stop-color:var(--tb)}.gi .fa{stop-color:var(--gi-a)}.gi .fb{stop-color:var(--gi-b)}.gi .fc{stop-color:var(--ta);stop-opacity:.28}.gi .ge{stroke:var(--gi-edge)}.gi .gr{stroke:var(--gi-rim)}.gi .gd{stroke:var(--gi-detail)}.gi .gdf{color:var(--gi-detail)}.knob{width:32px;height:32px;border-radius:50%;background:var(--knob);color:var(--text);display:grid;place-items:center;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.knob:hover{background:color-miLine truncated
@@ -1,6 +0,0 @@
"use strict";(()=>{var Oo=Object.create;var On=Object.defineProperty;var Ro=Object.getOwnPropertyDescriptor;var No=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,Fo=Object.prototype.hasOwnProperty;var Ko=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var qo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of No(e))!Fo.call(t,o)&&o!==n&&On(t,o,{get:()=>e[o],enumerable:!(r=Ro(e,o))||r.enumerable});return t};var Go=(t,e,n)=>(n=t!=null?Oo(Io(t)):{},qo(e||!t||!t.__esModule?On(n,"default",{value:t,enumerable:!0}):n,t));var gr=Ko((hr,mr)=>{"use strict";var fr=(function(){var t=function(d,m){var s=236,h=17,f=d,E=n[m],p=null,l=0,L=null,x=[],C={},R=function(w,k){l=f*4+17,p=(function(y){for(var T=new Array(y),S=0;S<y;S+=1){T[S]=new Array(y);for(var D=0;D<y;D+=1)T[S][D]=null}return T})(l),I(0,0),I(l-7,0),I(0,l-7),et(),Q(),it(w,k),f>=7&&ot(w),L==null&&(L=$t(f,E,x)),G(L,k)},I=function(w,k){for(var y=-1;y<=7;y+=1)if(!(w+y<=-1||l<=w+y))for(var T=-1;T<=7;T+=1)k+T<=-1||l<=k+T||(0<=y&&y<=6&&(T==0||T==6)||0<=T&&T<=6&&(y==0||y==6)||2<=y&&y<=4&&2<=T&&T<=4?p[w+y][k+T]=!0:p[w+y][k+T]=!1)},z=function(){for(var w=0,k=0,y=0;y<8;y+=1){R(!0,y);var T=o.getLostPoint(C);(y==0||w>T)&&(w=T,k=y)}return k},Q=function(){for(var w=8;w<l-8;w+=1)p[w][6]==null&&(p[w][6]=w%2==0);for(var k=8;k<l-8;k+=1)p[6][k]==null&&(p[6][k]=k%2==0)},et=function(){for(var w=o.getPatternPosition(f),k=0;k<w.length;k+=1)for(var y=0;y<w.length;y+=1){var T=w[k],S=w[y];if(p[T][S]==null)for(var D=-2;D<=2;D+=1)for(var K=-2;K<=2;K+=1)D==-2||D==2||K==-2||K==2||D==0&&K==0?p[T+D][S+K]=!0:p[T+D][S+K]=!1}},ot=function(w){for(var k=o.getBCHTypeNumber(f),y=0;y<18;y+=1){var T=!w&&(k>>y&1)==1;p[Math.floor(y/3)][y%3+l-8-3]=T}for(var y=0;y<18;y+=1){var T=!w&&(k>>y&1)==1;p[y%3+l-8-3][Math.floor(y/3)]=T}},it=function(w,k){for(var y=E<<3|k,T=o.getBCHTypeInfo(y),S=0;S<15;S+=1){var D=!w&&(T>>S&1)==1;S<6?p[S][8]=D:S<8?p[S+1][8]=D:p[l-15+S][8]=D}for(var S=0;S<15;S+=1){var D=!w&&(T>>S&1)==1;S<8?p[8][l-S-1]=D:S<9?p[8][15-S-1+1]=D:p[8][15-S-1]=D}p[l-8][8]=!w},G=function(w,k){for(var y=-1,T=l-1,S=7,D=0,K=o.getMaskFunction(k),N=l-1;N>0;N-=2)for(N==6&&(N-=1);;){for(var X=0;X<2;X+=1)if(p[T][N-X]==null){var nt=!1;D<w.length&&(nt=(w[D]>>>S&1)==1);var q=K(T,N-X);q&&(nt=!nt),p[T][N-X]=nt,S-=1,S==-1&&(D+=1,S=7)}if(T+=y,T<0||l<=T){T-=y,y=-y;break}}},V=function(w,k){for(var y=0,T=0,S=0,D=new Array(k.length),K=new Array(k.length),N=0;N<k.length;N+=1){var X=k[N].dataCount,nt=k[N].totalCount-X;T=Math.max(T,X),S=Math.max(S,nt),D[N]=new Array(X);for(var q=0;q<D[N].length;q+=1)D[N][q]=255&w.getBuffer()[q+y];y+=X;var gt=o.getErrorCorrectPolynomial(nt),vt=c(D[N],gt.getLength()-1),Dn=vt.mod(gt);K[N]=new Array(gt.getLength()-1);for(var q=0;q<K[N].length;q+=1){var Bn=q+Dn.getLength()-K[N].length;K[N][q]=Bn>=0?Dn.getAt(Bn):0}}for(var Hn=0,q=0;q<k.length;q+=1)Hn+=k[q].totalCount;for(var on=new Array(Hn),Ae=0,q=0;q<T;q+=1)for(var N=0;N<k.length;N+=1)q<D[N].length&&(on[Ae]=D[N][q],Ae+=1);for(var q=0;q<S;q+=1)for(var N=0;N<k.length;N+=1)q<K[N].length&&(on[Ae]=K[N][q],Ae+=1);return on},$t=function(w,k,y){for(var T=g.getRSBlocks(w,k),S=v(),D=0;D<y.length;D+=1){var K=y[D];S.put(K.getMode(),4),S.put(K.getLength(),o.getLengthInBits(K.getMode(),w)),K.write(S)}for(var N=0,D=0;D<T.length;D+=1)N+=T[D].dataCount;if(S.getLengthInBits()>N*8)throw"code length overflow. ("+S.getLengthInBits()+">"+N*8+")";for(S.getLengthInBits()+4<=N*8&&S.put(0,4);S.getLengthInBits()%8!=0;)S.putBit(!1);for(;!(S.getLengthInBits()>=N*8||(S.put(s,8),S.getLengthInBits()>=N*8));)S.put(h,8);return V(S,T)};C.addData=function(w,k){k=k||"Byte";var y=null;switch(k){case"Numeric":y=u(w);break;case"Alphanumeric":y=M(w);break;case"Byte":y=b(w);break;case"Kanji":y=A(w);break;default:throw"mode:"+k}x.push(y),L=null},C.isDark=function(w,k){if(w<0||l<=w||k<0||l<=k)throw w+","+k;return p[w][k]},C.getModuleCount=function(){return l},C.make=function(){if(f<1){for(var w=1;w<40;w++){for(var k=g.getRSBlocks(w,E),y=v(),T=0;T<x.length;T++){var S=x[T];y.put(S.getMode(),4),y.put(S.getLength(),o.getLengthInBits(S.getMode(),w)),S.write(y)}for(var D=0,T=0;T<k.length;T++)D+=k[T].dataCount;if(y.getLengthInBits()<=D*8)break}f=w}R(!1,z())},C.createTableTag=function(w,k){w=w||2,k=typeof k=="undefined"?w*4:k;var y="";y+='<table style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: "+k+"px;",y+='">',y+="<tbody>";for(var T=0;T<C.getModuleCount();T+=1){y+="<tr>";for(var S=0;S<C.getModuleCount();S+=1)y+='<td style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: 0px;",y+=" width: "+w+"px;",y+=" height: "+w+"px;",y+=" background-color: ",y+=C.isDark(T,S)?"#000000":"#ffffff",y+=";",y+='"/>';y+="</tr>"}return y+="</tbody>",y+="</table>",y},C.createSvgTag=function(w,k,y,T){var S={};typeof arguments[0]=="object"&&(S=arguments[0],w=S.cellSize,k=S.margin,y=S.alt,T=S.title),w=w||2,k=typeof k=="undefined"?w*4:k,y=typeof y=="string"?{text:y}:y||{Line truncated
`}return y%2&&w>0?vt.substring(0,vt.length-y-1)+Array(y+1).join("▀"):vt.substring(0,vt.length-1)};return C.createASCII=function(w,k){if(w=w||1,w<2)return rn(k);w-=1,k=typeof k=="undefined"?w*2:k;var y=C.getModuleCount()*w+k*2,T=k,S=y-k,D,K,N,X,nt=Array(w+1).join("██"),q=Array(w+1).join(" "),gt="",vt="";for(D=0;D<y;D+=1){for(N=Math.floor((D-T)/w),vt="",K=0;K<y;K+=1)X=1,T<=K&&K<S&&T<=D&&D<S&&C.isDark(N,Math.floor((K-T)/w))&&(X=0),vt+=X?nt:q;for(N=0;N<w;N+=1)gt+=vt+`
`}return gt.substring(0,gt.length-1)},C.renderTo2dContext=function(w,k){k=k||2;for(var y=C.getModuleCount(),T=0;T<y;T++)for(var S=0;S<y;S++)w.fillStyle=C.isDark(T,S)?"black":"white",w.fillRect(T*k,S*k,k,k)},C};t.stringToBytesFuncs={default:function(d){for(var m=[],s=0;s<d.length;s+=1){var h=d.charCodeAt(s);m.push(h&255)}return m}},t.stringToBytes=t.stringToBytesFuncs.default,t.createStringToBytes=function(d,m){var s=(function(){for(var f=P(d),E=function(){var Q=f.read();if(Q==-1)throw"eof";return Q},p=0,l={};;){var L=f.read();if(L==-1)break;var x=E(),C=E(),R=E(),I=String.fromCharCode(L<<8|x),z=C<<8|R;l[I]=z,p+=1}if(p!=m)throw p+" != "+m;return l})(),h=63;return function(f){for(var E=[],p=0;p<f.length;p+=1){var l=f.charCodeAt(p);if(l<128)E.push(l);else{var L=s[f.charAt(p)];typeof L=="number"?(L&255)==L?E.push(L):(E.push(L>>>8),E.push(L&255)):E.push(h)}}return E}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},o=(function(){var d=[[],[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]],m=1335,s=7973,h=21522,f={},E=function(p){for(var l=0;p!=0;)l+=1,p>>>=1;return l};return f.getBCHTypeInfo=function(p){for(var l=p<<10;E(l)-E(m)>=0;)l^=m<<E(l)-E(m);return(p<<10|l)^h},f.getBCHTypeNumber=function(p){for(var l=p<<12;E(l)-E(s)>=0;)l^=s<<E(l)-E(s);return p<<12|l},f.getPatternPosition=function(p){return d[p-1]},f.getMaskFunction=function(p){switch(p){case r.PATTERN000:return function(l,L){return(l+L)%2==0};case r.PATTERN001:return function(l,L){return l%2==0};case r.PATTERN010:return function(l,L){return L%3==0};case r.PATTERN011:return function(l,L){return(l+L)%3==0};case r.PATTERN100:return function(l,L){return(Math.floor(l/2)+Math.floor(L/3))%2==0};case r.PATTERN101:return function(l,L){return l*L%2+l*L%3==0};case r.PATTERN110:return function(l,L){return(l*L%2+l*L%3)%2==0};case r.PATTERN111:return function(l,L){return(l*L%3+(l+L)%2)%2==0};default:throw"bad maskPattern:"+p}},f.getErrorCorrectPolynomial=function(p){for(var l=c([1],0),L=0;L<p;L+=1)l=l.multiply(c([1,a.gexp(L)],0));return l},f.getLengthInBits=function(p,l){if(1<=l&&l<10)switch(p){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:"+p}else if(l<27)switch(p){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:"+p}else if(l<41)switch(p){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:"+p}else throw"type:"+l},f.getLostPoint=function(p){for(var l=p.getModuleCount(),L=0,x=0;x<l;x+=1)for(var C=0;C<l;C+=1){for(var R=0,I=p.isDark(x,C),z=-1;z<=1;z+=1)if(!(x+z<0||l<=x+z))for(var Q=-1;Q<=1;Q+=1)C+Q<0||l<=C+Q||z==0&&Q==0||I==p.isDark(x+z,C+Q)&&(R+=1);R>5&&(L+=3+R-5)}for(var x=0;x<l-1;x+=1)for(var C=0;C<l-1;C+=1){var et=0;p.isDark(x,C)&&(et+=1),p.isDark(x+1,C)&&(et+=1),p.isDark(x,C+1)&&(et+=1),p.isDark(x+1,C+1)&&(et+=1),(et==0||et==4)&&(L+=3)}for(var x=0;x<l;x+=1)for(var C=0;C<l-6;C+=1)p.isDark(x,C)&&!p.isDark(x,C+1)&&p.isDark(x,C+2)&&p.isDark(x,C+3)&&p.isDark(x,C+4)&&!p.isDark(x,C+5)&&p.isDark(x,C+6)&&(L+=40);for(var C=0;C<l;C+=1)for(var x=0;x<l-6;x+=1)p.isDark(x,C)&&!p.isDark(x+1,C)&&p.isDark(x+2,C)&&p.isDark(x+3,C)&&p.isDark(x+4,C)&&!p.isDark(x+5,C)&&p.isDark(x+6,C)&&(L+=40);for(var ot=0,C=0;C<l;C+=1)for(var x=0;x<l;x+=1)p.isDark(x,C)&&(ot+=1);var it=Math.abs(100*ot/l/l-50)/5;return L+=it*10,L},f})(),a=(function(){for(var d=new Array(256),m=new Array(256),s=0;s<8;s+=1)d[s]=1<<s;for(var s=8;s<256;s+=1)d[s]=d[s-4]^d[s-5]^d[s-6]^d[s-8];for(var s=0;s<255;s+=1)m[d[s]]=s;var h={};return h.glog=function(f){if(f<1)throw"glog("+f+")";return m[f]},h.gexp=function(f){for(;f<0;)f+=255;for(;f>=256;)f-=255;return d[f]},h})();function c(d,m){if(typeof d.length=="undefined")throw d.length+"/"+m;var s=(function(){for(var f=0;f<d.length&&d[f]==0;)f+=1;for(var E=new Array(d.length-f+m),p=0;p<d.length-f;p+=1)E[p]=d[p+f];return E})(),h={};return h.getAt=function(f){return s[f]},h.getLength=function(){return s.length},h.multiply=function(f){for(var E=new Array(h.getLength()+f.getLength()-1),p=0;p<h.getLength();p+=1)for(var l=0;l<f.getLength();l+=1)E[p+l]^=a.gexp(a.glog(h.getAt(p))+a.glog(f.getAt(l)));return c(E,0)},h.mod=function( Line truncated
`),hostName:a,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},g={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(c),port:String(n.port),protocol_version:r.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:a};return n.dns[0]&&(g.dns1=n.dns[0]),n.dns[1]&&(g.dns2=n.dns[1]),g}function bi(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function wi(t){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let n=new e.Blob([t]).stream().pipeThrough(new e.CompressionStream("deflate")),r=new Uint8Array(await new e.Response(n).arrayBuffer()),o=new Uint8Array(4+r.length);return new DataView(o.buffer).setUint32(0,t.length,!1),o.set(r,4),o}catch{return null}}async function Ln(t,e,n=!0){let r=new TextEncoder().encode(JSON.stringify(xi(t,e))),o=n?await wi(r):null;return`vpn://${bi(o!=null?o:r)}`}var Zr=t=>t.replace(/^vpn:\/\//,"");var to=["height","marginTop","marginBottom","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"];function qt(t,e={}){let n=i("div",{class:`acc${e.inset?" inset":""}`}),r=t.map((u,M)=>{var $;let b=u.body.filter(d=>!!d),A=!b.length,O=[u.icon,i("span",{class:"acc-title"},i("span",{class:"t"},u.title),($=u.tag)!=null?$:null),u.val?i("span",{class:`acc-val${u.valHide?" hide-open":""}`},u.val):null],B=M===e.open&&!A,P=A?i("div",{class:"acc-head"},...O):i("button",{type:"button",class:"acc-head","aria-expanded":String(B),onclick:()=>v(H)},...O,F("chevron","i acc-chev")),H=i("div",{class:`acc-row${A?" still":""}${B?" open":""}`},P,i("div",{class:"acc-body"},...b));return n.appendChild(H),H}),o=u=>u.querySelector(".acc-body"),a=()=>r.forEach((u,M)=>{let b=u.classList.contains("open");u.classList.toggle("rt",M===0||b||r[M-1].classList.contains("open")),u.classList.toggle("rb",M===r.length-1||b||r[M+1].classList.contains("open"))}),c=u=>{let M=getComputedStyle(u),b={};for(let A of to)b[A]=A==="height"?`${u.getBoundingClientRect().height}px`:M[A];return b},g=()=>r.forEach(u=>{var M;return(M=u.querySelector("button.acc-head"))==null?void 0:M.setAttribute("aria-expanded",String(u.classList.contains("open")))});function v(u){var B;let M=r.map(c);r.forEach(P=>P.getAnimations().forEach(H=>H.cancel())),r.forEach(P=>o(P).getAnimations().forEach(H=>H.cancel()));let b=!u.classList.contains("open"),A=r.filter(P=>P.classList.contains("open")&&(P===u||b));r.forEach(P=>{P.classList.remove("closing"),P!==u&&P.classList.remove("open")}),u.classList.toggle("open",b),a();let O=ce();r.forEach((P,H)=>{let $=c(P);to.some(d=>M[H][d]!==$[d])&&(A.includes(P)&&P.classList.add("closing"),_(P,[M[H],$],{duration:Et.duration,easing:Et.easing}).onfinish=()=>P.classList.remove("closing"))}),A.forEach(P=>_(o(P),[{opacity:1},{opacity:0,filter:"blur(2px)"}],{duration:160,easing:J,fill:"forwards"})),b&&_(o(u),[{opacity:0,filter:"blur(2px)"},{opacity:1,filter:"blur(0px)"}],{duration:300,easing:"cubic-bezier(0,0,.58,1)"}),de(O),g(),(B=e.onToggle)==null||B.call(e,r.indexOf(u),b,!1)}return a(),{el:n,openIndex:()=>r.findIndex(u=>u.classList.contains("open")),setOpen(u){r.forEach((M,b)=>M.classList.toggle("open",b===u&&!M.classList.contains("still"))),a(),g(),r.forEach((M,b)=>{var A;return(A=e.onToggle)==null?void 0:A.call(e,b,M.classList.contains("open"),!0)})}}}function eo(t,e,n){let r=i("span",{class:"seg-pill"}),o=i("div",{class:"seg appseg",role:"tablist"},r),a=t.map(A=>{let O=i("button",{type:"button",class:"seg-b",role:"tab","aria-label":A.label,title:A.label,onclick:()=>b(A.value)},F(A.icon),i("span",{class:"seg-l"},A.label));return O.dataset.v=A.value,o.appendChild(O),O}),c=A=>A.querySelector(".seg-l"),g=()=>a.forEach(A=>{let O=A.dataset.v===e;A.classList.toggle("on",O),A.setAttribute("aria-selected",String(O))}),v=()=>{let A=a.find(O=>O.dataset.v===e);return A&&A.offsetWidth?[A.offsetLeft,o.clientWidth-A.offsetLeft-A.offsetWidth]:null},u=()=>{let A=v();A&&(r.style.left=`${A[0]}px`,r.style.right=`${A[1]}px`)},M=0;function b(A){if(A===e)return;let O=a.findIndex(C=>C.dataset.v===e),B=a.findIndex(C=>C.dataset.v===A),P=getComputedStyle(r),H=parseFloat(P.left)||0,$=parseFloat(P.right)||0,d=a.map(C=>parseFloat(getComputedStyle(C).flexGrow)||0),m=c(a[O]),s=m.getBoundingClientRect().width;[...a,...a.map(c)].forEach(C=>C.getAnimations().forEach(R=>R.cancel())),e=A,g(),a.forEach((C,R)=>{let I=R===B?1:0;d[R]!==I&&_(C,[{flexGrow:d[R]},{flexGrow:I}],{duration:U.duration,easing:U.easing})}),_(m,[{opacity:1,maxWidth:`${s}px`,marginLeft:"0px"},{opacity:0,maxWidth:"0px",marginLeft:"-8px"}],{duration:220,easing:"ease-out"}),_(c(a[B]),[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,delay:70,easing:Y,fill:"backwards"});let h=B>O,f=Lt()?U:Fn,E=performance.now(),p=Math.m Line truncated
`).flatMap((u,M)=>M?[`
`,ro(u,e)]:[ro(u,e)]));r();let o=!!Wt(t.filename,t.conf),a=i("button",{type:"button",class:"btn soft sm",onclick:()=>{e=!e,a.replaceChildren(F(e?"x":"key"),i("span",{},e?"Hide key":"Show key")),r(),n.querySelectorAll(".mask, .k").forEach(u=>_(u,[{filter:"blur(4px)",opacity:.4},{filter:"none",opacity:1}],{duration:320,easing:Y}))}},F("key"),i("span",{},"Show key")),c=i("button",{type:"button",class:"btn soft sm",onclick:u=>pt(t.conf,"Configuration copied",u.currentTarget)},F("copy"),i("span",{class:"lbl"},"Copy")),g=i("div",{class:"filecard"},i("div",{class:"fc-row"},i("span",{class:"filecard-ic"},".conf"),i("span",{class:"t"},i("span",{class:"mono"},t.filename),i("span",{},"For computers and routers"))),i("button",{type:"button",class:"btn accent sm block",onclick:()=>ye(t.filename,t.conf)},F(o?"open":"download"),i("span",{},o?"Share file":"Download"))),v=qt([{icon:j("file"),title:"Configuration",body:[i("div",{class:"confbar"},a,c),n]}],{inset:!0});return i("div",{class:"step-box"},g,v.el)}function fo(t){let e=i("span",{class:"osm-p"},at[t]),n=Dr(me(t,"ios"),me(t,"android"));return{el:i("span",{class:"scanline"},i("span",{},"In ",e,":"),n.el),set(r){Z(e,at[r],void 0,{whole:!0}),n.set(me(r,"ios"),me(r,"android"))}}}function ho(t){let e=i("span",{class:"tt"}),n=i("span",{class:"tt-m"}),r=i("span",{class:"hp-tip","aria-hidden":"true"},e,n),o=i("button",{type:"button",class:"hp-b",onclick:()=>ye(t().file,t().text)},F("download")),a=i("button",{type:"button",class:"hp-b"},F("copy")),c=i("div",{class:"hpill",role:"group","aria-label":"The connection","data-key":"conn"},o,a,r),g=null,v=0,u=0,M=s=>{var h;return s===a&&a.classList.contains("done")?"Copied":(h=s.getAttribute("aria-label"))!=null?h:""},b=(s,h)=>{n.textContent=h;let f=n.offsetWidth+20;return Math.min(s.offsetLeft+s.offsetWidth/2,c.offsetWidth+46-f/2)},A=s=>`translateX(${s}px) translateX(-50%)`,O=s=>{let h=getComputedStyle(r).transform;r.getAnimations().forEach(f=>f.cancel()),r.style.transform=A(s),_(r,[{transform:h},{transform:A(s)}],{duration:U.duration,easing:U.easing})},B=s=>Z(e,s),P=s=>{if(clearTimeout(v),g===s&&r.classList.contains("on"))return;if(g=s,r.classList.contains("on")){let f=M(s);return O(b(s,f)),B(f)}let h=()=>{let f=M(s);bt(e,f);let E=b(s,f);r.getAnimations().forEach(p=>p.cancel()),r.style.transform=A(E),r.classList.add("on"),_(r,[{opacity:0,transform:`${A(E)} translateY(-3px) scale(.96)`,filter:"blur(3px)"},{opacity:1,transform:A(E),filter:"blur(0px)"}],{duration:220,easing:Y})};performance.now()<u?h():v=window.setTimeout(h,420)},H=()=>{clearTimeout(v),g=null,r.classList.contains("on")&&(u=performance.now()+500,r.classList.remove("on"),_(r,[{opacity:1},{opacity:0}],{duration:120,easing:"ease-out"}))};for(let s of[o,a])s.addEventListener("pointerenter",h=>{h.pointerType==="mouse"&&P(s)}),s.addEventListener("focus",()=>{s.matches(":focus-visible")&&P(s)}),s.addEventListener("blur",H);c.addEventListener("pointerleave",H);let $=s=>{let h=F(s);a.querySelector("svg").replaceWith(h),_(h,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:yt.duration,easing:yt.easing})},d=()=>{if(g!==a||!r.classList.contains("on"))return;let s=M(a);O(b(a,s)),B(s)},m=0;return a.addEventListener("click",()=>{let s=t();pt(s.text,s.msg),clearTimeout(m),a.classList.contains("done")||(a.classList.add("done"),$("check"),d()),m=window.setTimeout(()=>{a.classList.remove("done"),$("copy"),d()},1600)}),{el:c,sync(){let s=t().app;o.setAttribute("aria-label",`Download ${s} config`),a.setAttribute("aria-label",`Copy ${s} config`)}}}function go(t){let e=i("b",{},"Waiting for the connection"),n=i("span",{class:"ws",hidden:!0}),r=i("div",{class:"way",role:"status","aria-live":"polite"},i("div",{class:"way-row"},i("span",{class:"way-end"},F(t.kind)),i("span",{class:"way-track"},i("span",{class:"way-glow"},i("i")),i("span",{class:"way-fill"})),i("span",{class:"way-end home"},F("server"))),i("div",{class:"way-text"},i("span",{class:"t"},e,n)));return{el:r,connected(){r.classList.add("done"),Z(e,`${t.name} connected`)},gaveUp(){r.classList.add("stopped"),Z(e,"No connection yet"),n.textContent="Close this and open it again to keep checking.",n.hidden=!1,_(e.parentElement,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,easing:Y})}}}function vo(t,e=4){window.setTimeout(async()=>{var n;try{let r=await ut("state");xt(r),be()||Mt(),!((n=r.person.devices.find(o=>o.id===t))!=null&&n.online)&&e>1&&vo(t,e-1)}catch{}},1500)}function yo(t,e,n){let r=te(),o=0,a=0,c=!1,g=Date.now(),v=async()=>{if(o=0,!c){if(Date.now()-g>6e5){c=!0,n();return}if(document.hidden)return u();try{let b=await ut("state");xt(b);let A=b.person.devices.find(O=>O.id===t.id);if(A&&A.handshake>r){c=!0,e(),A.online||vo(t.id);return}}catch(b){if(Oe(b)){c=!0;return}}a++,u()}},u=()=>{!c&&!o&&(o=window.setTimeout(v,a<6?5e3:a<12?15e3:3e4))},M=()=>{!document.hidden&&!c&&!o&&v()};return document.addEventListener("visibilitychange",M),u(),()=>{c=!0,o Line truncated
@@ -9,7 +9,7 @@ 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_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_ACCEPT_ENCODING',
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
'HTTP_CF_CONNECTING_IP' ])
env[k] = getenv(k);
@@ -6,6 +6,7 @@
"luci.dawnline": [
"rev",
"status",
"meter",
"setup_defaults",
"health",
"service_log",
@@ -4,7 +4,9 @@
// servers, people (and their devices), settings, home (services, circles),
// maint (Diagnostics, backups, removal) and updates (Components). Each module
// exports `methods` as { name: { args, call } }; read-only users get the
// methods listed under "read" in acl.d/luci-app-dawnline.json.
// methods listed under "read" in acl.d/luci-app-dawnline.json. Every method
// also takes `lang`, the admin page's language, and answers in it (its
// errors and the texts the backend writes, through dawnline.i18n).
'use strict';
import * as status from 'dawnline.rpc.status';
@@ -14,9 +16,29 @@ import * as settings from 'dawnline.rpc.settings';
import * as home from 'dawnline.rpc.home';
import * as maint from 'dawnline.rpc.maint';
import * as updates from 'dawnline.rpc.updates';
import * as i18n from 'dawnline.i18n';
/** The methods with `lang` added: the language is set for the call, the method never sees it. */
function in_lang(methods) {
let out = {};
for (let name, m in methods) {
let call = m.call;
out[name] = {
...m,
args: { ...(m.args ?? {}), lang: '' },
call: function(req) {
i18n.use(req.args?.lang);
if (req.args)
delete req.args.lang;
return call(req);
},
};
}
return out;
}
return {
'luci.dawnline': {
'luci.dawnline': in_lang({
...status.methods,
...servers.methods,
...people.methods,
@@ -24,5 +46,5 @@ return {
...home.methods,
...maint.methods,
...updates.methods,
},
}),
};
@@ -1,5 +1,6 @@
// Dawnline: "Check access" — walks the same rules the nft table and the
// client configuration apply, and says in words where a connection stops.
// client configuration apply, and says in words where a connection stops
// (in the admin's language: each step is a whole sentence).
'use strict';
@@ -9,17 +10,68 @@ 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';
const STATE_TEXT = {
no_server: 'they have no server',
server_off: 'their server is turned off',
paused: 'they are paused',
expired: 'their access has ended',
quota: 'they used up their data',
hours: 'it is outside their allowed hours',
};
/** "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);
}
const ACCESS_TEXT = { lan: 'Home only', internet: 'Internet only', both: 'Home and Internet' };
/** "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 ?? '' };
@@ -63,9 +115,9 @@ function peer_of(dmp, d) {
return dmp.peers[d.public_key];
}
/** What the device sends to the router: its configuration's AllowedIPs. */
/** What the device sends to the router: its configuration's AllowedIPs (its own, with lan_bypass). */
function routed(m, srv, p, d) {
return { nets: awg.allowed_ips(m, srv, p), what: 'Its configuration', list: null };
return awg.allowed_ips(m, srv, p, d);
}
/** The home network (interface) of a server that holds an address. */
@@ -87,19 +139,19 @@ function router_addrs(snap) {
function person_ok(m, p, d, states) {
let st = states[p.id] ?? 'active';
if (d.disabled)
return step(false, `${d.name} is turned off`, 'Turn the device on again on its page.');
return step(false, sprintf(_('%s is turned off'), d.name), _('Turn the device on again on its page.'));
if (st != 'active')
return step(false, `${p.name} can't connect: ${STATE_TEXT[st] ?? st}`, '');
return step(true, `${p.name} is active`, ACCESS_TEXT[p.access]);
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, `${who} has never connected`, 'There is no session the router could reach.');
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, `${who} isn't connected right now`, 'The router reaches it only while its VPN is on.');
return step(true, `${who} is connected`, '');
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. */
@@ -107,18 +159,18 @@ 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, `${d.name} has no server`, '') ];
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 r = routed(m, srv, p, d);
let allowed = r.nets;
let allowed = routed(m, srv, p, d);
let via = (ip) => {
let hit = in_nets(ip, allowed);
let what = r.list ? `${r.what}: ${r.list}` : `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`;
// The configuration's own words: the option and its value.
let what = `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`;
return hit
? step(true, `${r.what} sends it to the router`, what)
: step(false, `${r.what} doesn't send it to the router`, `${what}: the device's own network handles it.`);
? 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.
@@ -126,47 +178,56 @@ function from_device(m, d, t, states, dmp, snap) {
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', '') ];
return [ step(false, _('That is the same device'), '') ];
if (!q || q.server != p.server)
return stop(steps, step(false, `${who} is on another server`, 'Devices of different servers never reach each other.'));
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, `${p.name} has ${ACCESS_TEXT[p.access]}`, 'Only people with home access reach other devices.'));
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, `${q.name} has ${ACCESS_TEXT[q.access]}`, 'Only devices of people with home access can be reached.'));
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, `"Devices reach each other" is off on ${srv.name}`, 'Server → Access → Home network.'));
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, `${p.name} and ${q.name} are not in one circle`,
`${p.name}: ${a?.name ?? 'no circle'} · ${q.name}: ${b?.name ?? 'no circle'}`));
push(steps, step(true, `Both are in ${a.name}`, 'Devices in one circle reach each other.'));
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 ? `Both are ${p.name}'s devices` : 'Devices reach each other on this server', ''));
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, `${who} can't be reached: ${t.dev.disabled ? 'it is turned off' : STATE_TEXT[st] ?? st}`, ''));
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, `${t.ip} is this router: DNS is open to everyone`, ''));
push(steps, step(true, sprintf(_('%s is this router: DNS is open to everyone'), t.ip), ''));
else if (portal)
push(steps, step(true, `${t.ip} is this router: the personal portal is open to everyone`, ''));
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, `${t.ip} is this router`, `${p.name} has ${ACCESS_TEXT[p.access]}: only DNS and the portal on the router.`));
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, `${t.ip} is this router on a network ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`));
push(steps, step(true, `${t.ip} is this router`, h.all ? 'Home access includes the router.' : `On one of the networks ${p.name} reaches.`));
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;
@@ -175,14 +236,14 @@ function from_device(m, d, t, states, dmp, snap) {
// A tunnel address no device has.
let tn = in_tunnels(m, t.ip);
if (tn)
return stop(steps, step(false, `No device uses ${t.ip}`, `It is in the tunnel network ${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, `${t.ip} is at home (${hdev})`, `${p.name} has Internet only.`));
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) {
@@ -192,28 +253,32 @@ function from_device(m, d, t, states, dmp, snap) {
}
let names = join(', ', map(filter(map(p.services, (x) => m.services[x]), (x) => x), (x) => x.name));
if (!hit)
return stop(steps, step(false, `${t.ip}${t.port ? `:${t.port}` : ''} is not one of ${p.name}'s home services`, `Allowed: ${names}`));
push(steps, step(true, `${t.ip} is ${hit.name}, one of ${p.name}'s home services`,
length(hit.ports) ? `Ports ${join(', ', hit.ports)}` : 'All ports'));
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, `${t.ip} is in ${hdev}, which ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`));
push(steps, step(true, `${t.ip} is in ${hdev}`, h.all ? 'Home access reaches every home network.' : `One of the networks ${p.name} reaches.`));
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'}`));
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, `${t.ip} isn't in ${srv.name}'s home network`, 'Private addresses outside the home network are blocked.'));
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, `${t.ip} is on the internet`, `${p.name} has Home only: their device's own internet reaches it, not the tunnel.`));
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, `${t.ip} is on the internet`, srv.lan_like ? 'It leaves like a home device would.' : `It leaves through ${sn.wan.dev ?? 'the WAN'}.`));
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;
}
@@ -222,44 +287,47 @@ 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, `${d.name} has no server`, '') ];
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, `${ip} isn't in ${srv.name}'s home network`, 'Only home devices reach people\'s devices.') ];
let steps = [ step(true, `${ip} is at home (${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.name} has ${p.access == 'lan' ? 'only some home services' : ACCESS_TEXT[p.access]}`,
'Home devices reach only people with home access.'));
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, `${p.name} doesn't reach ${hdev}`, 'Networks a person does not reach cannot reach them either.'));
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, 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). */
export function check(m, from, to) {
/**
* `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(`"${from}" is not a device or an IPv4 address.`);
die(sprintf(_('"%s" is not a device or an IPv4 address.'), from));
if (!b)
die(`"${to}" is not a device or an IPv4 address.`);
let usage = core.load_usage();
let states = view.states(m, usage);
let dmp = live.dump(m);
let snap = net.snapshot(true);
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.');
die(_('Choose a device on at least one side.'));
let ok = length(filter(steps, (s) => !s.ok)) == 0;
return { ok, steps };
};
@@ -22,6 +22,7 @@ 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';
/** The network signature the last apply() worked from (the agent compares against it). */
@@ -93,9 +94,9 @@ function nft_result(err, present) {
return null;
}
if (was != err) {
log('Access rules', present
? "couldn't be updated — the previous rules stay, and changes to access wait until they load"
: "couldn't load — no device is loaded into the tunnels until they do", 'error', 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);
}
@@ -138,18 +139,19 @@ export function firewall_drift(m) {
/**
* What an admin should hear when a sync did not fully take: the access table
* failed, or a server did not accept its devices. Null when all went in.
* 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()
? `Access rules couldn't be updated (${table}): the previous rules stay, so this change isn't in effect yet.`
: `Access rules couldn't load (${table}): no device is loaded into the tunnels until they do.`);
? 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, `Couldn't load devices into ${m.servers[id]?.name ?? id}: ${r}.`);
return length(out) ? join(' ', out) + ' Open Diagnostics → Health.' : null;
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;
}
/*
@@ -242,7 +244,7 @@ export function apply(opts) {
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: r.lp.error } : !r.lp.off, peers: r.peers, warning: r.warning };
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). */
@@ -1,8 +1,9 @@
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client
// configurations (.conf, AmneziaVPN key), the netifd options of a server's
// tunnel, its peers (`awg syncconf`, no restart), live counters and what the
// watchdog and Health check about it. Plain WireGuard is AmneziaWG with the
// disguise off.
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation) and the values
// AmneziaWG refuses, client configurations (.conf, AmneziaVPN key), the
// netifd options of a server's tunnel, its peers (`awg syncconf`, no
// restart), live counters, the words for why a tunnel is kept down
// (blocked_text) and what the watchdog and Health check about it. Plain
// WireGuard is AmneziaWG with the disguise off.
import { readfile, stat, unlink } from 'fs';
import {
@@ -11,8 +12,10 @@ import {
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import { ipv6_groups } from 'dawnline.schema';
import * as pkg from 'dawnline.pkg';
import * as builds from 'dawnline.awg_builds';
import { _, L_ } from 'dawnline.i18n';
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
export const OBF_CONF = {
@@ -27,6 +30,9 @@ export const OBF_CONF = {
const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh';
/** The packages AmneziaWG comes in (the Components tab installs them). */
const PACKAGES = [ 'kmod-amneziawg', 'amneziawg-tools' ];
// A module constant, compiled once (a literal is compiled each time it runs):
// dump() checks it on every line of each tunnel's `awg show <ifname> dump`, every second.
const DIGITS = /^[0-9]+$/;
/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */
function proto_handler() {
@@ -98,15 +104,15 @@ export function genpsk() {
export function new_keys(public_key) {
let psk = genpsk();
if (!valid_key(psk))
die('Key generation failed (no random data).');
die(_('Key generation failed (no random data).'));
if (public_key) {
if (!valid_key(public_key))
die('Invalid public key.');
die(_('Invalid public key.'));
return { public_key, preshared_key: psk };
}
let priv = genkey(), pub = pubkey(priv);
if (!pub)
die('Key generation failed (is amneziawg-tools installed?).');
die(_('Key generation failed (is amneziawg-tools installed?).'));
return { private_key: priv, public_key: pub, preshared_key: psk };
};
@@ -114,7 +120,7 @@ export function new_keys(public_key) {
export function server_keys() {
let priv = genkey(), pub = pubkey(priv);
if (!pub)
die('Key generation failed (is amneziawg-tools installed?).');
die(_('Key generation failed (is amneziawg-tools installed?).'));
return { private_key: priv, public_key: pub };
};
@@ -134,7 +140,9 @@ function rand_h(used) {
}
}
// caps() answers from here while the tool, the protocol script and the module file are the same.
// caps() answers from here while the tool, the protocol script, the module
// file, the install record and the loaded module are the same (tmpfs: a
// reboot starts over).
const CAPS = `${RUN_DIR}/awg-caps.json`;
/**
@@ -142,15 +150,20 @@ const CAPS = `${RUN_DIR}/awg-caps.json`;
* options it passes on) and the `awg` tool (the keys it accepts) say what the
* tools know, the kernel module's package version what the kernel runs, and
* a feature counts only when both have it (tools 3.1 over a 2.0 module would
* configure header protection that the kernel silently lacks):
* configure header protection that the kernel silently lacks). While an
* update waits for a reboot (its old module stayed loaded) the kernel runs
* the generation from before it, as the install recorded it:
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
* v3 — header protection, trailers, padding, timing (AWG 3.1)
* tools / kmod — their generations ('1.0', '2.0', '3.1'; null unknown)
* mismatch — the two differ
* pending — an installed module waits for a reboot (dawnline.awg_builds)
*/
export function caps() {
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}`;
let core = builds.module_core();
let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}` +
`/${stat(builds.RECORD)?.mtime ?? 0}/${core ?? 0}`;
let cached = read_json(CAPS, null);
if (cached?.key == key && cached.caps)
return cached.caps;
@@ -159,12 +172,15 @@ export function caps() {
let t2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0;
let t3 = t2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
let tools = !stat(TOOL) ? null : t3 ? '3.1' : t2 ? '2.0' : '1.0';
// A module installed by hand has no package: then the tools are believed.
let kmod = builds.gen(pkg.version('kmod-amneziawg'));
// A module installed by hand has no package, so no generation (also when
// a pending update replaces it): then the tools are believed.
let rec = read_json(builds.RECORD, null), boot = builds.boot_id();
let kmod = builds.running_gen(rec, boot, core, pkg.version('kmod-amneziawg'));
let out = {
v2: t2 && (kmod == null || kmod != '1.0'),
v3: t3 && (kmod == null || kmod == '3.1'),
tools, kmod, mismatch: tools != null && kmod != null && tools != kmod,
pending: builds.pending(rec, boot, core),
};
ensure_dir(RUN_DIR);
write_json(CAPS, { key, caps: out }, 0o644);
@@ -172,10 +188,11 @@ export function caps() {
};
/**
* Why this AmneziaWG cannot run a server's disguise values, or null: a 3.1
* preset after a rollback to a 2.0 build would come up without the header
* protection every device expects, so such a server is kept down instead
* (dawnline.netifd).
* Why this AmneziaWG cannot run a server's disguise values, as a reason to
* keep the server down (blocked_text): { code: 'disguise', need, installed }
* (installed null: none), or null when it can. A 3.1 preset after a rollback
* to a 2.0 build would come up without the header protection every device
* expects, so such a server is kept down instead (dawnline.netifd).
*/
export function obf_unsupported(o) {
let c = caps();
@@ -185,9 +202,9 @@ export function obf_unsupported(o) {
let v2 = [ 's3', 's4', 'i1', 'i2', 'i3', 'i4', 'i5' ];
let ranged = length(filter([ 'h1', 'h2', 'h3', 'h4' ], (k) => match(`${o?.[k] ?? ''}`, /-/))) > 0;
if (has(v3) && !c.v3)
return `its disguise needs AmneziaWG 3.1 (installed: ${c.kmod ?? c.tools ?? 'none'})`;
return { code: 'disguise', need: '3.1', installed: c.kmod ?? c.tools };
if ((has(v2) || ranged) && !c.v2)
return `its disguise needs AmneziaWG 2.0 (installed: ${c.kmod ?? c.tools ?? 'none'})`;
return { code: 'disguise', need: '2.0', installed: c.kmod ?? c.tools };
return null;
};
@@ -236,18 +253,24 @@ function dns_answer() {
* offers Balanced or Maximum instead.
*/
export function obf_preset(name) {
if (name == 'max')
if (name == 'max') {
// 32 random bytes, as `awg genkey` makes them (no process). Without
// one the server would come up with weak or no header protection.
let hpk = genpsk();
if (!valid_key(hpk))
die(_('Key generation failed (no random data).'));
return {
jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50',
s1: '12', s2: '12', s3: '12', s4: '12',
h1: '1', h2: '2', h3: '3', h4: '4',
i1: dns_query(), i2: dns_answer(),
header_protection_key: sh_out('awg genkey'),
header_protection_key: hpk,
content_padding_addition: '10-100',
rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180',
keepalive_timeout: '5-15', max_handshake_attempts: '15-20',
random_trailers: 'on', disable_cookies: 'on',
};
}
if (name == 'off')
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
let o = {};
@@ -273,38 +296,222 @@ export function obf_preset(name) {
return o;
};
/* ---------- disguise values AmneziaWG refuses ---------- */
export function obf_errors(o) {
// Checked with ltrim, not regexes: this module loads with every portal request.
const DEC = '0123456789', HEX = '0123456789abcdefABCDEF';
/** A whole number in digits up to `top`, or null (no spaces: callers trim where the tools drop them). */
function uint(v, top) {
let s = `${v}`;
if (s == '' || length(s) > 10 || ltrim(s, DEC) != '')
return null;
return +s <= top ? +s : null;
}
/** A number or a range as AmneziaWG writes them ("5", "5-15"), each end up to `top`: [ lo, hi ], or null. */
function uint_range(v, top) {
let p = split(trim(`${v}`), '-');
let lo = length(p) <= 2 ? uint(p[0], top) : null;
let hi = length(p) == 2 ? uint(p[1], top) : lo;
return lo != null && hi != null && lo <= hi ? [ lo, hi ] : null;
}
/** Value `k` of disguise values `o` is set. */
function given(o, k) {
return o[k] != null && o[k] != '';
}
/**
* Packet types H1-H4: a number or a range each, apart from the others (the
* kernel refuses an overlap). One not given keeps WireGuard's own type, 1-4.
*/
function headers_unsafe(o, errs) {
let hs = [];
for (let i = 1; i <= 4; i++) {
let r = given(o, `h${i}`) ? uint_range(o[`h${i}`], 4294967295) : [ i, i ];
if (!r)
push(errs, sprintf(_('%s must be a number or a range like 100-200, up to 4294967295.'), OBF_CONF[`h${i}`]));
push(hs, r);
}
for (let i = 0; i < 4; i++)
for (let j = i + 1; j < 4; j++)
if (hs[i] && hs[j] && hs[i][0] <= hs[j][1] && hs[j][0] <= hs[i][1])
push(errs, sprintf(_('%s and %s overlap: each packet type needs values of its own.'), OBF_CONF[`h${i + 1}`], OBF_CONF[`h${j + 1}`]));
}
/**
* One tag of a signature packet as both the kernel and amneziawg-go read it:
* <b 0x..> fixed bytes (an even number of hex digits), <r N>, <rc N>, <rd N>
* (N random bytes, letters, digits; a negative N writes past the packet in
* the kernel, kmod #267) or <t> (the time). <c> is the kernel's alone and
* <d>, <ds>, <dz> amneziawg-go's: devices on the other refuse them.
*/
function itag_ok(tag) {
if (tag == 't')
return true;
let sp = index(tag, ' ');
if (sp < 0)
return false;
let key = substr(tag, 0, sp), val = substr(tag, sp + 1);
if (key == 'b')
return length(val) > 2 && length(val) % 2 == 0 && substr(val, 0, 2) == '0x' && ltrim(substr(val, 2), HEX) == '';
if (key == 'r' || key == 'rc' || key == 'rd')
return (uint(val, 1000) ?? 0) >= 1;
return false;
}
/** What is wrong with signature packet `name` (I1-I5) holding `s`, as a sentence; null when nothing. */
function itag_error(name, s) {
// In a .conf file `#` starts a comment and a line break ends the line: the rest would be lost.
if (index(s, '#') >= 0 || index(s, '\n') >= 0 || index(s, '\r') >= 0)
return sprintf(_('%s may not contain # or a line break.'), name);
// Text between tags is skipped by both parsers.
for (let a = index(s, '<'); a >= 0; a = index(s, '<')) {
let b = index(substr(s, a), '>');
if (b < 0)
return sprintf(_('%s has a tag that is not closed with >.'), name);
let tag = substr(s, a + 1, b - 1);
if (!itag_ok(tag))
return sprintf(_('%s: <%s> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>.'),
name, length(tag) > 24 ? `${substr(tag, 0, 24)}…` : tag);
s = substr(s, a + b + 1);
}
return null;
}
/** Signature packets I1-I5: their tags, and all of them in one device's configuration (one QR code). */
function itags_unsafe(o, errs) {
let total = 0;
for (let k in [ 'i1', 'i2', 'i3', 'i4', 'i5' ]) {
if (!given(o, k))
continue;
total += length(`${o[k]}`);
let e = itag_error(OBF_CONF[k], `${o[k]}`);
if (e)
push(errs, e);
}
if (total > 2000)
push(errs, sprintf(_('I1-I5 together must be at most 2000 characters, not %d.'), total));
}
/**
* What in disguise values `o` AmneziaWG would refuse, crash on or break
* devices with: what an import, a restore or a hand edit in uci must never
* hand to the kernel (dawnline.backup, dawnline.netifd). Only those rules,
* none of Dawnline's own bounds (obf_errors): a backup the kernel takes stays
* usable. Sentences in the reader's language; [] when the values are safe.
*/
export function obf_unsafe(o) {
o ??= {};
let errs = [];
for (let k, r in OBF_SPEC) {
let v = o[k];
if (v == null || v == '')
continue;
if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1])
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
let num = (k) => given(o, k) ? uint(trim(`${o[k]}`), 65535) : 0;
// 16-bit numbers for the tools; Jmin above Jmax sizes junk past its buffer (kmod #225).
for (let k in [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4' ])
if (num(k) == null)
push(errs, sprintf(_('%s must be a whole number from 0 to 65535.'), OBF_CONF[k]));
if (given(o, 'jmin') && given(o, 'jmax') && num('jmin') != null && num('jmax') != null && num('jmin') > num('jmax'))
push(errs, _('Jmin must not be larger than Jmax.'));
headers_unsafe(o, errs);
// Header protection: a 32-byte key, and every padding at least the 12 bytes of its nonce (the kernel checks).
if (given(o, 'header_protection_key')) {
if (!valid_key(o.header_protection_key))
push(errs, _('The header protection key is not a key.'));
for (let k in [ 's1', 's2', 's3', 's4' ])
if (num(k) != null && num(k) < 12)
push(errs, sprintf(_('%s must be at least 12 with header protection.'), OBF_CONF[k]));
}
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
push(errs, 'jmin > jmax');
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
push(errs, 's1 + 56 = s2');
let hs = {};
for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) {
let v = o[k];
if (v == null || v == '')
continue;
if (!match(v, /^[0-9]+(-[0-9]+)?$/))
push(errs, `${k} must be a number or range`);
else if (hs[v])
push(errs, 'h1-h4 must be distinct');
hs[v] = true;
// 3.1 timers and counts: 0 alone is the kernel's default; a 0 in a range
// would fire at once. Keys are dropped after 180 seconds whatever is set.
for (let k in [ 'rekey_after_time', 'rekey_timeout', 'reject_after_time', 'keepalive_timeout', 'max_handshake_attempts' ]) {
let r = given(o, k) ? uint_range(o[k], 65535) : [ 0, 0 ];
if (!r || (r[0] == 0 && r[1] > 0))
push(errs, sprintf(_('%s must be a number or a range like 5-15, from 1 to 65535.'), OBF_CONF[k]));
else if (k == 'reject_after_time' && r[1] > 180)
push(errs, _('RejectAfterTime must be at most 180 seconds.'));
}
if (given(o, 'content_padding_addition') && !uint_range(o.content_padding_addition, 65535))
push(errs, sprintf(_('%s must be a number or a range like 10-100, up to 65535.'), OBF_CONF.content_padding_addition));
// What both netifd and the .conf parser read as a switch.
for (let k in [ 'random_trailers', 'disable_cookies' ])
if (given(o, k) && index([ 'on', 'off', '1', '0' ], `${o[k]}`) < 0)
push(errs, sprintf(_('%s must be on or off.'), OBF_CONF[k]));
itags_unsafe(o, errs);
return errs;
};
/**
* What is wrong with the disguise values of a server Dawnline sets up: what
* AmneziaWG refuses (obf_unsafe), and Dawnline's own bounds on top (junk that
* stays under the path MTU, a handshake initiation and response that never
* share a size). Its presets pass it. Sentences in the reader's language; []
* when the values are fine.
*/
export function obf_errors(o) {
o ??= {};
let errs = obf_unsafe(o);
for (let k, r in OBF_SPEC) {
let n = given(o, k) ? uint(trim(`${o[k]}`), 65535) : null;
if (n != null && (n < r[0] || n > r[1]))
push(errs, sprintf(_('%s must be from %d to %d.'), OBF_CONF[k], r[0], r[1]));
}
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
push(errs, _('S2 must not be S1 + 56: the handshake initiation and response would have the same size.'));
return errs;
};
/**
* Disguise values `o` as anyone who may read the status sees them: all but
* the header protection key, a secret every device of the server shares
* (with it and the server's public key, captured traffic can be unmasked).
* Devices get it in their own configuration (client_config).
*/
export function obf_public(o) {
let out = { ...(o ?? {}) };
delete out.header_protection_key;
return out;
};
export function allowed_ips(m, srv, p) {
if (p.access == 'lan') {
/*
* Everything but a device's own local network, for a device whose local
* network stays outside the tunnel (lan_bypass): every IPv4 address outside
* the private ranges the access table drops for internet people anyway
* (dawnline.nft PRIVATE4: 10/8, 172.16/12, 192.168/16, 100.64/10,
* 169.254/16, 224/3), and every IPv6 address outside fc00::/7, fe80::/10
* and ff00::/8. Fixed lists (tests/ucode/awg.test.uc proves each is exactly
* that complement); what of the private ranges goes through the tunnel after
* all (DNS, home) is added to them.
*/
export const BYPASS4 = [
'0.0.0.0/5', '8.0.0.0/7', '11.0.0.0/8', '12.0.0.0/6', '16.0.0.0/4', '32.0.0.0/3', '64.0.0.0/3', '96.0.0.0/6',
'100.0.0.0/10', '100.128.0.0/9', '101.0.0.0/8', '102.0.0.0/7', '104.0.0.0/5', '112.0.0.0/4', '128.0.0.0/3', '160.0.0.0/5',
'168.0.0.0/8', '169.0.0.0/9', '169.128.0.0/10', '169.192.0.0/11', '169.224.0.0/12', '169.240.0.0/13', '169.248.0.0/14',
'169.252.0.0/15', '169.255.0.0/16', '170.0.0.0/7', '172.0.0.0/12', '172.32.0.0/11', '172.64.0.0/10', '172.128.0.0/9',
'173.0.0.0/8', '174.0.0.0/7', '176.0.0.0/4', '192.0.0.0/9', '192.128.0.0/11', '192.160.0.0/13', '192.169.0.0/16',
'192.170.0.0/15', '192.172.0.0/14', '192.176.0.0/12', '192.192.0.0/10', '193.0.0.0/8', '194.0.0.0/7', '196.0.0.0/6',
'200.0.0.0/5', '208.0.0.0/4',
];
export const BYPASS6 = [ '::/1', '8000::/2', 'c000::/3', 'e000::/4', 'f000::/5', 'f800::/6', 'fe00::/9', 'fec0::/10' ];
/** An IPv6 address BYPASS6 leaves out: in fc00::/7, fe80::/10 or ff00::/8 (the first 16 bits decide). False for anything else. */
function private6(a) {
let g = ipv6_groups(a)?.[0];
return g != null && ((g & 0xfe00) == 0xfc00 || (g & 0xffc0) == 0xfe80 || (g & 0xff00) == 0xff00);
}
/**
* What a device sends into the tunnel (its AllowedIPs; the server's peer
* line stays its address/32). Home only: the person's home networks, the
* tunnel network or the router's address, and the DNS. Internet: everything,
* or with `dev.lan_bypass` everything but the device's own local network
* (BYPASS4, BYPASS6), every DNS server it is given (IPv4 and IPv6) and for
* home access what Home only gets. Without `dev`, as for a device without
* lan_bypass.
*/
export function allowed_ips(m, srv, p, dev) {
if (p.access != 'lan' && !dev?.lan_bypass)
return [ '0.0.0.0/0', '::/0' ];
let home = () => {
let nets = core.person_home(srv, p).nets;
// With devices reaching each other, the whole tunnel network (the router's
// address is in it); otherwise only the router's own address.
@@ -313,13 +520,27 @@ export function allowed_ips(m, srv, p) {
push(nets, srv.subnet);
else if (a)
push(nets, `${a}/32`);
return nets;
};
let dns = core.client_dns(m, srv, p);
if (p.access == 'lan') {
// The resolver address must be reachable through the tunnel too (not the fallback).
let dns = core.client_dns(m, srv, p)[0];
if (dns)
push(nets, `${dns}/32`);
let nets = home();
if (dns[0])
push(nets, `${dns[0]}/32`);
return net.collapse(nets);
}
return [ '0.0.0.0/0', '::/0' ];
// Every DNS server stays in the tunnel: a private one left out would be
// asked on whatever network the device is on (a public one is in the rest).
let nets = [ ...BYPASS4 ], nets6 = [];
for (let a in dns)
if (ip2int(a) != null)
push(nets, `${a}/32`);
else if (private6(a))
push(nets6, `${a}/128`);
if (p.access == 'both')
push(nets, ...home());
return [ ...net.collapse(nets), ...BYPASS6, ...uniq(nets6) ];
};
@@ -367,14 +588,56 @@ function client_obf(srv, dev) {
return o;
}
/**
* The keep-alive `dev` gets (its own or the server's, core.device_keepalive)
* as [ lo, hi ] seconds; null when it is off (0). With 3.1 (header
* protection: its apps take ranges) jittered over ten seconds like the other
* timers, since a fixed beat would be the one regular thing left. The online
* window follows its upper end (dawnline.live).
*/
export function keepalive_range(srv, dev) {
let k = core.device_keepalive(srv, dev);
if (!(k > 0))
return null;
return srv.obf?.header_protection_key ? [ k, k + 10 ] : [ k, k ];
};
/**
* The longest an idle device goes between two handshakes, in seconds; null
* when its keep-alive is off (an idle device then sends nothing at all). Its
* keep-alive packets are what it sends, and the first one after its key's
* rekey time (RekeyAfterTime, WireGuard's 120 s; past 180 s the key is
* refused anyway) starts a handshake (kmod send.c keep_key_fresh): up to one
* keep-alive past that time, or each keep-alive once they are further apart.
*/
export function idle_handshake(srv, dev) {
let ka = keepalive_range(srv, dev);
if (!ka)
return null;
let rekey = min(uint_range(srv.obf?.rekey_after_time ?? '', 65535)?.[1] || 120, 180);
return ka[0] > rekey ? ka[1] : rekey + ka[1];
};
/**
* keepalive_range() as the apps write it ("25-35", "25"); null when off. The
* .conf and the AmneziaVPN key carry the same text (AmneziaVPN hands it on as
* written, ranges included).
*/
function keepalive_text(srv, dev) {
let r = keepalive_range(srv, dev);
if (!r)
return null;
return r[0] == r[1] ? `${r[0]}` : `${r[0]}-${r[1]}`;
}
export function client_config(m, dev) {
let p = m.people[dev.person];
let srv = p ? m.servers[p.server] : null;
if (!srv)
return null;
let host = core.endpoint_host(m, srv);
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
let allowed = allowed_ips(m, srv, p);
let ep = index(host, ':') >= 0 && substr(host, 0, 1) != '[' ? `[${host}]` : host;
let allowed = allowed_ips(m, srv, p, dev);
let dns = core.client_dns(m, srv, p);
let mtu = core.device_mtu(srv, dev);
let lines = [ '[Interface]' ];
@@ -396,10 +659,9 @@ export function client_config(m, dev) {
push(lines, `PresharedKey = ${dev.preshared_key}`);
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
push(lines, `Endpoint = ${ep}:${srv.port}`);
// With 3.1 (its apps take ranges) the keep-alive is jittered like the
// other timers; a fixed beat would be the one regular thing left.
if (srv.keepalive > 0)
push(lines, `PersistentKeepalive = ${srv.obf.header_protection_key ? `${srv.keepalive}-${srv.keepalive + 10}` : srv.keepalive}`);
let keepalive = keepalive_text(srv, dev);
if (keepalive)
push(lines, `PersistentKeepalive = ${keepalive}`);
return {
name: dev.name,
person: p.name,
@@ -419,7 +681,7 @@ export function client_config(m, dev) {
client_pub_key: dev.public_key,
psk_key: dev.preshared_key,
server_pub_key: srv.public_key,
persistent_keep_alive: `${srv.keepalive}`,
persistent_keep_alive: keepalive ?? '0',
obfuscation: obf,
},
};
@@ -443,12 +705,63 @@ export function netifd_options(srv) {
};
for (let k in core.OBF_KEYS)
o[`awg_${k}`] = srv.obf[k];
// DisableCookies is the devices' alone (their .conf and key keep it): on
// the server it would turn off WireGuard's own defence against a flood of
// handshakes (cookie replies and a per-address limit, only ever under
// load), and anyone who held a configuration could keep both cores busy.
// Null takes it off an interface that had it.
o.awg_disable_cookies = null;
return o;
};
/** Person states whose devices stay in the tunnel: active, and the limits the portal explains. */
export const SOFT_STATES = [ 'active', 'quota', 'hours' ];
/**
* The devices sync_peers() loads into server `sid`'s tunnel, in the model's
* order (an empty list when none). Pure: the model and the people's states
* (apply.states_for). Health and the agent compare a running tunnel with it.
*/
export function tunnel_devices(m, sid, states) {
let out = [];
let own = m.servers?.[sid]?.public_key;
for (let did, d in m.devices) {
let p = m.people[d.person];
// One malformed line makes syncconf refuse the whole server: such a device
// stays out (Health's Data check names it), and so does one with the
// server's own key, which the kernel silently ignores (it would look
// missing for ever). Over the data limit or outside the allowed hours the
// tunnel stays: the access table blocks everything but the portal, which
// says why (a silent handshake failure would look like a broken VPN).
if (p && p.server == sid && !d.disabled && index(SOFT_STATES, states[p.id]) >= 0 && valid_key(d.public_key) && ip2int(d.address) != null &&
(!own || d.public_key != own))
push(out, d);
}
return out;
};
/**
* How the peers dump() read on `ifname` differ from the devices that belong
* there (tunnel_devices): { loaded, missing, extra }, counted by key, not by
* number (a stale peer standing in for a missing one would make the numbers
* match). Pure.
*/
export function peer_diff(devs, dmp, ifname) {
let want = {};
for (let d in devs)
want[d.public_key] = true;
let loaded = 0, extra = 0, found = 0;
for (let k, p in dmp.peers)
if (p.ifname == ifname) {
loaded++;
if (want[k])
found++;
else
extra++;
}
return { loaded, missing: length(keys(want)) - found, extra };
};
/** Push the peer list of every server to the kernel without restarting it. */
export function sync_peers(m, states) {
ensure_dir(RUN_DIR);
@@ -462,15 +775,7 @@ export function sync_peers(m, states) {
continue;
}
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
for (let did, d in m.devices) {
let p = m.people[d.person];
// One malformed line makes syncconf refuse the whole server: such a device
// stays out (Health's Data check names it). Over the data limit or
// outside the allowed hours the tunnel stays: the access table blocks
// everything but the portal, which says why (a silent handshake failure
// would look like a broken VPN).
if (!p || p.server != id || d.disabled || index(SOFT_STATES, states[p.id]) < 0 || !valid_key(d.public_key) || ip2int(d.address) == null)
continue;
for (let d in tunnel_devices(m, id, states)) {
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
if (d.preshared_key)
push(lines, `PresharedKey = ${d.preshared_key}`);
@@ -482,43 +787,88 @@ export function sync_peers(m, states) {
unlink(f);
res[id] = r.code == 0 ? 'ok' : trim(r.out);
if (r.code != 0)
slog('awg', 'error', "couldn't load devices into the tunnel", trim(r.out), srv.name);
slog('awg', 'error', L_("couldn't load devices into the tunnel"), trim(r.out), srv.name);
}
return res;
};
/**
* Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
* Lines are told apart by their shape, not their length (each AmneziaWG
* generation adds fields to the interface line): an interface line carries
* its private and public key and a port, a peer line the peer's key, a
* preshared key or "(none)" and an endpoint. The tool fails when any one
* interface can't be read, but still prints the others: with `wanted` (the
* ifnames that matter) `ok` means those were all read, so another tunnel's
* trouble is not ours.
/** The interface's index while it exists (a new one each time netifd sets the tunnel up), else null. */
function ifindex(ifname) {
let s = trim(readfile(`/sys/class/net/${ifname}/ifindex`) ?? '');
return s != '' ? +s : null;
}
/*
* One interface's `awg show <ifname> dump` into `out` (see dump()). Lines are
* told apart by their shape, not their length (each AmneziaWG generation adds
* fields to the interface line): an interface line carries its private and
* public key and a port, a peer line the peer's key, a preshared key or
* "(none)" and an endpoint. Unlike `show all`, the lines have no ifname.
*/
export function dump(wanted) {
let r = sh('awg show all dump');
let out = { ok: r.code == 0, ifaces: {}, peers: {} };
for (let line in split(r.out, '\n')) {
let f = split(line, '\t');
if (length(f) < 5 || !valid_key(f[1]))
continue;
if (valid_key(f[2]) && match(f[3] ?? '', /^[0-9]+$/))
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
else if (length(f) >= 9 && (f[2] == '(none)' || valid_key(f[2]))) {
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],
};
}
function read_iface(out, ifname) {
// Read around the call: a link set up again in between gave counters of either one.
let before = ifindex(ifname);
// Not there (a tunnel netifd could not bring up, AmneziaWG gone after an
// upgrade): no process to learn it. One that appears is read next time.
if (before == null) {
out.reads[ifname] = 'down';
return;
}
if (!out.ok && type(wanted) == 'array')
out.ok = length(filter(wanted, (n) => !out.ifaces[n])) == 0;
let r = sh(`awg show ${q(ifname)} dump`);
let ix = ifindex(ifname);
let iface = null, peers = {};
if (r.code == 0)
for (let line in split(r.out, '\n')) {
let f = split(line, '\t');
if (length(f) < 4 || !valid_key(f[0]))
continue;
let key2 = valid_key(f[1]);
if (key2 && match(f[2], DIGITS))
iface = { public_key: f[1], port: +f[2], ifindex: ix };
else if (length(f) >= 8 && (key2 || f[1] == '(none)'))
peers[f[0]] = {
ifname,
endpoint: f[2] == '(none)' ? '' : f[2],
handshake: +f[4],
rx: +f[5],
tx: +f[6],
};
}
let read = iface != null;
// Gone during the read: its peers and their counters are gone with it.
if (ix == null) {
out.reads[ifname] = 'down';
return;
}
if (!read || ix != before) {
out.reads[ifname] = 'error';
out.ok = false;
return;
}
out.reads[ifname] = 'read';
out.ifaces[ifname] = iface;
for (let k, p in peers)
out.peers[k] = p;
}
/**
* Dawnline's own tunnels, one `awg show <ifname> dump` each for `ifnames`
* (live.tunnel_ifnames): never `all`, so another AmneziaWG interface on the
* router (a client tunnel with long I1-I5, say) neither slows the 1-second
* watcher down nor has its keys read. Returns { ok, reads: { ifname: 'read' |
* 'down' | 'error' }, ifaces: { ifname: { public_key, port, ifindex } },
* peers: { pubkey: { ifname, endpoint, handshake, rx, tx } } }, with only
* what was read in `ifaces` and `peers`:
* down the interface does not exist (/sys/class/net has no such link;
* no process is started for it): its peers and counters are gone
* error it exists but could not be read (or was set up again during the
* read): that says nothing about its peers
* `ok` is false when any of them is 'error' (true for an empty list).
*/
export function dump(ifnames) {
let out = { ok: true, reads: {}, ifaces: {}, peers: {} };
for (let ifn in ifnames ?? [])
read_iface(out, ifn);
return out;
};
@@ -528,6 +878,72 @@ export function server_state(srv) {
return { up: !!st?.up, uptime: st?.uptime ?? 0 };
};
/* ---------- why a tunnel is kept down ---------- */
/*
* dawnline.netifd keeps a server's tunnel down for a reason, kept per server
* in core.BLOCKED and loaded as `srv.blocked`. apply writes it, at boot and
* from the agent with no language, so it holds a code and its values, made
* into text when read:
* { code: 'ifname', ifname } the interface name is invalid
* { code: 'taken', ifname } network.<ifname> exists and isn't Dawnline's
* { code: 'disguise', need, installed } obf_unsupported()
* { code: 'disguise_invalid' } obf_unsafe() finds values AmneziaWG refuses
* (said again from the server's values when read)
* Files written by older versions hold the English fragment ("has an invalid
* interface name …"), shown as it is.
*/
/** A reason as the service log says it after the server's name: English, like every log line. */
export function blocked_note(r) {
if (type(r) != 'object')
return `${r}`;
if (r.code == 'ifname')
return sprintf(L_('has an invalid interface name "%s"'), r.ifname);
if (r.code == 'taken')
return sprintf(L_("can't use the network interface %s: it exists and isn't Dawnline's"), r.ifname);
if (r.code == 'disguise')
return r.installed ? sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: %s)'), r.need, r.installed)
: sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: none)'), r.need);
if (r.code == 'disguise_invalid')
return L_('is kept down: its disguise has values AmneziaWG cannot take');
return L_('is kept down');
};
/** What to do about a reason (blocked_note), for the service log's details. */
export function blocked_fix(r) {
if (r?.code == 'disguise')
return L_('Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
if (r?.code == 'disguise_invalid')
return L_('Choose a disguise on the Server page: it replaces the values set by hand.');
return L_('Choose another interface name in the server settings.');
};
/**
* Why the server's tunnel is kept down (`srv.blocked`), as a sentence with
* its name in the reader's language: what the admin UI shows. Null when it
* is not kept down.
*/
export function blocked_text(srv) {
let r = srv?.blocked;
if (!r)
return null;
if (type(r) != 'object')
return `${srv.name} ${r}.`;
if (r.code == 'ifname')
return sprintf(_('%s has an invalid interface name "%s".'), srv.name, r.ifname);
if (r.code == 'taken')
return sprintf(_("%s can't use the network interface %s: it exists and isn't Dawnline's."), srv.name, r.ifname);
if (r.code == 'disguise')
return r.installed
? sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: %s).'), srv.name, r.need, r.installed)
: sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: none).'), srv.name, r.need);
// Which values, from the server's own (the reason is kept as a code).
if (r.code == 'disguise_invalid')
return trim(sprintf(_('%s is kept down: its disguise has values AmneziaWG cannot take. %s'), srv.name, join(' ', obf_unsafe(srv.obf))));
return sprintf(_('%s is kept down.'), srv.name);
};
/* ---------- watchdog ---------- */
/** Why a tunnel is down, from netifd and the last related syslog lines. */
@@ -553,19 +969,20 @@ export function probes(m, ctx) {
// AmneziaWG itself first: without it no tunnel can run (they come back on the next pass).
// Missing packages and an unknown protocol are reported once; only the module can be loaded here.
let st = state();
let base = { id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', back: 'is ready again' };
let base = { id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', back: L_('is ready again') };
if (!st.tools || !st.kmod) {
push(out, { ...base, ok: false, repair: null,
problem: `${st.tools ? "kernel module isn't" : "isn't"} installed: no tunnel can run — install it in Dawnline → Components`,
detail: () => `Missing: ${join(', ', st.missing)}.` });
problem: st.tools ? L_("kernel module isn't installed: no tunnel can run - install it in Dawnline → Components")
: L_("isn't installed: no tunnel can run - install it in Dawnline → Components"),
detail: () => sprintf(L_('Missing: %s.'), join(', ', st.missing)) });
return out;
}
push(out, { ...base, ok: st.loaded && st.handler,
problem: !st.loaded ? "kernel module isn't loaded" : "isn't known to the network service — restart the network or reboot",
problem: !st.loaded ? L_("kernel module isn't loaded") : L_("isn't known to the network service - restart the network or reboot"),
detail: !st.loaded
? () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4")
: () => 'netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.',
repair: !st.loaded ? { what: 'loading it', run: () => system('modprobe amneziawg >/dev/null 2>&1') } : null,
: () => L_('netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.'),
repair: !st.loaded ? { what: L_('loading it'), run: () => system('modprobe amneziawg >/dev/null 2>&1') } : null,
});
// Without the protocol handler ifup cannot work: the tunnels are not probed (or restarted) one by one.
if (st.loaded && !st.handler)
@@ -574,13 +991,13 @@ export function probes(m, ctx) {
// A tunnel Dawnline may not set up (dawnline.netifd) is reported, never restarted:
// an interface of the same name that isn't Dawnline's may be your LAN.
let own = core.valid_ifname(srv.ifname) ? ctx.owner?.(srv.ifname) : null;
let why = srv.blocked ?? (!core.valid_ifname(srv.ifname) ? `has an invalid interface name "${srv.ifname}"`
: own != null && own != srv.id ? `can't use the network interface ${srv.ifname}: it exists and isn't Dawnline's` : null);
let why = srv.blocked ?? (!core.valid_ifname(srv.ifname) ? { code: 'ifname', ifname: srv.ifname }
: own != null && own != srv.id ? { code: 'taken', ifname: srv.ifname } : null);
if (why) {
push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null,
problem: why, back: 'AmneziaWG is running again',
detail: () => 'Choose another interface name in the server settings.',
problem: blocked_note(why), back: L_('AmneziaWG is running again'),
detail: () => blocked_fix(why),
});
continue;
}
@@ -588,10 +1005,11 @@ export function probes(m, ctx) {
let up = !!s?.up;
push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: up && ctx.udp_listening(srv.port),
problem: !s ? 'AmneziaWG is missing from the router' : !up ? "AmneziaWG isn't running" : `AmneziaWG isn't accepting connections on port ${srv.port}`,
back: `AmneziaWG is running again · accepting connections on port ${srv.port}`,
problem: !s ? L_('AmneziaWG is missing from the router') : !up ? L_("AmneziaWG isn't running")
: sprintf(L_("AmneziaWG isn't accepting connections on port %d"), srv.port),
back: sprintf(L_('AmneziaWG is running again · accepting connections on port %d'), srv.port),
detail: () => iface_errors(srv.ifname),
repair: s ? { what: 'restarting it', run: () => system(`ifup ${q(srv.ifname)}`) } : { what: 'setting it up again', run: ctx.reapply },
repair: s ? { what: L_('restarting it'), run: () => system(`ifup ${q(srv.ifname)}`) } : { what: L_('setting it up again'), run: ctx.reapply },
});
}
return out;
@@ -600,6 +1018,9 @@ export function probes(m, ctx) {
/* ---------- issued configurations ---------- */
const ISSUED = `${DATA_DIR}/issued.json`;
// The lines a fingerprint leaves out. A module constant, compiled once, not
// for each line of each device's configuration.
const DEVICE_OWN = /^(PrivateKey|Jc|Jmin|Jmax) /;
function fnv32(str) {
let h = 2166136261;
@@ -616,7 +1037,7 @@ function fnv32(str) {
*/
export function config_fingerprint(m, dev) {
let c = dev ? client_config(m, dev) : null;
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^(PrivateKey|Jc|Jmin|Jmax) /)))) : null;
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, DEVICE_OWN)))) : null;
};
/** Device id → fingerprint of the configuration last shown or downloaded. */
@@ -1,8 +1,12 @@
// Dawnline — where AmneziaWG comes from: the awg-openwrt projects publish
// builds per OpenWrt release and target (the kernel module must match the
// firmware). Used by the updater and the Components RPCs.
// 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 } from 'fs';
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';
@@ -36,19 +40,52 @@ export function firmware() {
/** 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).
* 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) {
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(),
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.
@@ -88,6 +125,42 @@ export function gen(version) {
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 = {};
@@ -1,7 +1,8 @@
// 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.
// 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';
@@ -9,10 +10,12 @@ 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`;
/**
@@ -38,9 +41,10 @@ const MAX_UNPACKED = 16 * 1024 * 1024;
/**
* 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 and a
* unique port, and the people and devices must be consistent
* (core.model_errors). [] when it can be used.
* 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);
@@ -51,17 +55,16 @@ export function config_errors(c) {
let internal = values(net.INTERNAL);
let ifnames = {}, ports = {}, subnets = [];
for (let id, srv in m.servers) {
let who = `Server ${srv.name}`;
for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ]))
push(errs, `${who}: ${e}`);
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, `${who}: interface ${srv.ifname} is also used by ${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, `${who}: ${srv.ifname} is one of the router's own network interfaces.`);
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, `${who}: UDP ${srv.port} is also used by ${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);
@@ -75,10 +78,10 @@ function check_config_dir(dir) {
// 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.');
die(_('The configuration in this file cannot be read.'));
let errs = config_errors(c);
if (length(errs))
die(`This configuration can't be used: ${join(' ', errs)}`);
die(sprintf(_("This configuration can't be used: %s"), join(' ', errs)));
}
/** A private scratch directory under RUN_DIR (the caller removes it). */
@@ -129,7 +132,8 @@ export function backup_create(reason, keep) {
let r = sh(`tar -czf ${q(tmp)} -C / ${files}`);
if (r.code != 0 || !rename(tmp, `${BACKUP_DIR}/${name}`)) {
unlink(tmp);
die(`Backup failed: ${trim(r.out) || 'the archive could not be written (is the flash full?)'}`);
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 = {};
@@ -144,10 +148,10 @@ export function backup_create(reason, keep) {
function backup_path(name) {
if (!match(name ?? '', NAME))
die('Invalid backup name.');
die(_('Invalid backup name.'));
let p = `${BACKUP_DIR}/${name}`;
if (!file_exists(p))
die('Backup not found.');
die(_('Backup not found.'));
return p;
}
@@ -158,24 +162,24 @@ function backup_path(name) {
function check_archive(path) {
let r = sh(`tar -tvzf ${q(path)}`);
if (r.code != 0)
die('Not a valid backup archive.');
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(`Unexpected entry in backup: ${name}`);
die(sprintf(_('Unexpected entry in backup: %s'), name));
if (index(FILES, name) < 0)
die(`Unexpected file in backup: ${name}`);
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.');
die(_('Backup does not contain /etc/config/dawnline.'));
if (total > MAX_UNPACKED)
die('Backup is too large.');
die(_('Backup is too large.'));
}
/**
@@ -190,7 +194,7 @@ function install_files(dir) {
for (let f in FILES) {
let data = readfile(`${dir}/${f}`);
if (data != null && !write_file(`/${f}`, data, 0o600))
die(`Couldn't write /${f}. Is the flash full?`);
die(sprintf(_("Couldn't write %s. Is the flash full?"), `/${f}`));
}
}
catch (e) {
@@ -208,7 +212,7 @@ export function backup_restore(name, path) {
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.');
die(_('Not a valid backup archive.'));
check_config_dir(`${dir}/etc/config`);
backup_create('pre-restore', name);
install_files(dir);
@@ -238,7 +242,7 @@ export function backup_read(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.');
die(_('Upload is empty or too large.'));
ensure_dir(RUN_DIR);
let tmp = `${RUN_DIR}/upload.tar.gz`;
write_file(tmp, data);
@@ -273,23 +277,23 @@ export function export_json() {
/** 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.');
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(`Invalid section ${s?.['.name']}.`);
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(`Invalid option ${k}.`);
die(sprintf(_('Invalid option %s.'), k));
if (type(v) == 'array')
for (let x in v) {
if (type(x) != 'string')
die(`Invalid option ${k}.`);
die(sprintf(_('Invalid option %s.'), k));
push(lines, `\tlist ${k} '${esc(x)}'`);
}
else
@@ -317,6 +321,6 @@ export function import_json(data) {
let ok = write_file('/etc/config/dawnline', text, 0o600);
unlock(l);
if (!ok)
die("Couldn't write /etc/config/dawnline. Is the flash full?");
die(sprintf(_("Couldn't write %s. Is the flash full?"), '/etc/config/dawnline'));
return apply.apply();
};
@@ -4,9 +4,10 @@
import { cursor } from 'uci';
import {
valid_name, valid_key, valid_host, valid_date, slugify, host_label, ucut, NAME_RULE, parse_cidr, cidr_overlaps, int2ip, ip2int,
valid_name, valid_device_name, DEVICE_NAME_MAX, valid_key, valid_host, valid_iface, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
} from 'dawnline.util';
import { _, N_ } from 'dawnline.i18n';
import * as net from 'dawnline.net';
import * as schema from 'dawnline.schema';
import { policy as updates_policy } from 'dawnline.updates';
@@ -198,6 +199,13 @@ export function load(c) {
created: toint(r.created, 0),
created_by: r.created_by ?? 'admin',
disabled: bool(r.disabled, false),
// The device's own link values (admin only): 0 / null = the server's
// (device_mtu, device_keepalive). Out of range is kept as read, so
// model_errors can name it; the configuration then uses the server's.
mtu: toint(r.mtu, 0),
keepalive: r.keepalive == null || r.keepalive == '' ? null : toint(r.keepalive, null),
// Its own local network stays outside the tunnel (awg.allowed_ips).
lan_bypass: bool(r.lan_bypass, false),
};
m.devices[id] = d;
if (m.people[d.person])
@@ -366,18 +374,40 @@ export function alloc_address(m, srv) {
*/
const AUTO_MTU = 1380;
const MOBILE_MTU = 1280;
/** What an MTU set by hand may be (the server's and a device's alike). */
export const MTU_RANGE = [ 1280, 1500 ];
/** What a keep-alive set by hand may be, in seconds (0 = off). */
export const KEEPALIVE_RANGE = [ 0, 600 ];
function in_range(n, r) {
return type(n) == 'int' && n >= r[0] && n <= r[1];
}
/** The server's tunnel MTU: the one set, or automatic for its disguise. */
export function tunnel_mtu(srv) {
return srv.mtu || max(MOBILE_MTU, AUTO_MTU - toint(srv.obf?.s4, 0));
};
/** The MTU a device's configuration carries: the tunnel's, at most 1280 for phones and tablets. */
/**
* The MTU a device's configuration carries: the device's own when the admin
* set one, else the tunnel's, at most 1280 for phones and tablets.
*/
export function device_mtu(srv, dev) {
if (in_range(dev.mtu, MTU_RANGE))
return dev.mtu;
let mtu = tunnel_mtu(srv);
return index(MOBILE_KINDS, dev.kind) >= 0 ? min(mtu, MOBILE_MTU) : mtu;
};
/**
* The keep-alive a device's configuration carries, in seconds (0 = off): the
* device's own when the admin set one, else the server's. Both ends never
* have to agree on it (the server's peers carry none), so it is the device's.
*/
export function device_keepalive(srv, dev) {
return in_range(dev?.keepalive, KEEPALIVE_RANGE) ? dev.keepalive : srv.keepalive;
};
export function endpoint_host(m, srv) {
return srv.endpoint || m.settings.portal_host || '';
};
@@ -481,35 +511,35 @@ export function new_code() {
export function create_person(c, m, a) {
if (!valid_name(a.name))
fail(NAME_RULE);
fail(name_rule());
// The id is a UCI section name: letters, digits and underscores only (a dash
// makes uci drop the section). Repeated names get _2, _3, …
let base = replace(a.slug ?? slugify(a.name), /-/g, '_');
if (!match(base, /^[a-z0-9_]{1,32}$/))
fail('The id may use lowercase letters, digits and underscores.');
fail(_('The id may use lowercase letters, digits and underscores.'));
// Any kind of section (store.id_taken, which imports this module).
let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || m.circles[id] ||
index([ 'settings', 'main', 'global', 'defaults' ], id) >= 0;
let slug = base;
for (let n = 2; taken(slug); n++) {
if (n > 99)
fail(`"${base}" is already taken.`);
fail(sprintf(_('"%s" is already taken.'), base));
slug = `${substr(base, 0, 28)}_${n}`;
}
let srv_id = a.server ?? keys(m.servers)[0];
if (!m.servers[srv_id])
fail('Set up a server first.');
fail(_('Set up a server first.'));
let access = a.access ?? 'internet';
if (index(ACCESS, access) < 0)
fail('Access must be lan, internet or both.');
fail(_('Access must be lan, internet or both.'));
let limit = toint(a.device_limit, m.settings.default_device_limit);
if (limit < 1 || limit > 32)
fail('Device limit must be between 1 and 32.');
fail(_('Device limit must be between 1 and 32.'));
if (a.expires && !valid_date(a.expires))
fail('End date must be YYYY-MM-DD.');
fail(_('End date must be YYYY-MM-DD.'));
let quota = num(a.quota_gb, 0);
if (quota < 0 || quota > 100000)
fail('Monthly data must be a positive number of GB.');
fail(_('Monthly data must be a positive number of GB.'));
c.set(CONFIG, slug, 'person');
c.set(CONFIG, slug, 'server', srv_id);
@@ -535,52 +565,53 @@ export function create_person(c, m, a) {
export function update_person(c, m, id, a) {
let p = m.people[id];
if (!p)
fail('Unknown person.');
fail(_('Unknown person.'));
let set = (k, v) => (v == null || v == '') ? c.delete(CONFIG, id, k) : c.set(CONFIG, id, k, `${v}`);
if (a.name != null) {
if (!valid_name(a.name))
fail(NAME_RULE);
fail(name_rule());
set('name', trim(a.name));
}
if (a.access != null) {
if (index(ACCESS, a.access) < 0)
fail('Access must be lan, internet or both.');
fail(_('Access must be lan, internet or both.'));
set('access', a.access);
}
if (a.device_limit != null) {
let n = toint(a.device_limit, 0);
if (n < 1 || n > 32)
fail('Device limit must be between 1 and 32.');
fail(_('Device limit must be between 1 and 32.'));
let have = length(p.devices);
if (n < have)
fail(`${p.name} already has ${have} devices. Remove one first to lower the limit to ${n}.`);
fail(sprintf(N_(have, '%s already has %d device. Remove one first to lower the limit to %d.',
'%s already has %d devices. Remove one first to lower the limit to %d.'), p.name, have, n));
set('device_limit', n);
}
if (a.expires != null) {
if (a.expires != '' && !valid_date(a.expires))
fail('End date must be YYYY-MM-DD.');
fail(_('End date must be YYYY-MM-DD.'));
set('expires', a.expires);
}
if (a.expire_action != null) {
if (index([ 'pause', 'notify', 'remove' ], a.expire_action) < 0)
fail('Unknown end action.');
fail(_('Unknown end action.'));
set('expire_action', a.expire_action == 'pause' ? '' : a.expire_action);
}
if (a.dns_mode != null) {
if (index([ 'device', 'home' ], a.dns_mode) < 0)
fail('Unknown DNS choice.');
fail(_('Unknown DNS choice.'));
set('dns_mode', a.dns_mode == 'device' ? '' : a.dns_mode);
}
if (a.expire_warn != null) {
let n = toint(a.expire_warn, -1);
if (n < 0 || n > 60)
fail('Warning must be 0-60 days.');
fail(_('Warning must be 0-60 days.'));
set('expire_warn', n == 3 ? '' : n);
}
if (a.quota_gb != null) {
let q = num(a.quota_gb, -1);
if (a.quota_gb != '' && (q < 0 || q > 100000))
fail('Data limit must be a positive number of GB.');
fail(_('Data limit must be a positive number of GB.'));
set('quota_gb', q > 0 ? q : '');
}
if (a.quota_period != null)
@@ -588,13 +619,13 @@ export function update_person(c, m, id, a) {
if (a.bonus_gb != null) {
let b = num(a.bonus_gb, -1);
if (b < 0 || b > 100000)
fail('Extra data must be a positive number of GB.');
fail(_('Extra data must be a positive number of GB.'));
set('bonus_gb', b > 0 ? b : '');
set('bonus_month', b > 0 ? month_key() : '');
}
if (a.hours != null) {
if (a.hours != '' && !parse_hours(a.hours))
fail('Hours must look like 07:00-23:00.');
fail(_('Hours must look like 07:00-23:00.'));
set('hours', a.hours);
}
if (a.note != null)
@@ -602,7 +633,7 @@ export function update_person(c, m, id, a) {
if (type(a.services) == 'array') {
for (let sid in a.services)
if (!m.services[sid])
fail(`Unknown service ${sid}.`);
fail(sprintf(_('Unknown service %s.'), sid));
if (length(a.services))
c.set(CONFIG, id, 'service', a.services);
else
@@ -611,7 +642,7 @@ export function update_person(c, m, id, a) {
if (a.circle != null) {
let ci = m.circles[a.circle];
if (a.circle != '' && (!ci || ci.server != p.server))
fail('Unknown circle.');
fail(_('Unknown circle.'));
set('circle', a.circle);
}
// Another server: every device gets an address in its tunnel (so each
@@ -619,13 +650,13 @@ export function update_person(c, m, id, a) {
// server's and go.
if (a.server != null && a.server != '' && a.server != p.server) {
if (!m.servers[a.server])
fail('Unknown server.');
fail(_('Unknown server.'));
set('server', a.server);
p.server = a.server;
for (let did in p.devices) {
let addr = alloc_address(m, m.servers[a.server]);
if (!addr)
fail(`No free address left on ${m.servers[a.server].name}.`);
fail(sprintf(_('No free address left on %s.'), m.servers[a.server].name));
m.devices[did].address = addr;
c.set(CONFIG, did, 'address', addr);
}
@@ -633,7 +664,7 @@ export function update_person(c, m, id, a) {
c.delete(CONFIG, id, 'home_net');
}
if (type(a.home_nets) == 'array') {
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), valid_iface));
if (length(nets))
c.set(CONFIG, id, 'home_net', nets);
else
@@ -647,38 +678,45 @@ export function update_person(c, m, id, a) {
* Add a device for a person. `opts.keys` = { private_key?, public_key,
* preshared_key } from dawnline.awg (or a public key the browser generated).
* `opts.by` is 'admin' or 'portal'; the portal is held to the device limit.
* `opts.lan_bypass` true keeps the device's own local network outside the
* tunnel (awg.allowed_ips).
*/
export function create_device(c, m, person_id, name, kind, opts) {
opts ??= {};
let p = m.people[person_id];
if (!p)
fail('Unknown person.');
fail(_('Unknown person.'));
let srv = m.servers[p.server];
if (!srv)
fail('The person has no server.');
fail(_('The person has no server.'));
name = trim(name ?? '');
if (!valid_name(name))
fail('Enter a device name (up to 48 characters).');
if (!valid_device_name(name))
fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX));
if (index(KINDS, kind) < 0)
kind = 'other';
if (opts.by == 'portal' && length(p.devices) >= p.device_limit)
fail(`Device limit reached (${p.device_limit}).`);
fail(sprintf(_('Device limit reached (%d).'), p.device_limit));
for (let id in p.devices)
if (lc(m.devices[id].name) == lc(name))
fail(`"${name}" already exists.`);
fail(sprintf(_('"%s" already exists.'), name));
let addr = alloc_address(m, srv);
if (!addr)
fail('No free addresses left in the server subnet.');
fail(_('No free addresses left in the server subnet.'));
let k = opts.keys ?? {};
if (!valid_key(k.public_key))
fail('Key generation failed (is amneziawg-tools installed?).');
fail(_('Key generation failed (is amneziawg-tools installed?).'));
for (let o, d in m.devices)
if (d.public_key == k.public_key)
fail('This key is already in use.');
fail(_('This key is already in use.'));
// A server's own key (it is in every configuration): the kernel would silently ignore such a peer.
for (let sid, s in m.servers)
if (s.public_key == k.public_key)
fail(_('This key is already in use.'));
let id = `d_${rand_hex(4)}`;
let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '',
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false };
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false,
mtu: 0, keepalive: null, lan_bypass: opts.lan_bypass === true };
c.set(CONFIG, id, 'device');
c.set(CONFIG, id, 'person', person_id);
c.set(CONFIG, id, 'name', name);
@@ -689,6 +727,8 @@ export function create_device(c, m, person_id, name, kind, opts) {
c.set(CONFIG, id, f, dev[f]);
c.set(CONFIG, id, 'created', `${dev.created}`);
c.set(CONFIG, id, 'created_by', dev.created_by);
if (dev.lan_bypass)
c.set(CONFIG, id, 'lan_bypass', '1');
// Keep the in-memory model consistent for callers that continue.
m.devices[id] = dev;
@@ -699,21 +739,60 @@ export function create_device(c, m, person_id, name, kind, opts) {
export function rename_device(c, m, id, name) {
let d = m.devices[id];
if (!d)
fail('Unknown device.');
fail(_('Unknown device.'));
name = trim(name ?? '');
if (!valid_name(name))
fail('Enter a device name (up to 48 characters).');
if (!valid_device_name(name))
fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX));
for (let o in m.people[d.person]?.devices ?? [])
if (o != id && lc(m.devices[o].name) == lc(name))
fail(`"${name}" already exists.`);
fail(sprintf(_('"%s" already exists.'), name));
c.set(CONFIG, id, 'name', name);
d.name = name;
};
/**
* The admin's link settings of a device: `a` = { mtu?, keepalive?,
* lan_bypass? }, only keys present change; '' takes a number back to the
* server's (0 is a keep-alive of its own: off). Each is in the device's
* configuration alone (the server's peers carry neither), so a change asks
* that device to import again and touches nothing on the router. Returns the
* names of the options that changed.
*/
export function set_device_link(c, m, id, a) {
let d = m.devices[id];
if (!d)
fail(_('Unknown device.'));
let changed = [];
let put = (k, v, was) => {
if (v == was)
return;
if (v == null)
c.delete(CONFIG, id, k);
else
c.set(CONFIG, id, k, `${v}`);
push(changed, k);
};
let number = (v, r, msg) => {
let s = trim(`${v}`);
if (s == '')
return null;
if (!match(s, /^[0-9]{1,4}$/) || +s < r[0] || +s > r[1])
fail(msg);
return +s;
};
if (a.mtu != null)
put('mtu', number(a.mtu, MTU_RANGE, _('MTU must be 1280-1500.')), d.mtu || null);
if (a.keepalive != null)
put('keepalive', number(a.keepalive, KEEPALIVE_RANGE, _('Keep-alive must be 0-600 seconds.')), d.keepalive);
if (a.lan_bypass != null)
put('lan_bypass', a.lan_bypass === true ? 1 : null, d.lan_bypass ? 1 : null);
return changed;
};
export function delete_device(c, m, id) {
let d = m.devices[id];
if (!d)
fail('Unknown device.');
fail(_('Unknown device.'));
c.delete(CONFIG, id);
let p = m.people[d.person];
if (p)
@@ -725,9 +804,9 @@ export function delete_device(c, m, id) {
export function rotate_device(c, m, id, keys) {
let d = m.devices[id];
if (!d)
fail('Unknown device.');
fail(_('Unknown device.'));
if (!valid_key(keys?.public_key) || !keys?.private_key)
fail('Key generation failed.');
fail(_('Key generation failed.'));
c.set(CONFIG, id, 'private_key', keys.private_key);
c.set(CONFIG, id, 'public_key', keys.public_key);
if (keys.preshared_key)
@@ -737,7 +816,7 @@ export function rotate_device(c, m, id, keys) {
export function delete_person(c, m, id) {
let p = m.people[id];
if (!p)
fail('Unknown person.');
fail(_('Unknown person.'));
for (let d in p.devices)
c.delete(CONFIG, d);
c.delete(CONFIG, id);
@@ -757,20 +836,20 @@ export function private_cidr(c) {
export function server_errors(m, srv, others_subnets) {
let errs = [];
if (!valid_ifname(srv.ifname))
push(errs, 'Interface name: 1-12 lowercase letters, digits or _.');
push(errs, _('Interface name: 1-12 lowercase letters, digits or _.'));
if (srv.port < 1 || srv.port > 65535)
push(errs, 'Port must be 1-65535.');
push(errs, _('Port must be 1-65535.'));
let c = parse_cidr(srv.subnet);
if (!c)
push(errs, 'Subnet must look like 10.77.0.0/24.');
push(errs, _('Subnet must look like 10.77.0.0/24.'));
else
for (let o in others_subnets ?? []) {
let oc = parse_cidr(o);
if (oc && cidr_overlaps(c, oc))
push(errs, `Subnet overlaps ${o}.`);
push(errs, sprintf(_('Subnet overlaps %s.'), o));
}
if (srv.endpoint != '' && !valid_host(srv.endpoint))
push(errs, 'Endpoint must be a hostname or IP address.');
push(errs, _('Endpoint must be a hostname or IP address.'));
return errs;
};
@@ -779,61 +858,74 @@ export function server_errors(m, srv, others_subnets) {
* an address outside their server's subnet, the server's own address, a
* prefix on it or one shared with another device (the access sets are keyed
* by address, and one bad peer line makes `awg syncconf` refuse the whole
* server), malformed keys, people and devices pointing at servers, people,
* circles or services that do not exist, and two people with one link. [] when
* it is consistent. Import, restore and Health check it; the runtime sync
* skips what it would reject (dawnline.awg, dawnline.nft).
* server), malformed keys, an MTU or keep-alive of their own out of range,
* people and devices pointing at servers, people, circles or services that do
* not exist, and two people with one link. [] when it is consistent. Import,
* restore and Health check it; the runtime sync skips what it would reject
* (dawnline.awg, dawnline.nft), and a configuration takes the server's value
* for a link value out of range (device_mtu, device_keepalive).
*/
export function model_errors(m) {
let errs = [];
let codes = {}, addrs = {};
for (let id, p in m.people) {
let who = `Person ${p.name}`;
if (p.server != '' && !m.servers[p.server])
push(errs, `${who}: server ${p.server} does not exist.`);
push(errs, sprintf(_('Person %s: server %s does not exist.'), p.name, p.server));
if (p.circle != '' && !m.circles[p.circle])
push(errs, `${who}: circle ${p.circle} does not exist.`);
push(errs, sprintf(_('Person %s: circle %s does not exist.'), p.name, p.circle));
for (let sid in p.services)
if (!m.services[sid])
push(errs, `${who}: home service ${sid} does not exist.`);
push(errs, sprintf(_('Person %s: home service %s does not exist.'), p.name, sid));
if (p.code != '') {
if (codes[p.code])
push(errs, `${who}: has the same personal link as ${codes[p.code]}.`);
push(errs, sprintf(_('Person %s: has the same personal link as %s.'), p.name, codes[p.code]));
codes[p.code] = p.name;
}
}
for (let id, d in m.devices) {
let p = m.people[d.person];
let who = `Device ${d.name}${p ? ` of ${p.name}` : ''}`;
if (!p) {
push(errs, `${who}: person ${d.person} does not exist.`);
push(errs, sprintf(_('Device %s: person %s does not exist.'), d.name, d.person));
continue;
}
let say = (msg, ...args) => push(errs, sprintf(msg, d.name, p.name, ...args));
if (!valid_key(d.public_key))
push(errs, `${who}: the public key is not a key.`);
say(_('Device %s of %s: the public key is not a key.'));
if (d.private_key != '' && !valid_key(d.private_key))
push(errs, `${who}: the private key is not a key.`);
say(_('Device %s of %s: the private key is not a key.'));
if (d.preshared_key != '' && !valid_key(d.preshared_key))
push(errs, `${who}: the preshared key is not a key.`);
say(_('Device %s of %s: the preshared key is not a key.'));
// Its own link values (0 / null: the server's); one out of range is never used.
if (d.mtu && !in_range(d.mtu, MTU_RANGE))
say(_('Device %s of %s: MTU %d is not between 1280 and 1500.'), d.mtu);
if (d.keepalive != null && !in_range(d.keepalive, KEEPALIVE_RANGE))
say(_('Device %s of %s: keep-alive %d is not between 0 and 600 seconds.'), d.keepalive);
let n = ip2int(d.address);
if (n == null) {
push(errs, `${who}: address ${d.address || '(none)'} is not a plain IPv4 address.`);
if (d.address)
say(_('Device %s of %s: address %s is not a plain IPv4 address.'), d.address);
else
say(_('Device %s of %s: address (none) is not a plain IPv4 address.'));
continue;
}
let srv = m.servers[p.server];
// AmneziaWG ignores a peer with the interface's own key (dawnline.awg tunnel_devices leaves it out).
if (srv?.public_key && d.public_key == srv.public_key)
say(_("Device %s of %s: the public key is the server's own."));
let t = srv ? parse_cidr(srv.subnet) : null;
if (t && (n < t.first || n > t.last))
push(errs, `${who}: address ${d.address} is outside ${srv.name}'s tunnel ${srv.subnet}.`);
say(_("Device %s of %s: address %s is outside %s's tunnel %s."), d.address, srv.name, srv.subnet);
else if (t && n == t.first)
push(errs, `${who}: address ${d.address} is the router's own address on ${srv.name}.`);
say(_("Device %s of %s: address %s is the router's own address on %s."), d.address, srv.name);
let key = `${p.server} ${d.address}`;
if (addrs[key])
push(errs, `${who}: address ${d.address} is also used by ${addrs[key]}.`);
addrs[key] = who;
let o = addrs[key];
if (o)
say(_('Device %s of %s: address %s is also used by device %s of %s.'), d.address, o.device, o.person);
addrs[key] = { device: d.name, person: p.name };
}
for (let id, ci in m.circles)
if (!m.servers[ci.server])
push(errs, `Circle ${ci.name}: server ${ci.server} does not exist.`);
push(errs, sprintf(_('Circle %s: server %s does not exist.'), ci.name, ci.server));
return errs;
};
@@ -854,7 +946,7 @@ export function renumber_server(c, m, srv, subnet) {
for (let did in p.devices) {
let addr = alloc_address(m, srv);
if (!addr)
fail(`${subnet} has no room for every device on ${srv.name}.`);
fail(sprintf(_('%s has no room for every device on %s.'), subnet, srv.name));
m.devices[did].address = addr;
c.set(CONFIG, did, 'address', addr);
}
@@ -890,7 +982,7 @@ export function wan_forwards(zone, proto) {
c.load('firewall');
let out = [];
c.foreach('firewall', 'redirect', (r) => {
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
if (substr(r['.name'], 0, 9) == 'dawnline_' || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
return;
// fw4's default is "tcp udp".
let protos = split(type(r.proto) == 'array' ? join(' ', r.proto) : r.proto ?? 'tcp udp', /[ ,]+/);
@@ -13,6 +13,7 @@ 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() {
@@ -23,7 +24,8 @@ export function ready() {
export function need_awg() {
if (!awg.installed()) {
let miss = awg.state().missing ?? [];
die(`AmneziaWG is not installed${length(miss) ? ` (${join(', ', miss)})` : ''}: install it in Dawnline → Components.`);
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.'));
}
};
@@ -31,17 +33,21 @@ export function need_awg() {
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.');
die(opts.person != null ? _('Device not found.') : _('Unknown device.'));
if (opts.by == 'portal' && d.disabled)
die('The admin has turned this device off.');
die(_('The admin has turned this device off.'));
return d;
}
/** New device with fresh keys (or the browser's public key): { id, config }. */
/**
* 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) }));
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 });
@@ -50,14 +56,21 @@ export function add(person, name, kind, opts) {
};
/**
* Rename and/or turn a device off or on (`ch` = { name?, disabled? }); only
* the admin turns devices off. Returns the runtime sync.
* 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.');
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 };
@@ -69,18 +82,28 @@ export function update(id, ch, opts) {
else
c.delete(core.CONFIG, id, 'disabled');
}
if (link)
linked = core.set_device_link(c, m, id, ch);
return was;
});
let r = apply.sync();
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. */
export function rotate(id, opts) {
/*
* 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) => {
@@ -102,14 +125,15 @@ export function rotate(id, opts) {
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): 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, as rotate.
* 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 ??= {};
@@ -126,7 +126,7 @@ export function sync(m, dry) {
let stale = [];
c.foreach('firewall', null, (s) => {
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
if (substr(s['.name'], 0, 9) == 'dawnline_' && !want[s['.name']])
push(stale, s['.name']);
});
for (let s in stale) {
@@ -170,6 +170,9 @@ export function drift(m) {
};
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);
@@ -184,8 +187,7 @@ 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')) {
// "1000: from all fwmark 0x1 lookup 100", or "fwmark 0x1/0xff".
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/);
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] };
@@ -8,6 +8,7 @@
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/' ];
@@ -54,11 +55,11 @@ function api_json(url) {
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.');
die(_('GitHub API rate limit reached: try again in an hour.'));
if (r.status == 404)
return null;
if (r.status >= 400)
die(`GitHub: ${j?.message ?? `HTTP ${r.status}`}`);
die(sprintf(_('GitHub: %s'), j?.message ?? `HTTP ${r.status}`));
return j;
}
@@ -209,18 +210,18 @@ export function download(url, dest, o) {
for (let i, u in tries) {
let host = replace(u, /^https:\/\/([^\/]+)\/.*$/, '$1');
if (i > 0)
o.log?.(`Trying mirror ${host}`);
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?.(`Warning: ${host} sent a file that does not match GitHub's sha256, discarded`);
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');
o.log?.(_('GitHub did not answer, trying mirrors'));
}
return null;
};
@@ -1,8 +1,10 @@
// 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';
@@ -43,19 +45,27 @@ export function needs() {
};
};
// " 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')) {
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
let m = match(line, /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /);
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.
@@ -63,10 +73,10 @@ export function udp_bound() {
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), /[ \t]+/);
let f = split(trim(line), BLANKS);
if (f[0] != proto && f[0] != `${proto}6`)
continue;
let m = match(f[3] ?? '', /:([0-9]+)$/);
let m = match(f[3] ?? '', PORT_SUFFIX);
let owner = split(f[length(f) - 1], '/');
if (!m || !owner[1] || out[m[1]])
continue;
@@ -174,43 +184,12 @@ export function foreign_subnets() {
/*
* 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"). Longest names
* first; a server's name after the check name is kept.
* 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).
*/
const PROBLEM = [
[ 'AmneziaWG answers reach devices', 'AmneziaWG answers may not reach devices' ],
[ 'AmneziaWG devices loaded', 'Not every device is loaded into AmneziaWG' ],
[ 'AmneziaWG subnet is unique', 'AmneziaWG subnet overlaps another network' ],
[ 'AmneziaWG port is free', 'AmneziaWG port is taken' ],
[ 'AmneziaWG installed', 'AmneziaWG isn’t ready' ],
[ 'AmneziaWG firewall', 'AmneziaWG firewall rules are missing' ],
[ 'AmneziaWG running', 'AmneziaWG is down' ],
[ 'Portal answers reach visitors', 'Portal answers may not reach visitors' ],
[ 'Portal address points here', 'Portal address doesn’t point here' ],
[ 'Portal address', 'Portal address isn’t set' ],
[ 'Portal certificate', 'Portal certificate needs attention' ],
[ 'Personal portal', 'Personal portal isn’t working' ],
[ 'Plain HTTP links', 'Portal links use plain HTTP' ],
[ 'Internet like a home device', 'Internet like a home device isn’t working' ],
[ 'DNS for Home-only devices', 'DNS for Home-only devices isn’t working' ],
[ 'Background agent running', 'Background agent isn’t running' ],
[ 'Access rules loaded', 'Access rules aren’t loaded' ],
[ 'Server configured', 'No server yet' ],
[ 'Public address', 'Public address needs attention' ],
[ 'Clock is set', 'Clock isn’t set' ],
];
function problem_of(title) {
for (let p in PROBLEM)
if (substr(title, 0, length(p[0])) == p[0])
return p[1] + substr(title, length(p[0]));
return title;
}
/** problem: the failed check in words, when the table's wording does not fit the case. */
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 ?? problem_of(title)) : null };
return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? title) : null };
}
/**
@@ -222,13 +201,14 @@ function replies(m) {
return { ok: fw.reply_ok(m, d), diverts: map(d, fw.divert_str) };
}
function reply_check(id, title, proto, port, r) {
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 ? `Answers from ${uc(proto)} ${port} are swallowed by a proxy on the router (${via}): clients get no reply.`
: length(r.diverts) ? `Answers from ${uc(proto)} ${port} go straight out. A proxy on the router diverts its own traffic (${via}); these answers skip it.`
: `Answers from ${uc(proto)} ${port} go straight out.`,
r.ok ? null : 'apply');
!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);
@@ -243,48 +223,183 @@ export function wan_kind(wan) {
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 }.
* 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) {
let ips = host ? lookup.resolve(host) : [];
let wan = srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan');
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: wan ?? null, kind: wan_kind(wan),
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 facts in words: { status: ok|warn|error, text }. `proto_note` names what must get through ("UDP 4500"). */
/*
* 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.' };
return { status: 'error', text: _('No public address: devices will not know where to connect.') };
if (!length(f.ips))
return { status: 'error', text: `${f.host} does not resolve.` };
return { status: 'error', text: sprintf(_('%s does not resolve.'), f.host) };
if (f.cloudflare)
return { status: 'error', text: `${f.host} → ${join(', ', f.ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.` };
if (f.v6_only)
return { status: f.kind == 'public' ? 'warn' : 'ok', text: `${f.host} → ${join(', ', f.ips6)}: IPv6 only, so only devices with IPv6 connect${f.kind == 'public' ? ` (the router's IPv4 ${f.wan} has no name)` : ''}.` };
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')
return { status: 'warn', text: f.kind == 'cgnat'
? `The WAN address ${f.wan} is CGNAT (shared by the ISP): ${proto_note} cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.`
: `The WAN address ${f.wan} is private: this router is behind another one. Forward ${proto_note} on it, or devices cannot connect.` };
if (f.wan && !f.here)
return { status: 'warn', text: `${f.host} points at ${join(', ', f.ips4)}, not this router (WAN ${f.wan}). Check your DNS / DDNS.` };
return { status: 'ok', text: f.here ? `${f.host} points at this router (${f.wan}).` : `${f.host} → ${join(', ', f.ips)}` };
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, srv, host, proto_note) {
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);
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
@@ -294,7 +409,7 @@ function endpoint_check(id, title, srv, host, proto_note) {
function policy_routing() {
let out = [];
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/);
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`) ?? '';
@@ -306,7 +421,9 @@ function policy_routing() {
return out;
}
const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).";
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() {
@@ -318,27 +435,73 @@ function overlay_free_kb() {
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
function awg_check() {
let st = awg.load();
let title = 'AmneziaWG installed';
if (length(st.missing ?? [])) {
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(st.missing, 'kmod-amneziawg') >= 0)
if (kc && index(missing, 'kmod-amneziawg') >= 0)
return check('awg', title, 'error',
`The firmware changed (kernel ${kc.was} → ${kc.now}): the AmneziaWG build installed for it is gone. Install the build for this firmware.`,
'install:awg', 'AmneziaWG needs a build for the new firmware');
return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg',
'AmneziaWG isn’t installed');
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',
`The kernel module doesn't load${why ? `: ${why}` : '.'} Reinstall a build for this kernel in Components.`, 'updates',
'AmneziaWG’s kernel module doesn’t load');
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');
return check('awg', title, 'ok', 'Kernel module, awg tool and the netifd protocol are present.');
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. */
@@ -347,45 +510,39 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
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}`, `AmneziaWG running${label}`, 'error', NO_PROTO, 'netrestart'));
push(out, check(`up_${id}`, running, 'error', no_proto(), 'netrestart', down));
else
push(out, check(`up_${id}`, `AmneziaWG running${label}`, up ? 'ok' : 'error',
up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` :
(st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${srv.ifname} does not exist.`),
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
if (up) {
// By key, not by count: a stale peer standing in for a missing one would
// make the numbers match.
let states = apply.states_for(m, core.load_usage());
let wanted = {}, expected = 0;
for (let did, d in m.devices) {
let p = m.people[d.person];
if (p?.server == id && !d.disabled && index(awg.SOFT_STATES, states[d.person]) >= 0) {
wanted[d.public_key] = true;
expected++;
}
}
let loaded = {}, actual = 0;
for (let k, p in dmp.peers)
if (p.ifname == srv.ifname) {
loaded[k] = true;
actual++;
}
let missing = length(filter(keys(wanted), (k) => !loaded[k]));
let extra = length(filter(keys(loaded), (k) => !wanted[k]));
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 ? `${actual} device${actual == 1 ? ' is' : 's are'} loaded in the tunnel.` :
`${missing} of ${expected} device${expected == 1 ? '' : 's'} missing${extra ? `, ${extra} loaded that should not be` : ''}.`,
same ? null : 'sync'));
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 ? `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}`, `AmneziaWG answers reach devices${label}`, 'udp', srv.port, rep));
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();
@@ -395,7 +552,8 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
push(clash, s['.name']);
});
if (length(clash))
push(out, check(`port_${id}`, `AmneziaWG port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', 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)) {
@@ -403,8 +561,12 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
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) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`));
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;
}
@@ -412,50 +574,59 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
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', 'Personal portal', 'error', `HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install: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', 'Personal portal', 'error',
`TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`));
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', 'Personal portal', listening ? 'ok' : 'error',
listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart'));
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.'));
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));
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)' : ''}.`));
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', 'tcp', s.portal_port, rep));
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',
`Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`));
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.'));
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 ? `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.`));
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 }.
* 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).
*/
@@ -469,46 +640,50 @@ export function health(m) {
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.'));
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'));
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 ? `${int(free / 1024 * 10) / 10} MB free: settings may stop saving. Remove old backups (Settings → Backups) or shorten the history.`
: `${int(free / 1024)} MB free on the overlay.`,
null, 'The router is running out of flash'));
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.'));
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'));
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) ? `Policy routing on the router (${join('; ', pr)}) sends marked traffic straight out, past the home-device path: tunnel traffic it matches skips your LAN's proxies and filters.`
: 'No other policy routing ahead of the tunnel rules.',
null, 'Other policy routing bypasses the home-device path'));
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(' ', slice(data, 0, 4))}${length(data) > 4 ? ` (${length(data) - 4} more)` : ''} Such devices are left out of the tunnels: fix or remove them.`
: 'Every device has a key and an address of its own inside its server.'));
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');
@@ -516,21 +691,23 @@ export function health(m) {
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.'));
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}`, srv, core.endpoint_host(m, srv), `UDP ${srv.port}`));
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 ? `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'));
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));
}
}
@@ -542,10 +719,11 @@ export function health(m) {
// 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' ? `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'));
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)
@@ -572,9 +750,9 @@ export function fix(id) {
// 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(`${m[1]} is not one of Dawnline's tunnels.`);
die(sprintf(_("%s is not one of Dawnline's tunnels."), m[1]));
system(`ifup ${q(m[1])}`);
return { ok: true };
}
die('Unknown fix.');
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;
};
@@ -11,11 +11,14 @@ import {
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';
// 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`;
@@ -31,6 +34,8 @@ export const CATEGORY = {
person_added: 'people', person_removed: 'people', person_changed: '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', 'people', 'problems' ];
@@ -95,24 +100,90 @@ export const PRESENCE = `${RUN_DIR}/presence.json`;
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() {
let beat = +(read_json(BEAT, 0) ?? 0);
if (!beat || time() - beat > BEAT_STALE)
return null;
return read_json(PRESENCE, null);
return agent_running() ? read_json(PRESENCE, null) : null;
};
/**
* Peers of every tunnel: { ok, ifaces, peers: { public key: { ifname, endpoint,
* handshake, rx, tx } }, presence }. See dawnline.awg.
* 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 function dump(m) {
// Only Dawnline's own tunnels decide `ok`: another AmneziaWG interface on
// the router that cannot be read is not our trouble.
let mine = m ? map(filter(values(m.servers), (s) => s.private_key && s.enabled), (s) => s.ifname) : null;
let d = awg.dump(mine);
d.presence = presence();
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;
};
@@ -121,11 +192,15 @@ 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 < ONLINE_WINDOW);
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;
};
@@ -214,34 +289,36 @@ function offline(rec) {
/**
* 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 actually read: an interface the tool couldn't read says nothing, and
* forgetting the last counters there would count them again on the next good
* read. A failed read with nothing in it changes nothing at all.
* 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(m);
let ts = time();
let live = {};
if (d.ok === false && !length(d.peers)) {
for (let id in keys(m.devices))
live[id] = offline(usage.devices[id]);
return live;
}
for (let id, dev in m.devices) {
let rec = usage.devices[id] ??= { raw: [ 0, 0 ] };
let peer = d.peers[dev.public_key];
if (!peer) {
let ifname = m.servers[m.people[dev.person]?.server]?.ifname;
if (d.ok !== false || d.ifaces[ifname] != null)
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 ];
@@ -262,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,
@@ -369,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)
@@ -378,7 +458,7 @@ 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;
@@ -7,13 +7,24 @@
// └── 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.
//
// 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 —
@@ -22,7 +33,8 @@
//
// 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';
@@ -33,14 +45,16 @@ 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;
export const RESOLVER_CONF = resolver.CONF;
const STATE = `${RUN_DIR}/loop.json`;
const NS_RULES = '/var/etc/dawnline-ns.nft';
const WHO = 'Internet like a home device';
const WHO = L_('Internet like a home device');
function log(msg, level, detail) {
slog('dawnline', level ?? 'info', msg, detail, WHO);
@@ -104,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;
}
@@ -180,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() {
@@ -199,8 +289,8 @@ function all_ifnames(m) {
}
/**
* 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);
@@ -210,24 +300,26 @@ 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.` };
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);
@@ -238,6 +330,7 @@ export function plan(m) {
dev,
gateway: int2ip(lan.ip),
address: addr,
mac,
prefix: lan.prefix,
dns: facts.dns ?? int2ip(lan.ip),
transit: tx,
@@ -250,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
@@ -263,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
}
@@ -276,8 +380,40 @@ 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 = [];
@@ -292,31 +428,58 @@ function current_rules(ifnames) {
}
function rule_key(pref, iif, to, table) {
// `ip -j rule` shows a /32 destination without its length.
if (to && index(to, '/') < 0)
to += '/32';
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() {
@@ -329,21 +492,25 @@ function tunnel_ifnames() {
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);
};
@@ -362,8 +529,8 @@ export function ensure(m, force) {
remove(ifnames);
ensure_dir(RUN_DIR);
write_json(STATE, { error: p.error, off: !!p.off }, 0o644);
if (p.error && p.error != was.error)
log('is off', 'error', 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, {});
@@ -374,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}`,
@@ -404,25 +576,35 @@ 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)) {
if (read_json(STATE, {}).error != `Setup failed: ${errs[0]}`)
log('failed — internet goes out directly for now', 'error', 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] };
write_json(STATE, { error: why }, 0o644);
return { error: why };
}
ensure_dir(RUN_DIR);
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
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(`is on · traffic enters ${p.dev} as ${p.address}`, 'up');
log(sprintf(L_('is on · traffic enters %s as %s'), p.dev, p.address), 'up');
else if (!healthy)
log(`was broken — set up again (${p.dev} as ${p.address})`, 'repair');
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;
};
@@ -440,7 +622,7 @@ export function remember(p) {
});
};
/** Last applied state for views and health checks. */
/** 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)
@@ -449,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. */
@@ -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);
};
@@ -8,6 +8,7 @@ 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';
@@ -32,7 +33,7 @@ function word_codes() {
}
});
});
slog('dawnline', 'info', 'moved to word codes', null, 'Personal links');
slog('dawnline', 'info', L_('moved to word codes'), null, L_('Personal links'));
}
/*
@@ -101,7 +102,7 @@ function auto_mtu() {
mark_migrated(w, 'auto_mtu');
});
if (any)
slog('dawnline', 'info', 'MTU is now automatic', null, 'Servers');
slog('dawnline', 'info', L_('MTU is now automatic'), null, L_('Servers'));
}
/** All of them, in order. */
@@ -163,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]) : [];
@@ -295,10 +295,13 @@ export function lan_names() {
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 ?? '', /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g) ?? [])
for (let ip in match(e.detail ?? '', ANY_IPV4) ?? [])
if (names[ip[0]])
(out ??= {})[ip[0]] = names[ip[0]];
return out;
@@ -2,13 +2,16 @@
// 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.
// 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`;
@@ -28,6 +31,14 @@ export function owner(ifname, c) {
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();
@@ -35,12 +46,12 @@ export function sync(m) {
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, msg, detail) => {
blocked[srv.id] = msg;
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 = msg;
if (was[srv.id] != msg)
log(srv.name, msg, 'error', detail);
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
@@ -49,7 +60,7 @@ export function sync(m) {
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', "isn't installed: tunnels were left as they are", 'error', 'Install it in Dawnline → Components.');
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()}`);
}
@@ -59,22 +70,24 @@ export function sync(m) {
continue;
let ifn = srv.ifname;
if (!core.valid_ifname(ifn)) {
block(srv, `has an invalid interface name "${ifn}"`, 'Interface name: 1-12 lowercase letters, digits or _.');
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, `can't use the network interface ${ifn}: it exists and isn't Dawnline's`,
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 ? awg.obf_unsupported(srv.obf) : null;
let why = !tools ? null : length(awg.obf_unsafe(srv.obf)) ? { code: 'disguise_invalid' } : awg.obf_unsupported(srv.obf);
if (why) {
block(srv, `is kept down: ${why}`, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
block(srv, why, awg.blocked_fix(why));
continue;
}
delete srv.blocked;
@@ -83,17 +96,16 @@ export function sync(m) {
continue;
// Per server: with several, each changed one has to be brought up again.
let mine = uci_section(c, 'network', ifn, 'interface');
let set = (opt, val) => {
if (uci_put(c, 'network', ifn, opt, val))
for (let k, v in options(srv))
if (uci_put(c, 'network', ifn, k, v))
mine = true;
};
for (let k, v in awg.netifd_options(srv))
set(k, v);
set('disabled', srv.enabled ? null : '1');
set('auto', srv.enabled ? null : '0');
set('_dawnline', id);
// 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.
set('_dawnline_name', srv.name);
if (uci_put(c, 'network', ifn, '_dawnline_name', srv.name))
changed = true;
if (mine) {
changed = true;
push(touched, ifn);
@@ -123,6 +135,9 @@ export function sync(m) {
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)
@@ -132,3 +147,29 @@ export function sync(m) {
}
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;
};
@@ -10,7 +10,8 @@ import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
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' ];
/** 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' ];
@@ -18,8 +19,11 @@ function ip4(a) {
return ip2int(a ?? '') != null;
}
/** Per-person runtime membership: which tunnel addresses may reach what. */
export function access_sets(m, usage, states) {
/**
* 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);
@@ -27,7 +31,7 @@ export function access_sets(m, usage, states) {
let sets = {};
for (let k in SETS)
sets[k] = [];
let snap = net.snapshot();
snap ??= net.snapshot();
let homes = {}, groups = {};
for (let id, d in m.devices) {
let p = m.people[d.person];
@@ -91,13 +95,23 @@ function portal_ports(m) {
return ports;
}
function table(m, sets) {
/**
* 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 = loop.client_dns();
let dns_addr = ctx.dns_addr;
if (!ip4(dns_addr))
dns_addr = null;
let rt = loop.resolver_target();
let snap = net.snapshot();
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 = {};
@@ -194,7 +208,7 @@ function table(m, sets) {
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 = loop.lan_dns();
let lan_dns = ctx.lan_dns;
if (!ip4(lan_dns))
lan_dns = null;
push(t, ' chain dns {');
@@ -228,9 +242,13 @@ export function load(script) {
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. */
export function render(m, sets) {
return table(m, sets);
/**
* 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. */
@@ -4,6 +4,7 @@
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');
@@ -46,13 +47,28 @@ export function version(name) {
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) {
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];
return file_info(path).version;
};
/**
@@ -99,26 +115,59 @@ function preflight(files, need_kb, log) {
for (let f in files ?? [])
need += int(((stat(f)?.size ?? 0) * 3) / 1024);
if (free < need)
die(`Not enough free space on the router: ${int(free / 1024)} MB free, about ${int(need / 1024) + 1} MB needed. Remove old backups or packages first`);
log?.(` ${int(free / 1024)} MB free on the overlay`);
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)));
}
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
/** 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;
// apk leaves an installed version alone, whatever the file: a reinstall
// that changed nothing is a failure, not a silent "done".
let marker = '/usr/share/ucode/dawnline/util.uc';
let before = force ? stat(marker)?.mtime : null;
let ok = logged(`apk add --allow-untrusted ${args}`, log).code == 0;
if (ok && force && before != null && stat(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");
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;
}
return ok;
// 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. */
@@ -1,9 +1,9 @@
// Dawnline — the personal portal.
//
// GET /<code> the app shell
// GET /<code>/assets/<file> its script, styles and fonts
// GET /<code>/assets/<file> its script and styles (gzipped when the browser takes it)
// GET /<code>/api/state
// POST /<code>/api/devices { name, kind, public_key? }
// 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? }
//
@@ -24,6 +24,10 @@
// 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).
@@ -36,10 +40,12 @@ 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 TYPES = { js: 'text/javascript', css: 'text/css', png: 'image/png' };
const FAIL_LIMIT = 8;
const FAIL_WINDOW = 900;
// All Cloudflare visitors together (three-word codes can't be guessed anyway).
@@ -60,13 +66,22 @@ const SECURITY_HEADERS = {
'Cache-Control': 'no-store',
};
const NOT_READY = "Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.";
// States the admin stopped the person in: the portal only shows, it changes nothing.
const LOCKED = {
paused: 'Your access is paused.',
expired: 'Your access has ended.',
};
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) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
@@ -124,7 +139,7 @@ function body(r) {
if (len <= 0)
return {};
if (len > BODY_MAX)
fail(r, '413 Payload Too Large', 'Request too large.');
fail(r, '413 Payload Too Large', _('Request too large.'));
let raw = '';
while (length(raw) < len) {
let chunk = r.io.read(len - length(raw));
@@ -137,7 +152,7 @@ function body(r) {
return type(j) == 'object' ? j : {};
}
catch (e) {
fail(r, '400 Bad Request', 'Invalid JSON.');
fail(r, '400 Bad Request', _('Invalid JSON.'));
}
}
@@ -236,7 +251,7 @@ function rate_action(r) {
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.');
fail(r, '429 Too Many Requests', _('Too many changes in a short time. Try again in a few minutes.'));
}
/* ---------- pages ---------- */
@@ -248,24 +263,26 @@ function place(r) {
/** 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.
// The build's time joins the version: every update gives the assets new URLs, so they are cached for good.
let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
let base = r.base, title = place(r);
// The icon goes in the page: a request of its own would start another CGI process.
let icon = readfile(`${ASSETS}/icon.svg`);
let favicon = icon ? `<link rel="icon" href="data:image/svg+xml;base64,${b64enc(icon)}" type="image/svg+xml">\n` : '';
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'; " +
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; " +
"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, viewport-fit=cover">
<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}">
${favicon}<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>
@@ -276,13 +293,18 @@ function shell(r) {
finish();
}
/** Script, styles, icon and fonts (kept outside the web root). */
/** Script and styles (kept outside the web root); the shell's ?v= changes with every build, so they never go stale. */
function asset(r, name) {
let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2|png)$/)?.[1];
let data = ext ? readfile(`${ASSETS}/${name}`) : null;
let ext = match(name, /^[a-z0-9-]+\.(js|css|png)$/)?.[1];
// The build keeps a gzipped copy beside each: a third of the bytes for a browser that takes it.
let gz = ext && r.gzip ? readfile(`${ASSETS}/${name}.gz`) : null;
let data = gz ?? (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' });
let h = { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=31536000, immutable', 'Vary': 'Accept-Encoding' };
if (gz != null)
h['Content-Encoding'] = 'gzip';
headers(r, '200 OK', h);
r.io.write(data);
finish();
}
@@ -305,7 +327,7 @@ 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 (LOCKED[own])
if (index(LOCKED, own) >= 0)
return own;
}
return st;
@@ -313,7 +335,7 @@ function person_state(m, p, usage) {
/** Why the person can't change anything right now, or null. */
function locked(r) {
return LOCKED[person_state(r.m, r.person, core.load_usage())] ?? null;
return locked_reason(person_state(r.m, r.person, core.load_usage()));
}
/** Refuses a change (or a config) while the person is stopped. */
@@ -340,7 +362,7 @@ function https_url(r) {
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 });
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. */
@@ -353,7 +375,8 @@ function tz_offset() {
function state(r) {
let m = r.m, person = r.person;
let usage = core.load_usage();
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, 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]);
@@ -369,9 +392,12 @@ function state(r) {
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: LOCKED[v.state] != null,
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,
@@ -389,7 +415,7 @@ function state(r) {
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.');
fail(r, '404 Not Found', _('Device not found.'));
return d;
}
@@ -402,9 +428,10 @@ function api_add(r) {
need_https(r);
let b = body(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
fail(r, '503 Service Unavailable', not_ready());
rate_action(r);
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
// 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) });
}
@@ -427,7 +454,7 @@ const ACTIONS = {
reconnect: (r, d, b) => {
need_https(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_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 };
},
@@ -443,7 +470,7 @@ function api_device(r, id) {
let b = body(r);
let act = ACTIONS[b.action];
if (!act)
fail(r, '400 Bad Request', 'Unknown action.');
fail(r, '400 Bad Request', _('Unknown action.'));
rate_action(r);
let res = act(r, d, b);
reload(r);
@@ -499,6 +526,7 @@ export function handle(io) {
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
person: null,
base: '',
gzip: match(lc(header('accept-encoding') ?? ''), /(^|[ ,])gzip([ ;,]|$)/) != null,
};
let segs = filter(split(path, '/'), (s) => s != '');
@@ -542,21 +570,23 @@ export function handle(io) {
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.');
fail(r, '403 Forbidden', _('Cross-site request refused.'));
}
else if (r.method != 'GET')
fail(r, '405 Method Not Allowed', 'Method not allowed.');
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.');
fail(r, '404 Not Found', _('Not found.'));
rt.run(r, rt.args[0]);
fail(r, '404 Not Found', 'Not found.');
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) {
@@ -21,11 +21,14 @@ export function name_covers(name, 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\.crt$/);
let m = match(f, FULLCHAIN);
if (!m)
continue;
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
@@ -6,6 +6,7 @@ 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
@@ -45,16 +46,16 @@ export function default_method() {
/** A disguise method the installed AmneziaWG can run. */
export function check_method(name) {
if (index(METHODS, name) < 0)
die('Unknown disguise method.');
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.');
? _('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.');
? _('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;
};
@@ -75,6 +76,7 @@ function tcp_forwards(m) {
/**
* 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 = [];
@@ -86,11 +88,11 @@ export function tcp_taken(m) {
}
};
for (let p in schema.RESERVED_PORTS)
hold(p, 'the router itself');
hold(p, _('the router itself'));
for (let p, name in health.tcp_port_programs())
hold(+p, `${name} on this router`);
hold(+p, sprintf(_('%s on this router'), name));
for (let f in tcp_forwards(m))
push(out, { from: f.from, to: f.to, who: `port forward “${f.name}”` });
push(out, { from: f.from, to: f.to, who: sprintf(_('port forward “%s”'), f.name) });
return out;
};
@@ -100,12 +102,12 @@ export function check_portal(m, was) {
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).');
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(`Links on IP addresses use plain HTTP on the next port (${hp}), which the portal cannot take. Choose another portal port.`);
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.
@@ -120,11 +122,13 @@ export function check_portal(m, was) {
continue;
let owners = health.tcp_port_owners(p);
if (length(owners))
die(`TCP ${p} is already used by ${join(', ', owners)}.${p != port ? ' Links on IP addresses use plain HTTP on the port after the portal\'s.' : ''} Choose another portal port.`);
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(`TCP ${p} is sent on by port forward “${f.name}”. Choose another portal port.`);
die(sprintf(_('TCP %d is sent on by port forward “%s”. Choose another portal port.'), p, f.name));
};
@@ -4,7 +4,7 @@
import { readfile } from 'fs';
import { cursor } from 'uci';
import { sh_out, ip2int, rand_int, rand_hex, admin_log, valid_name, ulength, NAME_RULE } from 'dawnline.util';
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';
@@ -12,6 +12,7 @@ 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 ---------- */
@@ -22,29 +23,29 @@ function new_id(m, make) {
if (!store.id_taken(m, id))
return id;
}
die('Could not find a free id, try again.');
die(_('Could not find a free id, try again.'));
}
function service_set(a) {
let name = str(a.name);
if (!valid_name(name))
die(`Service: ${NAME_RULE}`);
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.');
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(`Invalid 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.');
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.');
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);
@@ -61,7 +62,7 @@ function service_set(a) {
function service_delete(a) {
store.transact((c, m) => {
if (!m.services[a.id])
die('Unknown service.');
die(_('Unknown service.'));
c.delete(core.CONFIG, a.id);
for (let pid, p in m.people)
if (index(p.services, a.id) >= 0) {
@@ -82,17 +83,17 @@ function service_delete(a) {
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 \\.');
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.');
die(_('Unknown circle.'));
let server = ci?.server ?? a.server;
if (!m.servers[server])
die('Unknown server.');
die(_('Unknown server.'));
for (let id, o in m.circles)
if (id != a.id && o.server == server && lc(o.name) == lc(name))
die(`${name} already exists.`);
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');
@@ -121,7 +122,7 @@ function circle_delete(a) {
let res = store.transact((c, m) => {
let ci = m.circles[a.id];
if (!ci)
die('Unknown circle.');
die(_('Unknown circle.'));
c.delete(core.CONFIG, a.id);
for (let pid, p in m.people)
if (p.circle == a.id)
@@ -173,7 +174,7 @@ function home_hosts(a) {
let m = core.load();
let srv = m.servers[a.id] ?? values(m.servers)[0];
if (!srv)
die('No server yet.');
die(_('No server yet.'));
let nets = [];
for (let cidr in net.server_net(srv).nets) {
let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/);
@@ -1,6 +1,7 @@
// 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';
@@ -49,10 +50,10 @@ function import_all(a) {
/** 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.');
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.');
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');
@@ -9,6 +9,7 @@ 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' ];
@@ -55,13 +56,15 @@ function person_update(a) {
let s = apply.sync();
let m = core.load();
let u = core.load_usage();
return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
// 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.');
die(_('Unknown person.'));
if (a.paused)
c.set(core.CONFIG, a.id, 'paused', '1');
else
@@ -79,7 +82,7 @@ function person_pause(a) {
function person_regen(a) {
let gone = store.transact((c, m) => {
if (!m.people[a.id])
die('Unknown person.');
die(_('Unknown person.'));
c.set(core.CONFIG, a.id, 'code', core.new_code());
c.set(core.CONFIG, a.id, 'code_set', `${time()}`);
let gone = [];
@@ -106,7 +109,7 @@ function person_links(a) {
let m = core.load();
let p = m.people[a.id];
if (!p)
die('Unknown person.');
die(_('Unknown person.'));
return { code: p.code, link: core.portal_url(m, p), links: core.portal_urls(m, p) };
}
@@ -125,7 +128,7 @@ function person_usage(a) {
let m = core.load();
let p = m.people[a.id];
if (!p)
die('Unknown person.');
die(_('Unknown person.'));
let days = clamp_days(a.days);
let devs = {};
for (let d in p.devices)
@@ -137,20 +140,28 @@ function person_usage(a) {
function device_create(a) {
devices.need_awg();
return devices.add(a.person, a.name, a.kind, { by: 'admin' });
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.');
awg.mark_issued(m, d.id);
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 }, { by: 'admin' });
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 = {
@@ -168,9 +179,10 @@ export const methods = {
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: '' }, call: wrap(device_create) },
device_config: { args: { id: '' }, call: wrap(device_config) },
device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) },
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' })) },
device_rotate: { args: { id: '' }, call: wrap((a) => devices.rotate(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' })) },
};
@@ -2,7 +2,7 @@
// 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, NAME_RULE, rand_int, uniq, admin_log } from 'dawnline.util';
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';
@@ -15,6 +15,7 @@ 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' ];
@@ -27,6 +28,7 @@ const MESH_WORDS = { off: 'devices kept apart', all: 'devices reach each other',
* 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 = [];
@@ -39,26 +41,26 @@ function udp_taken(m, srv, wan_zone) {
};
for (let id, o in m.servers)
if (id != srv?.id)
hold(o.port, `server “${o.name}”`);
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, `interface ${s['.name']}`);
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}`] ? `${progs[`${p}`]} on this router` : 'another program on this router');
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: `port forward “${f.name}”` });
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(`UDP ${port} is used by ${t.who}. Choose another port.`);
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. */
@@ -197,7 +199,8 @@ function setup_defaults(a) {
let port = free_port(udp);
return {
id: free_server_id(m),
name: length(m.servers) ? `Server ${length(m.servers) + 1}` : 'Home',
// 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)),
@@ -229,7 +232,7 @@ function setup_defaults(a) {
function endpoint_probe(a) {
let host = str(a.host);
if (host != '' && !valid_host(host))
die('Public address must be a hostname or IP address.');
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);
@@ -241,14 +244,14 @@ function endpoint_probe(a) {
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.");
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.');
die(_('MTU must be 1280-1500.'));
return s;
}
@@ -260,19 +263,19 @@ function server_create(a) {
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.');
die(_('Server ID may use lowercase letters, digits and underscores.'));
if (!id_free(m, id))
die(`"${id}" is already taken.`);
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(`Network interface ${ifname} already exists.`);
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.');
die(_('UDP port must be 1-65535.'));
port = +str(a.port);
}
check_udp_port(port, udp);
@@ -285,7 +288,7 @@ function server_create(a) {
// 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.');
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);
@@ -298,7 +301,7 @@ function server_create(a) {
c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, id, 'server');
if (!valid_name(str(a.name) || 'Home'))
die(`Server: ${NAME_RULE}`);
die(_('Server: Enter a name: up to 48 characters, without < > " or \\.'));
set('name', str(a.name) || 'Home');
set('ifname', ifname);
set('port', `${port}`);
@@ -322,14 +325,15 @@ function server_create(a) {
set('detected_wan', snap.wan);
if (snap.lan)
set('detected_lan', snap.lan);
set('lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
// 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.');
die(_('Portal port must be 1-65535.'));
c.set(core.CONFIG, 'settings', 'portal_port', `${+str(a.portal_port)}`);
}
}
@@ -394,7 +398,7 @@ function interfaces_get(a) {
let m = core.load();
let srv = m.servers[a.id] ?? values(m.servers)[0];
if (!srv)
die('No server yet.');
die(_('No server yet.'));
return interfaces_view(m, srv, net.snapshot(true));
}
@@ -406,12 +410,12 @@ function server_interfaces(a) {
let res = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
die(_('Unknown server.'));
if (!auto_wan) {
if (!snap.devices[wan_dev])
die('Choose the interface that leads to the internet.');
die(_('Choose the interface that leads to the internet.'));
if (!snap.devices[wan_dev].zone)
die(`${wan_dev} is not in a firewall zone, so the server port cannot be opened on it.`);
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 : [])) {
@@ -420,9 +424,9 @@ function server_interfaces(a) {
if (d == '' || d == srv.ifname || (!snap.devices[d] && index(srv.lan_devices, d) < 0))
continue;
if (snap.devices[d]?.master)
die(`${d} is part of ${snap.devices[d].master}; choose ${snap.devices[d].master} instead.`);
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(`${d} is the WAN.`);
die(sprintf(_('%s is the WAN.'), d));
push(lans, d);
}
lans = uniq(lans);
@@ -485,7 +489,7 @@ 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(`${d} is not an IP address.`);
die(sprintf(_('%s is not an IP address.'), d));
return list;
}
@@ -497,22 +501,22 @@ function server_update(a) {
let srv = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
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: ${NAME_RULE}`);
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.');
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.');
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));
@@ -522,7 +526,7 @@ function server_update(a) {
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.');
die(_('Unknown choice for devices reaching each other.'));
set('mesh', v.mesh);
set('device_mesh', null);
}
@@ -530,7 +534,7 @@ function server_update(a) {
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.');
die(_('Keep-alive must be 0-600 seconds.'));
set('keepalive', str(v.keepalive));
}
if (v.dns != null) {
@@ -544,13 +548,13 @@ function server_update(a) {
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.');
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.');
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(`Subnet overlaps ${t}.`);
die(sprintf(_('Subnet overlaps %s.'), t));
core.renumber_server(c, m, srv, cidr_str(pc));
}
return srv;
@@ -583,7 +587,7 @@ function server_ports(a) {
let m = core.load();
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
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) };
@@ -592,10 +596,14 @@ function server_ports(a) {
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.');
die(_('Unknown server.'));
for (let k in core.OBF_KEYS)
c.delete(core.CONFIG, srv.id, k);
for (let k, v in o)
@@ -611,12 +619,12 @@ function server_obfuscation(a) {
/** 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.');
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.');
die(_('Unknown server.'));
let gone = 0;
for (let pid, p in m.people)
if (p.server == srv.id) {
@@ -12,6 +12,7 @@ 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' ];
@@ -92,7 +93,7 @@ function same(a, b) {
function settings_update(a) {
let v = a.values ?? {};
if (type(v) != 'object')
die('Nothing to save.');
die(_('Nothing to save.'));
let res = store.transact((c, m) => {
let restart = false;
c.set(core.CONFIG, 'settings', 'settings');
@@ -1,7 +1,9 @@
// Dawnline rpcd methods: the live revision, the Overview status (servers,
// people, totals, map, recent activity), the activity log and traffic history.
// 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';
@@ -12,6 +14,7 @@ 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). */
@@ -122,10 +125,12 @@ function server_view(m, srv, usage, dmp, rates, days) {
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.
blocked: srv.blocked ?? 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 })),
peers, online, obf: srv.obf,
// 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).
@@ -135,7 +140,8 @@ function server_view(m, srv, usage, dmp, rates, days) {
/*
* Everything the pages show at once. Readable by read-only users: no personal
* codes or links here (person_links has them).
* 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();
@@ -221,19 +227,19 @@ function logs_clear(a) {
let f = {};
if (a.person) {
if (!m.people[a.person])
die('Unknown 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.');
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.');
die(_('Older than must be a number of days.'));
f.before = time() - +a.older_days * 86400;
}
let removed = live.clear_events(f);
@@ -252,11 +258,11 @@ function logs_clear(a) {
function usage_clear(a) {
let m = core.load();
if (index([ 'all', 'person', 'device' ], a.scope) < 0)
die('Unknown scope.');
die(_('Unknown scope.'));
if (a.scope == 'person' && !m.people[a.id])
die('Unknown person.');
die(_('Unknown person.'));
if (a.scope == 'device' && !m.devices[a.id])
die('Unknown device.');
die(_('Unknown device.'));
let req = { scope: a.scope, id: a.id, ts: time() };
ensure_dir(RUN_DIR);
let l = lock('usage-reset');
@@ -280,8 +286,21 @@ 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) },
@@ -11,11 +11,14 @@ 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]
// 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)?|amneziawg(:rollback|:(auto|slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/;
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) {
@@ -41,11 +44,14 @@ function awg_tunnels() {
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, /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/);
let x = match(line, RELEASE_LINE);
if (x)
rel[lc(x[1])] = x[2];
}
@@ -62,6 +68,8 @@ function status(a) {
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(),
};
@@ -71,7 +79,7 @@ function status(a) {
function releases(a) {
let page = +(a.page ?? 1);
if (page != int(page) || page < 1 || page > 50)
die('Unknown page.');
die(_('Unknown page.'));
return { releases: map(gh.releases(REPO, page), (x) => ({ ...x, body: null, digests: null })), page };
}
@@ -80,12 +88,12 @@ 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.');
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(`No release ${tag} in ${rp}.`);
die(sprintf(_('No release %s in %s.'), tag, rp));
return { ...r, digests: null, repo: rp };
}
@@ -93,7 +101,7 @@ function notes(a) {
function changes(a) {
let to = a.to ?? '', from = a.from ?? '';
if (!match(to, TAG) || (from != '' && !match(from, TAG)))
die('Unknown release.');
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/, '') ] : []))
@@ -109,18 +117,20 @@ function changes(a) {
function run(a) {
let what = a.what ?? 'check';
if (length(what) > 400 || !match(what, TARGET))
die('Unknown update 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.' : `${n} is not a package Dawnline manages.`);
die(n == '' ? _('Unknown update target.') : sprintf(_('%s is not a package Dawnline manages'), n));
if (upd.busy())
die('Another component action is already running.');
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}`;
system(`start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${args}`);
// 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)
@@ -8,6 +8,7 @@
import { stat } from 'fs';
import { ip2int, valid_host, ulength } from 'dawnline.util';
import { INTERVALS, TARGETS } from 'dawnline.updates';
import { _ } from 'dawnline.i18n';
/* ---------- addresses ---------- */
@@ -109,37 +110,36 @@ export function to_int(v, dflt, lo, hi) {
/*
* 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; msg: the error for a bad value.
* 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, msg: 'Public address must be a hostname or IP address.' },
portal_alt: { type: 'hosts', dflt: [], restart: true, msg: 'Other addresses must be hostnames or IP addresses.' },
portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true,
msg: 'Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).' },
portal_redirect: { type: 'url', dflt: '', msg: 'Redirect must be a full http:// or https:// address.' },
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, msg: 'Default device limit must be 1-32.' },
default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32 },
hostnames: { type: 'bool', dflt: true },
domain: { type: 'domain', dflt: 'lan', msg: 'Domain may use lowercase letters, digits, dashes and dots.' },
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' ], msg: 'Unknown location service.' },
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, msg: 'Keep activity for 0 (no age limit) to 9999 days.' },
log_max: { type: 'int', dflt: 2000, min: 100, max: 20000, msg: 'Log size must be 100-20000 events.' },
log_persist: { type: 'enum', dflt: 'hourly', values: [ '10min', 'hourly', 'off' ], msg: 'Save the log every 10min, hourly or off.' },
usage_keep_days: { type: 'int', dflt: 62, min: 7, max: 1830, msg: 'Daily traffic history must be 7-1830 days.' },
usage_keep_months: { type: 'int', dflt: 24, min: 1, max: 120, msg: 'Monthly traffic history must be 1-120 months.' },
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', msg: 'Fallback DNS must be an IPv4 address (or empty for none).' },
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), msg: 'Check every 6h, 12h, 1d or 7d.' },
update_interval: { type: 'enum', dflt: '1d', values: keys(INTERVALS) },
update_auto: { type: 'bool', dflt: true },
update_mode: { type: 'enum', dflt: 'scheduled', values: [ 'immediate', 'scheduled' ], msg: 'Install updates immediately or scheduled.' },
update_time: { type: 'time', dflt: '04:00', msg: 'Enter a time as HH:MM, 00:00 to 23:59.' },
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 },
@@ -148,8 +148,30 @@ export const SETTINGS = {
/** Ports the portal never takes: SSH, DNS and the LuCI web server. */
export const RESERVED_PORTS = [ 22, 53, 80, 443 ];
function bad(spec, key) {
die(spec.msg ?? `Invalid value for ${key}.`);
/** 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));
}
/**
@@ -160,14 +182,14 @@ function bad(spec, key) {
export function validate(key, val) {
let spec = SETTINGS[key];
if (!spec)
die(`Unknown setting ${key}.`);
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(spec, key);
bad(key);
if (trim(x) != '' && index(lst, trim(x)) < 0)
push(lst, trim(x));
}
@@ -190,40 +212,40 @@ export function validate(key, val) {
return null;
if (t == 'bool') {
if (val != '0' && val != '1')
die(`${key} is 0 or 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(spec, key);
bad(key);
val = `${+val}`;
}
else if (t == 'enum') {
if (index(spec.values, val) < 0)
bad(spec, key);
bad(key);
}
else if (t == 'host') {
if (!valid_host(val))
bad(spec, key);
bad(key);
}
else if (t == 'url') {
if (length(val) > 300 || !match(val, /^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^[:space:]"'<>]*)?$/))
bad(spec, key);
bad(key);
}
else if (t == 'file') {
if (substr(val, 0, 1) != '/' || !stat(val))
die(`${val} does not exist.`);
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(spec, key);
bad(key);
}
else if (t == 'ipv4') {
if (!ipv4(val))
bad(spec, key);
bad(key);
}
else if (t == 'time') {
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
bad(spec, key);
bad(key);
}
return val;
};
@@ -5,6 +5,7 @@
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' ];
@@ -15,8 +16,11 @@ export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
* caller's change never happened, and nothing downstream may act on it.
*/
export function commit(c) {
if (!c.commit(core.CONFIG))
die(`Couldn't save /etc/config/dawnline: ${c.error() ?? 'the write failed'}. Is the flash full?`);
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');
};
@@ -1,12 +1,15 @@
// 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 } from 'fs';
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);
@@ -16,12 +19,12 @@ function status(installed, latest) {
export function check(ctx) {
let r = gh.latest(REPO);
if (!r)
return { installed: VERSION, latest: null, update: false, repo: REPO, status: '', note: `Cannot reach github.com/${REPO}` };
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' ? `Dawnline update is available: ${VERSION} → ${latest}`
: st == 'dev' ? `Installed Dawnline ${VERSION} is newer than the release ${latest}`
: `Dawnline is up to date (${VERSION})`);
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 };
};
@@ -44,21 +47,51 @@ function want_sha(ctx, tag, asset, dir) {
return null;
}
/** Download a release's package, verified against its sha256. */
function fetch(ctx, tag, dir) {
let ver = replace(tag, /^v/, '');
let asset = `luci-app-dawnline-${ver}.${pkg.ext()}`;
ctx.phase(`Downloading ${asset}`);
/** 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(`Release ${tag} publishes no checksum for ${asset}: not installing an unverified package`);
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(`Download failed: ${asset}`);
ctx.log(`sha256 matches the release (${substr(want, 0, 12)}…)`);
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 ]) {
@@ -72,23 +105,54 @@ function tag_of(ver) {
}
function backup(ctx) {
ctx.phase('Backing up configuration');
ctx.phase(_('Backing up configuration'));
system('/usr/bin/dawnline backup --reason pre-update >/dev/null 2>&1');
}
/** arg: null (latest) | @<tag> | reinstall | rollback */
/**
* 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');
die(_('No previous Dawnline version is kept on the router'));
out.to = k.version;
ctx.versions(VERSION, k.version);
backup(ctx);
ctx.phase(`Rolling back to ${k.version}`);
ctx.phase(sprintf(_('Rolling back to %s'), k.version));
if (!pkg.install_files(k.files, true, ctx.log))
die('Installation failed');
die(_('Installation failed'));
upd.forget('app');
ctx.after('app');
return out;
@@ -114,25 +178,25 @@ export function install(ctx, arg) {
}
out.to = replace(tag, /^v/, '');
ctx.versions(VERSION, out.to);
let f = fetch(ctx, tag, ctx.work);
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(`Keeping Dawnline ${VERSION} for rollback`);
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`) ]);
upd.keep('app', VERSION, fetch(ctx, tag_of(VERSION), `${ctx.work}/keep`));
}
catch (e) {
ctx.log(`Warning: could not keep ${VERSION}: ${e.message}`);
ctx.log(sprintf(_('Warning: could not keep %s: %s'), VERSION, e.message));
}
}
backup(ctx);
ctx.phase('Installing package');
if (!pkg.install_files([ f ], force, ctx.log))
die('Installation failed');
ctx.phase(_('Installing package'));
if (!pkg.install_files(files, force, ctx.log))
die(_('Installation failed'));
ctx.after('app');
return out;
};
@@ -1,6 +1,8 @@
// 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';
@@ -10,6 +12,7 @@ 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`);
@@ -51,16 +54,16 @@ export function check(ctx) {
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' };
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' };
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(`Looking for the ${src.label} build for OpenWrt ${substr(fw.tag, 1)}`);
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;
@@ -88,23 +91,31 @@ export function check(ctx) {
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 ? `AmneziaWG ${cur}: no source publishes this build for this firmware any more`
: st == 'outdated' ? `AmneziaWG update is available: ${cur} → ${mine.version}`
: `AmneziaWG is up to date (${cur})`);
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),
note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} yet` : null };
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 and up again. */
function reload_module(ctx, before, after) {
if (!before['kmod-amneziawg'] || before['kmod-amneziawg'] == after['kmod-amneziawg'])
return;
/**
* 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');
@@ -112,38 +123,64 @@ function reload_module(ctx, before, after) {
if (s.proto == 'amneziawg' && s.disabled != '1')
push(ifaces, s['.name']);
});
ctx.phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`);
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}'`);
}
// Both steps must really happen: the new tools against the old module (or
// no module at all) leave every tunnel down while the job says "done".
ctx.run('rmmod amneziawg');
if (stat('/sys/module/amneziawg'))
die('The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update');
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)");
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. */
function settle(ctx, before, after) {
if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) {
ctx.phase('Loading the kernel module');
/**
* 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");
die(_("AmneziaWG is installed, but its kernel module doesn't load on this firmware"));
}
else
reload_module(ctx, before, after);
// 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.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. */
@@ -163,26 +200,25 @@ function pick(fw) {
/** 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');
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');
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');
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(`Rolling back to ${k.version}`);
ctx.phase(sprintf(_('Rolling back to %s'), k.version));
if (!pkg.install_files(k.files, true, ctx.log))
die('Package installation failed');
die(_('Package installation failed'));
upd.forget('amneziawg');
out.after = builds.installed();
settle(ctx, before, out.after);
return out;
return finish(ctx, out, k.build, fw.tag, was);
}
let parts = split(arg ?? '', ':');
let id = parts[0] || 'auto';
@@ -190,18 +226,18 @@ export function install(ctx, arg) {
if (id == 'auto') {
id = pick(fw);
if (!id)
die(`No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} (${fw.postfix}) yet`);
die(sprintf(_('No AmneziaWG build for OpenWrt %s (%s) yet'), substr(fw.tag, 1), fw.postfix));
}
let src = builds.SOURCES[id];
if (!src)
die(`Unknown AmneziaWG build ${id}`);
die(sprintf(_('Unknown AmneziaWG build %s'), id));
out.build = id;
let files = [];
for (let p in [ ...builds.PKGS, ...(want_ru ? [ builds.RU ] : []) ]) {
ctx.phase(`Downloading ${p} from ${src.repo}`);
ctx.phase(sprintf(_('Downloading %s from %s'), p, src.repo));
let f = fetch(ctx, fw, p, id, ctx.work);
if (!f)
die(`No ${p} build for OpenWrt ${substr(fw.tag, 1)} in ${src.repo}, or it could not be verified`);
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]);
@@ -219,23 +255,20 @@ export function install(ctx, arg) {
kept = sid;
}
if (kept) {
ctx.phase(`Keeping AmneziaWG ${out.from} for rollback`);
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.log(_('Warning: the installed build is no longer published, nothing to keep for rollback'));
}
ctx.phase('Refreshing package lists');
ctx.phase(_('Refreshing package lists'));
pkg.refresh(ctx.log);
ctx.phase(`Installing the ${src.label} build`);
ctx.phase(sprintf(_('Installing the %s build'), src.label));
if (!pkg.install_files(files, true, ctx.log))
die('Package installation failed');
die(_('Package installation failed'));
if (!want_ru && pkg.version(builds.RU))
pkg.remove([ builds.RU ], ctx.log);
out.after = builds.installed();
settle(ctx, before, out.after);
builds.record(id, fw.tag, out.after);
return out;
return finish(ctx, out, id, fw.tag, was);
};
@@ -4,6 +4,7 @@
// 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' ];
@@ -41,7 +42,7 @@ function with_family(names, up) {
/** 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');
ctx.phase(_('Refreshing package lists'));
pkg.refresh();
}
let up = pkg.upgradable();
@@ -54,7 +55,8 @@ export function check(ctx, refresh) {
all[x] = true;
}
let n = length(keys(all));
ctx.log(n ? `${n} package update${n == 1 ? '' : 's'} in the feeds: ${join(', ', sort(keys(all)))}` : 'System packages are up to date');
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' };
};
@@ -63,22 +65,22 @@ export function install(ctx, arg) {
let names = filter(split(arg ?? '', ','), (x) => x != '');
for (let n in names)
if (index(NAMES, n) < 0)
die(`${n} is not a package Dawnline manages`);
die(sprintf(_('%s is not a package Dawnline manages'), n));
if (!length(names))
die('Nothing to install');
ctx.phase('Refreshing package lists');
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(`Updating ${join(', ', have)}`);
ctx.phase(sprintf(_('Updating %s'), join(', ', have)));
if (!pkg.upgrade(have, ctx.log))
die('Update failed');
die(_('Update failed'));
}
if (length(missing)) {
ctx.phase(`Installing ${join(', ', missing)}`);
ctx.phase(sprintf(_('Installing %s'), join(', ', missing)));
if (!pkg.add(missing, ctx.log))
die('Installation failed');
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 ];
@@ -6,6 +6,7 @@
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`;
@@ -126,12 +127,16 @@ export function busy() {
return false;
};
/** The last job; a "running" one whose worker is gone (the lock is free) reads as failed. */
/**
* 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.error = _('The update stopped unexpectedly.');
j.finished = j.finished ?? time();
}
return j;
@@ -3,8 +3,9 @@
// 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.10.0';
export const VERSION = '0.16.0';
/** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline';
@@ -364,8 +365,14 @@ export function slog_restore() {
/* ---------- 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;
@@ -388,7 +395,7 @@ export function int2ip(n) {
* allowed networks use this; parse_cidr is the stricter one for subnets.
*/
export function cidr_any(s) {
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
let m = match(s ?? '', CIDR);
if (!m)
return null;
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
@@ -431,10 +438,10 @@ export function cloudflare_ip(a) {
/** 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);
@@ -543,11 +550,99 @@ export function valid_name(s) {
return type(s) == 'string' && ulength(trim(s)) > 0 && ulength(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
};
/** What valid_name wants, for the admin. */
export const NAME_RULE = 'Enter a name: up to 48 characters, without < > " or \\.';
/** 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). */
@@ -555,10 +650,25 @@ 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 || is_ip6(s));
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). */
@@ -570,11 +680,18 @@ export function valid_date(s) {
return l.year == +m[1] && l.mon == +m[2] && l.mday == +m[3];
};
// 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(translit(trim(`${s ?? ''}`)));
out = replace(out, /[^a-z0-9]+/g, '-');
out = replace(out, /^-+|-+$/g, '');
out = replace(out, NOT_LC_ALNUM, '-');
out = trim(out, '-');
return substr(out, 0, 32) || 'user';
};
@@ -583,8 +700,8 @@ export function slugify(s) {
* "telefon"): at most 40 characters, "device" when nothing is left.
*/
export function host_label(s) {
let l = replace(lc(translit(`${s ?? ''}`)), /[^a-z0-9]+/g, '-');
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 40), /-+$/g, '');
let l = replace(lc(translit(`${s ?? ''}`)), NOT_LC_ALNUM, '-');
l = rtrim(substr(trim(l, '-'), 0, 40), '-');
return l || 'device';
};
@@ -595,9 +712,9 @@ export function host_label(s) {
* refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left.
*/
export function tunnel_name(s) {
let l = replace(translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-');
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, '');
return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline';
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 ---------- */
@@ -657,9 +774,21 @@ 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 (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/))
if (!valid_iface(ifname))
return null;
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
if (!s)
@@ -6,17 +6,17 @@ import * as live from 'dawnline.live';
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 = [];
for (let i = n - 1; i >= 0; i--) {
let v = rec?.days?.[day_key_ago(i)];
push(out, v ? v[0] + v[1] : 0);
push(out, v ? [ v[0], v[1] ] : [ 0, 0 ]);
}
return out;
};
/** Daily totals (rx+tx) from the 1st of this month to today, oldest first (the portal's month chart). */
/** 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));
};
@@ -58,6 +58,7 @@ export function device_view(m, d, usage, dmp) {
m._reconnect ??= awg.reconnects();
let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]);
let p = m.people[d.person];
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) {
@@ -65,6 +66,7 @@ export function device_view(m, d, usage, dmp) {
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,
@@ -73,7 +75,7 @@ export function device_view(m, d, usage, dmp) {
disabled: d.disabled,
created: d.created,
created_by: d.created_by,
online: hs > 0 && live.online(dmp, d.id, peer),
online,
handshake: hs,
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
active: !!peer,
@@ -84,6 +86,21 @@ export function device_view(m, d, usage, dmp) {
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;
};
@@ -1,10 +1,12 @@
// 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; its state to
// RUN_DIR for the Health page. A cron job (libexec/dawnline/heartbeat) looks
// after the agent itself.
// 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';
@@ -34,57 +36,75 @@ function restart_services() {
}
/**
* What to look at: { id (= the Health check id), src, name (chip), who (the log's subject), ok,
* problem, back, detail?, repair: { what, run }? }. The log reads "<who> <problem> — <what>".
* 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.
push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) }));
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: 'Access rules', ok: nft.present(),
problem: 'are missing', back: 'are loaded again',
repair: { what: 'loading them again', run: () => apply.apply() },
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: 'Firewall', ok: fw == null,
problem: fw == 'off' ? "isn't running on this router (fw4): tunnels and the portal are closed"
: fw == 'changed' ? "rules for Dawnline were changed or removed" : "rules for Dawnline aren't loaded",
back: 'rules for Dawnline are in place again',
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: 'restoring them', run: () => { apply.apply(); system('fw4 -q reload'); } },
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: 'Personal portal', ok: health.tcp_listening(s.portal_port),
problem: `isn't answering on port ${s.portal_port}`, back: 'answers again',
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: 'restarting it', run: restart_services },
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: 'DNS for Home-only devices', ok: loop.resolver_running(),
problem: "isn't running", back: 'runs again',
repair: { what: 'restarting it', run: restart_services },
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: "can't reach Dawnline (luci.dawnline is missing in rpcd)", back: 'reaches Dawnline again',
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: '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') },
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;
}
@@ -107,7 +127,8 @@ export function run(m) {
x.ok = p.ok;
if (p.ok) {
if (x.reported)
slog(p.src, 'up', p.back + (x.stuck ? ' · restored' : x.tries ? ` (after ${x.tries} repair${x.tries > 1 ? 's' : ''})` : ''), null, p.who);
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;
@@ -128,7 +149,7 @@ export function run(m) {
if (busy)
continue;
if (p.repair?.max && x.tries >= p.repair.max && !x.reported) {
slog(p.src, 'error', `${p.problem} — not repaired again (${p.repair.max} repairs didn't help)`, p.detail?.(), p.who);
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;
}
@@ -142,7 +163,7 @@ export function run(m) {
// 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', `${p.problem} — ${x.tries} repairs didn't help`, p.detail?.(), p.who);
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;
@@ -151,13 +172,13 @@ export function run(m) {
x.next = now + WAIT[min(x.tries, length(WAIT) - 1)];
x.reported = true;
if (!x.stuck)
slog(p.src, 'repair', `${p.problem} — ${p.repair.what}`, p.detail?.(), p.who);
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', `couldn't be repaired: ${e.message}`, null, p.who);
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 });
@@ -168,18 +189,41 @@ export function run(m) {
write_json(STATE, { last: now, targets: t, repairs }, 0o644);
};
/** For the Health page: the watchdog's state and the newest log entries. */
/**
* 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: 'Agent', ok: beat > 0 && time() - beat < 180, tries: 0 } ];
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: x.name, ok: !!x.ok, tries: x.tries ?? 0 });
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: st.repairs ?? [],
targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: chip_name(m, n, r.id, r.name) })),
},
log: slog_read(200),
};
+5 -3
View File
@@ -7,7 +7,7 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
- `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`): traffic silence is no signal, a phone asleep is silent too.
- 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
@@ -16,13 +16,15 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
- 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.
- **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 all dump` (about 4 ms with process start), 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.
- **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
+1 -1
View File
@@ -15,7 +15,7 @@ Match the code around you: its naming, comment density and idiom win over person
- **Every module opens with a header comment**: what it owns, what it deliberately does not (and where that lives), and any invariant callers rely on (locks, files it writes, who may call it).
- **Layers point one way.** Pure helpers and the data model know nothing about the router or the UI; orchestration calls them, never the reverse. Dawnline's layers are in `backend.md`.
- **No god files, no grab-bag `ops`/`misc`/`kit` modules.** When a helper is used by one module, it stays private in that module.
- **Delete, don't deprecate.** When something is replaced, move every caller and remove the old code in the same change; no shims, no commented-out blocks.
- **Delete, don't deprecate.** When something is replaced, move every caller and remove the old code in the same change; no shims, no commented-out blocks. The same goes for its strings: new text is translated in the same change, removed text leaves the catalogs (`i18n.md`).
## Logic and state
+2 -2
View File
@@ -1,6 +1,6 @@
# Frontend (TypeScript: admin UI and portal)
Read with `code-standards.md` and, for anything visible, `ui-design.md`.
Read with `code-standards.md` and, for anything visible, `ui-design.md` and `i18n.md` (every visible string goes through `_()`). Portal work starts with `DESIGN.md` (its tokens, components and motion).
## Code
@@ -16,4 +16,4 @@ Read with `code-standards.md` and, for anything visible, `ui-design.md`.
## Checks
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm test`, `npm run build`; the rebuilt bundles under `package/` are committed (CI fails otherwise).
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm run lint`, `npm run knip`, `npm run i18n:check`, `npm test`, `npm run build`; the catalogs are committed, the bundles under `package/` are git-ignored (CI builds them before packaging).
+98
View File
@@ -0,0 +1,98 @@
# Translations (admin UI, portal, backend messages)
Dawnline is written in English and translated through gettext catalogs. Russian is the first translation. Read with `frontend.md` (and `backend.md` for messages the router sends).
## The rule
- **What is added is localized in the same change.** A new page, section, control, toast, error, check or log line in the admin UI, the portal or the backend comes with its strings wrapped (`_()`, `N_()`, `plural()`, `L_()`) and translated in every `ru.po`. Not "later": CI refuses a catalog with an untranslated string.
- **What is removed leaves nothing behind.** Deleting or rewording text deletes its old entries: `npm run i18n` drops every entry no code uses any more, and `npm run i18n:check` (CI) fails while a catalog still holds one. No dead entries, no hand-kept leftovers, no commented-out translations: the catalogs follow the code, as the code follows `code-standards.md` ("Delete, don't deprecate").
- **Every change to visible text is checked in Russian too**: the wording against the glossary below, the layout at narrow widths (Russian runs longer).
## How it fits together
- **Admin UI (LuCI).** Every visible string goes through LuCI's globals `_()` and `N_()`. The catalog is `package/luci-app-dawnline/po/ru/dawnline.po`; luci.mk compiles it with po2lmo into the separate package `luci-i18n-dawnline-ru` (`/usr/lib/lua/luci/i18n/dawnline.ru.lmo`, plus the uci-defaults that adds Russian to LuCI's languages). LuCI loads it when the page language is Russian (`luci.main.lang`, or `auto` with a Russian browser). Without the package everything stays English. The LuCI menu titles (`menu.d`) are in the same catalog.
- **Portal.** Not LuCI: it carries its own catalog (`web/src/portal/i18n/ru.po`, made into a lookup table at build time and bundled into `portal.js`), so it speaks Russian on every router, with or without the admin's package. `portal/i18n.ts` installs `_()`/`N_()` with LuCI's meaning, opens in the visitor's kept choice or the browser's language, and the language menu in the breadcrumb switches it in place. The demo's own strings are in `web/src/portal/demo/i18n/`.
- **Shared code** (`web/src/shared`) runs in both and is in both catalogs.
- **Backend messages** (ucode: `die()` texts, health checks, endpoint verdicts, the updater's phases) go through `_()` / `N_()` from `dawnline.i18n` and are in the `dawnline` catalog too. The admin page sends its language with every RPC call (`lang`, added by `web/src/admin/api.ts` and stripped by `rpcd/ucode/luci.dawnline`), the updater gets it from the job's start (`DAWNLINE_LANG`), the portal's CGI from `Accept-Language` (the portal's fetch sends the visitor's choice). `dawnline.i18n` reads LuCI's catalog through `luci.core`, so the backend speaks Russian where `luci-i18n-dawnline-ru` is installed; the portal page translates what reaches it in English from `portal.uc`, `devices.uc`, `core.uc` and `awg.uc` with its own catalog. The agent's and the CLI's terminal output stay English. Text the backend stores and shows later is stored as a code (or, for service log lines, as `L_()` templates) and put into words when it is read.
- **Delivery.** The release has `luci-i18n-dawnline-ru-<version>.{ipk,apk}` next to the app. `install.sh` adds it when LuCI is in Russian (its setting, or `luci-i18n-base-ru` installed) or with `--lang ru`; the updater installs it with every Dawnline update when it is installed; Components → Dawnline → Translation adds or removes it. LuCI reads a language's catalogs once per web server process, so each of these restarts uhttpd afterwards.
- **Collecting.** `npm run i18n` (in `web/`) reads the code and rewrites the `.pot` templates and the `.po` files: new strings are added untranslated, gone ones removed, translations kept (and reused across catalogs). `npm run i18n:check` (CI) fails when a catalog is out of date, a string is untranslated, or a translation lost a placeholder. After changing visible text: run `npm run i18n`, translate the new entries in each `ru.po`, commit the catalogs with the code.
## Writing strings
- **Every visible string is wrapped**: text, buttons, headings, toasts, errors, tooltips (`title`), `aria-label`, `placeholder`, `alt`, the page title, confirm dialogs, CSV headers. Not wrapped: product and protocol names standing alone (Dawnline, AmneziaWG, WireGuard, OpenWrt, LuCI), ids, keys, paths, commands, package names, CSS classes, URLs, values sent to the router, log/event ids, `console` output.
- **Literals only.** `_('Save')`, never `_(label)` or `` _(`Hello ${name}`) ``: the extractor cannot collect them and fails. Placeholders `%s` (or `%d`) are filled with `fmt()` from `shared/i18n.ts`: `fmt(_('Removed %s'), name)`.
- **Whole sentences.** Never glue a sentence from pieces (`'Removed ' + name + ' from ' + circle`, or `_('ends') + ' ' + date`): word order and case endings differ. One msgid per sentence with placeholders. Pieces joined by separators (`PC · 10.0.0.2 · online`) are separate facts and stay separate strings.
- **Elements inside a sentence** (a link, a `<b>`): `fill(_('Install it in %s'), link)` returns the children for `E()` / `h()`. The link text is its own `_()`.
- **Counts** go through `plural(n, '%s device', '%s devices')` (number formatted, both forms literals) or `N_(n, 'Device', 'Devices')` when the number is not in the text. Never `n === 1 ? … : …` or `` `${n} devices` ``: Russian has three forms (1 устройство, 2 устройства, 5 устройств), and 21 takes the singular. Use them even where English always has the plural.
- **Numbers and dates** in the page's language: `num(n)` (2,000 / 2 000), `num(v, 1)` for one decimal, `bytes()`, `fmtDay()`, `toLocaleDateString(locale(), …)`. Never a hard-coded `'en-GB'` or `toFixed()` for shown numbers.
- **Text is made when it is drawn**, inside functions, never at module level in the portal and the shared code (the portal changes language in place; the extractor refuses it there). A table of labels becomes a function: `kindLabel(k)` in `shared/format.ts`.
- **Context** when one English word means two things: `_('Off', 'state')` vs `_('Off', 'switch')`. Use it only for real clashes.
- **Whitespace and line breaks** are not part of a msgid: no leading/trailing spaces, no double spaces, no `\n` (LuCI squeezes whitespace before the lookup; po2lmo cannot carry newlines). Put spacing in the markup or the separator.
- **Keep the English as it is** when wrapping, except to turn a glued sentence into one with placeholders.
- **Other apps' labels** (the menus of AmneziaVPN, WireGuard and AmneziaWG in set-up steps) are quoted word for word, with a context of their own (`_('Create from QR code', 'WireGuard app')`), and translated with the app's own Russian from its sources (English where the app has no Russian). Where they come from is noted in `portal/setup.ts`.
- **Messages from the router** arrive in the page's language already (admin) or are translated with `routerText()` (portal): never glue them into a sentence of the page's own; ask the backend for a whole sentence instead.
## Writing backend messages
- `import { _, N_ } from 'dawnline.i18n';` and wrap literals only: `die(_('Backup not found.'))`, `die(sprintf(_('Download failed: %s'), asset))`, `sprintf(N_(n, '%d device', '%d devices'), n)`. Placeholders `%s` and `%d` only, filled after the lookup.
- `_()` inside functions only: rpcd keeps the modules loaded and the language changes with each call (the extractor refuses module-level calls).
- Wrap what a person reads in LuCI or the portal; leave ids, status values, command lines and sentinels alone.
- Messages a portal visitor can get belong in `portal.uc` or `devices.uc` and are best static sentences: the page can translate those without the package.
- **Service log lines** (`slog()` and the watchdog's problem/back/what texts) are written once, in English, by processes with no language (the agent), and read later. Mark their words with `L_()` instead of `_()`: `slog('awg', 'up', sprintf(L_('updated · %s → %s'), a, b), null, L_('System packages'))`. `L_` returns the English; the extractor collects it into the catalog and into `web/src/admin/events/log-templates.ts`, and the admin page matches each line against those templates and translates it (`logText()` in `events/model.ts`), values and nested templates included. Keep a template's English when you touch it (lines already in logs match it), and give the Russian the agreement its subject needs; a translation may start with «:» to go on after the subject («Сервер Home: AmneziaWG не работает»).
## Russian
Write like a careful Russian product (Telegram, Яндекс), not a word-for-word translation.
- **Tone:** polite and short, «вы» in lower case. Buttons and menu items are verbs in the infinitive (perfective where it fits): «Сохранить», «Удалить», «Скопировать», «Добавить устройство», «Изменить»; «Отмена» for Cancel, «Закрыть», «Готово», «Назад», «Далее».
- **States** in forms that fit any person: «На паузе» (not «Приостановлен/а»), «Доступ закончился», «В сети» / «Не в сети». Prefer constructions without gender; when unavoidable, masculine as the neutral form.
- **Typography:** «ёлочки» for quotes, «ё» where it belongs (ещё, всё, истёк), the ellipsis character «…». No em dashes (—): where a dash is needed, a plain one with spaces ( - ), or a colon or a comma (the catalog check refuses «—»). Ranges keep the en dash (1–32, 07:00–23:00). Numbers with a space before units: «1,5 ГБ», «20 Мбит/с».
- **Units:** Б, КБ, МБ, ГБ, ТБ; бит/с, кбит/с, Мбит/с, Гбит/с; «5 мин назад», «3 ч назад», «2 дн. назад»; «2 д 5 ч», «5 ч 12 мин», «12 мин».
- **Length:** Russian runs ~20–30% longer. Keep buttons, pills, tabs and segmented controls short (abbreviate or rephrase), and check the layout in the browser at narrow widths.
- **Product and technical names stay as they are:** Dawnline, AmneziaWG, AmneziaVPN, WireGuard, OpenWrt, LuCI, GitHub, Cloudflare, Let's Encrypt, DDNS, DNS, MTU, UDP, TCP, IPv4/IPv6, NAT, CGNAT, LAN, WAN, QR-код, opkg/apk.
### Glossary
| English | Russian |
|---|---|
| server | сервер |
| person / people (the page) | человек / люди («Люди»); Add person — «Добавить человека» |
| device | устройство |
| circle | круг |
| access | доступ |
| home network | домашняя сеть |
| internet | интернет |
| home network + internet | домашняя сеть и интернет |
| LAN Bypass (a device's option) | обход локальной сети («Обход локальной сети») |
| portal, personal link, personal page | портал, личная ссылка, личная страница |
| invite (card) | приглашение (карточка приглашения) |
| disguise; Off / Balanced / Maximum | маскировка; Выкл. / Сбалансированная / Максимальная |
| data limit | лимит трафика |
| usage, traffic | трафик |
| end date; ends in 3 days | дата окончания; закончится через 3 дня |
| allowed hours; outside allowed hours | часы доступа; вне часов доступа |
| pause / resume; paused | приостановить / возобновить; на паузе |
| online / offline; last seen 12 min ago | в сети / не в сети; «В сети 12 мин назад» (not «Было в сети») |
| set up a device; setup | настроить устройство; настройка |
| app | приложение |
| key, public key, private key | ключ, публичный ключ, приватный ключ |
| configuration file (.conf) | файл конфигурации (.conf) |
| endpoint, public address | адрес сервера, публичный адрес |
| port, port forward | порт, проброс порта |
| tunnel | туннель |
| handshake | рукопожатие |
| router | роутер |
| firewall, zone | межсетевой экран, зона |
| interface, network | интерфейс, сеть |
| certificate | сертификат |
| Overview / Servers / People / Activity | Обзор / Серверы / Люди / События |
| Diagnostics / Health / Logs | Диагностика / Состояние / Журналы |
| Settings / Components / Updates | Настройки / Компоненты / Обновления |
| backup, restore | резервная копия, восстановить |
| check (health), fix | проверка, исправить |
| What's new | Что нового |
| Advanced | Дополнительно |
| watchdog | автовосстановление |
| places (map) | места |
| Copied | Скопировано |
| Undo | Отменить |
+3 -1
View File
@@ -2,6 +2,8 @@
The bar is a modern product UI (Linear / Vercel / Raycast level), not a "native" LuCI form. A plain label + input row, a bare radio list, three columns of check marks or a text dump is a first draft, never the result.
**The portal has its own design system, `DESIGN.md`** (repo root): read it before any portal work, mocks included. Build from its tokens, components and spring tokens, follow its Do's and Don'ts, and update it in the same change when the portal's look or motion changes. The admin follows this file and the LuCI theme.
## Approach
- **Mock first.** Any visible change beyond a one-line fix: show a mockup (2–4 genuinely different options when the direction is open) with a recommendation, then build the chosen one. Do not start coding a layout the user has not seen.
@@ -29,4 +31,4 @@ A mock is judged against the page it will live on, so it must already look like
## Done means seen
Deploy, then look at it in the browser (desktop width, and narrow when layout changes) before reporting. Check modals and drawers stack correctly and long values do not overflow.
Deploy, then look at it in the browser (desktop width, and narrow when layout changes) before reporting. Check modals and drawers stack correctly and long values do not overflow. Look at it in Russian too: a visible change is localized in the same change (`i18n.md`), and Russian text is longer.
+32 -9
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash
# Build the release packages with the OpenWrt SDK in Docker (as CI does):
# scripts/build-packages.sh [ipk|apk|all]
# Output: dist/luci-app-dawnline-<version>.{ipk,apk} and dist/sha256sums.txt
# Output: dist/luci-app-dawnline-<version>.{ipk,apk}, a translation package per
# po/<lang> (dist/luci-i18n-dawnline-<lang>-<version>.{ipk,apk}) and dist/sha256sums.txt
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
@@ -16,6 +17,11 @@ APK_SDK="${APK_SDK:-itdoginfo/openwrt-sdk-apk:25.12.3}"
grep -q "^export const VERSION = '$VERSION';" "$APP/root/usr/share/ucode/dawnline/util.uc" || { echo "util.uc VERSION != $VERSION" >&2; exit 1; }
grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/package.json version != $VERSION" >&2; exit 1; }
# The web bundles are not committed: web/ builds them (npm run build).
for f in htdocs/luci-static/resources/dawnline/app.js root/usr/share/dawnline/portal/assets/portal.js root/usr/share/dawnline/portal/assets/portal.css; do
[ -f "$APP/$f" ] || { echo "$APP/$f is missing: run 'npm run build' in web/" >&2; exit 1; }
done
mkdir -p "$OUT"
build() {
local type="$1" sdk="$2" tag="dawnline-build:$1"
@@ -25,13 +31,29 @@ build() {
rm -rf "$OUT/.$type" && mkdir -p "$OUT/.$type"
docker cp "$id:/builder/out/." "$OUT/.$type/"
docker rm "$id" >/dev/null
local f
f="$(find "$OUT/.$type" -type f -name "*.$type" | head -n1)"
[ -n "$f" ] || { echo "no .$type built" >&2; exit 1; }
# ipk names use underscores (luci-app-dawnline_0.1.0-r1_all.ipk): one stable name for both.
mv "$f" "$OUT/luci-app-dawnline-$VERSION.$type"
local f name
for f in "$OUT/.$type"/*."$type"; do
[ -f "$f" ] || continue
# ipk names use underscores (luci-app-dawnline_0.1.0-r1_all.ipk), apk names
# dashes: one stable name per package for both, its name and the version.
name="$(basename "$f")"
name="${name%%[_-][0-9]*}"
mv "$f" "$OUT/$name-$VERSION.$type"
echo "$OUT/$name-$VERSION.$type"
done
rm -rf "$OUT/.$type"
echo "$OUT/luci-app-dawnline-$VERSION.$type"
for name in luci-app-dawnline $(i18n_packages); do
[ -f "$OUT/$name-$VERSION.$type" ] || { echo "no $name .$type built" >&2; exit 1; }
done
}
# The translation packages luci.mk makes: one per po/<lang>.
i18n_packages() {
local d
for d in "$APP"/po/*/; do
d="$(basename "$d")"
[ "$d" = templates ] || printf 'luci-i18n-dawnline-%s\n' "$d"
done
}
case "$WHAT" in
@@ -43,9 +65,10 @@ esac
(
cd "$OUT"
set -- luci-app-dawnline-"$VERSION".ipk luci-app-dawnline-"$VERSION".apk
files=""
for f in "$@"; do [ -f "$f" ] && files="$files $f"; done
for name in luci-app-dawnline $(i18n_packages); do
for f in "$name-$VERSION".ipk "$name-$VERSION".apk; do [ -f "$f" ] && files="$files $f"; done
done
# shellcheck disable=SC2086
if command -v sha256sum >/dev/null; then sha256sum $files; else shasum -a 256 $files; fi > sha256sums.txt
)
+18 -2
View File
@@ -1,7 +1,10 @@
#!/usr/bin/env bash
# Build the web bundles and pack luci-app-dawnline as a filesystem overlay
# tarball: dist/luci-app-dawnline-<version>.tar.gz (paths relative to /).
# This is the asset the in-app updater and install.sh install.
# tarball: dist/luci-app-dawnline-<version>.tar.gz (paths relative to /), with
# the translations as their packages lay them out (the catalogs compiled by
# web/i18n/lmo.ts, byte for byte po2lmo's, and the uci-defaults that adds the
# language to LuCI). scripts/deploy.sh installs it for development; releases
# are the .ipk/.apk packages (build-packages.sh).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
@@ -15,10 +18,23 @@ grep -q "PKG_VERSION:=$VERSION\$" "$APP/Makefile" || { echo "Makefile PKG_VERSIO
grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/package.json version != $VERSION" >&2; exit 1; }
[ "${SKIP_WEB:-0}" = 1 ] || (cd "$ROOT/web" && npm run --silent ci)
# With SKIP_WEB=1 the bundles come from an earlier build (they are not committed).
for f in htdocs/luci-static/resources/dawnline/app.js root/usr/share/dawnline/portal/assets/portal.js root/usr/share/dawnline/portal/assets/portal.css; do
[ -f "$APP/$f" ] || { echo "$APP/$f is missing: run 'npm run build' in web/" >&2; exit 1; }
done
mkdir -p "$STAGE/www" "$OUT"
cp -R "$APP/root/." "$STAGE/"
cp -R "$APP/htdocs/." "$STAGE/www/"
for po in "$APP"/po/*/dawnline.po; do
l="$(basename "$(dirname "$po")")"
[ "$l" = templates ] && continue
mkdir -p "$STAGE/usr/lib/lua/luci/i18n"
node "$ROOT/web/i18n/lmo.ts" "$po" "$STAGE/usr/lib/lua/luci/i18n/dawnline.$l.lmo"
# The name LuCI lists the language by (luci.mk's LUCI_LANG.<lang>).
case "$l" in ru) name='Русский (Russian)' ;; *) name="$l" ;; esac
printf "uci set luci.languages.%s='%s'; uci commit luci\n" "$l" "$name" > "$STAGE/etc/uci-defaults/luci-i18n-dawnline-$l"
done
chmod 755 "$STAGE/usr/bin/dawnline" "$STAGE/usr/libexec/dawnline/agent" "$STAGE/usr/libexec/dawnline/updater" "$STAGE/usr/libexec/dawnline/resolver" "$STAGE/usr/libexec/dawnline/postupdate" \
"$STAGE/etc/init.d/dawnline" "$STAGE/etc/uci-defaults/90_dawnline" "$STAGE/etc/hotplug.d/iface/95-dawnline" \
"$STAGE/usr/share/dawnline/portal/www/cgi-bin/portal" "$STAGE/usr/share/dawnline/portal/cgi.uc"
+262
View File
@@ -0,0 +1,262 @@
#!/usr/bin/env node
// Capture the raw README screenshots of the personal portal into
// docs/screenshots/raw/ (2x PNG): the page (portal.png) and the three steps of
// adding a phone in front of it (portal-add-1..3.png: Add a device, the set-up
// sheet waiting, the phone connected), each sheet alone on a transparent page.
// The Russian ones take a -ru suffix. scripts/frame-screenshots.py then frames
// them for the README.
//
// The portal is its demo build (web/dist/demo, `npm run build:demo`, built
// first unless --no-build): the real portal over a router that lives in the
// page, so no one's real page is shown and adding a device adds none. It is
// opened as https://vpn.example.com/<code> and every file is answered from the
// build over the DevTools protocol (scripts/cdp.mjs), so its personal link
// reads like one. The cast is made up here: the demo's own three devices (the
// ones its router keeps, so adding one works) under other names, three more
// shown beside them, and the person's and the server's names.
//
// scripts/capture-portal.mjs [--lang en,ru] [--no-build]
import { execFileSync } from 'node:child_process';
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, extname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { die, launch, sleep } from './cdp.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const WEB = join(ROOT, 'web');
const DEMO = join(WEB, 'dist', 'demo');
const RAW = join(ROOT, 'docs', 'screenshots', 'raw');
const SCALE = 2;
/** The page's width, as the README shot always had it. */
const WIDTH = 1320;
/** Around a sheet in its capture: left, top, right, bottom (frame-screenshots.py FLOW_MARGIN). */
const MARGIN = [56, 40, 56, 72];
const ORIGIN = 'https://vpn.example.com';
/** The demo's personal link (web/src/portal/demo/index.html, data-base). */
const CODE = 'kelino-sarupa-motive';
const NAMES = { person: 'Aemeath', server: 'Ames Gateway' };
/** The device this page is open on (its card says "This device"). */
const HERE = 'MacBook Air';
/** The phone added in the steps. */
const NEW = 'Pixel 9';
const SLOTS = 8;
const args = { langs: ['en', 'ru'], build: true };
for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i];
if (a === '--lang') args.langs = (process.argv[++i] ?? die('--lang needs a value')).split(',');
else if (a === '--no-build') args.build = false;
else die(`unknown argument ${a}`);
}
const DAY = 86400;
const now = () => Math.floor(Date.now() / 1000);
/**
* What the demo's router keeps (its DemoDb, in localStorage before the page loads): three devices, so one more
* fits its limit of four and the steps add it for real.
*/
function demoDb(t) {
const dev = (id, name, kind, n, gb, hs, days) => ({
id,
name,
kind,
n,
gb,
hs,
connectAt: 0,
created: t - days * DAY,
by: 'admin',
stale: false,
});
return {
scenario: 'normal',
devs: [
dev('d_mac', HERE, 'computer', 2, 5.4, t - 20, 60),
dev('d_iph', 'iPhone 16', 'phone', 3, 2.3, t - 40, 58),
dev('d_gal', 'Galaxy S24', 'phone', 4, 0.66, t - 26 * 3600, 30),
],
next: 5,
};
}
/**
* The page's side, before it loads: the language, the router's devices, the demo's own chrome hidden, and every
* answer of its router touched on the way to the page (the names, this device, the slots, the devices shown
* beside the ones it keeps).
*/
const prelude = (lang, db) => `(() => {
try {
localStorage.setItem('dl.lang', ${JSON.stringify(lang)});
localStorage.setItem('dawnline-demo', ${JSON.stringify(JSON.stringify(db))});
} catch {}
const NAMES = ${JSON.stringify(NAMES)}, HERE = ${JSON.stringify(HERE)}, SLOTS = ${SLOTS};
const extra = (devs, t) => {
const like = (d, o) => ({ ...d, link: null, setup: null, online: false, config_stale: false, created_by: 'admin', ...o });
const mac = devs.find((d) => d.name === HERE) ?? devs[0];
const none = { handshake: 0, endpoint: '', month: [0, 0], total: [0, 0], spark: mac.spark.map(() => [0, 0]) };
const scale = (p, f) => p.map((v) => Math.round(v * f));
return [
like(mac, { id: 'x_tv', name: 'Living room TV', kind: 'other', address: '10.8.0.6', handshake: t - 3 * 3600,
config_stale: true, month: scale(mac.month, 1.13), total: scale(mac.total, 1.4),
spark: mac.spark.map((p) => scale(p, 1.1)), created: t - 45 * 86400 }),
like(mac, { id: 'x_ipad', name: 'iPad', kind: 'tablet', address: '10.8.0.7', created: t - 2 * 86400, ...none }),
like(mac, { id: 'x_rtr', name: 'Cottage router', kind: 'router', address: '10.8.0.8', created: t - 86400, ...none }),
];
};
const touch = (st) => {
if (!st?.person) return;
const own = st.person.devices;
st.person.name = NAMES.person;
if (st.server) st.server.name = NAMES.server;
st.person.devices = [...own, ...extra(own, st.now)];
st.person.device_limit = SLOTS;
st.can_add = st.person.devices.length < SLOTS;
st.here = own.find((d) => d.name === HERE)?.id ?? null;
};
let inner = window.fetch;
Object.defineProperty(window, 'fetch', {
configurable: true,
get: () => inner,
// The demo's router takes fetch over (demo/serve.ts): its answers pass through here.
set: (f) => {
inner = async (...a) => {
const r = await f(...a);
if (!String(a[0] instanceof Request ? a[0].url : a[0]).includes('/api/')) return r;
let j;
try { j = await r.clone().json(); } catch { return r; }
touch(j?.person ? j : j?.state);
return new Response(JSON.stringify(j), { status: r.status, headers: { 'content-type': 'application/json' } });
};
},
});
addEventListener('DOMContentLoaded', () => {
const s = document.createElement('style');
// The demo's chip, GitHub knob and set-up state switch go, and the path takes the row again, as on a router's
// page.
s.textContent = '.dm-chip, .dm-gh, .dm-way { display: none !important; } .cr-path { flex: 1 !important; }';
document.head.append(s);
});
})()`;
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml' };
/** Answer the page's requests from the demo build: its page for the personal link, its files by name. */
async function serve(page) {
page.on('Fetch.requestPaused', async (e) => {
const path = new URL(e.request.url).pathname;
const file = path === `/${CODE}` || path === '/' ? 'index.html' : path.slice(1);
let body;
try {
body = readFileSync(join(DEMO, file));
} catch {
await page.send('Fetch.fulfillRequest', { requestId: e.requestId, responseCode: 404, body: '' }).catch(() => {});
return;
}
await page.send('Fetch.fulfillRequest', {
requestId: e.requestId,
responseCode: 200,
responseHeaders: [{ name: 'Content-Type', value: TYPES[extname(file)] ?? 'application/octet-stream' }],
body: body.toString('base64'),
});
});
await page.send('Fetch.enable', { patterns: [{ urlPattern: `${ORIGIN}/*`, requestStage: 'Request' }] });
}
async function shoot(page, file, clip) {
const { data } = await page.send('Page.captureScreenshot', {
format: 'png',
clip: { ...clip, scale: 1 },
captureBeyondViewport: true,
});
writeFileSync(join(RAW, file), Buffer.from(data, 'base64'));
console.log(`${file}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
}
// The page's content: everything on screen but full-width or full-height wrappers, 36px around it (as the
// README shot always was; what waits off screen, as a field's measuring copy does, is no content).
const PAGE_CLIP = `(() => {
let l = innerWidth, r = 0, b = 0;
for (const e of document.querySelectorAll('#app *')) {
const x = e.getBoundingClientRect();
if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue;
if (x.left < 0 || x.right > innerWidth) continue;
l = Math.min(l, x.left);
r = Math.max(r, x.right);
b = Math.max(b, x.bottom);
}
return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 };
})()`;
// The open sheet alone: the page and the scrim out of sight on a transparent page, MARGIN around the sheet.
const SHEET_CLIP = `(() => {
const r = document.querySelector('.sheet-root.open .sheet').getBoundingClientRect();
const [l, t, rr, b] = ${JSON.stringify(MARGIN)};
return { x: r.left - l, y: r.top - t, width: r.width + l + rr, height: r.height + t + b };
})()`;
const ALONE = `(() => {
const s = document.createElement('style');
s.id = 'alone';
s.textContent = 'html, body { background: transparent !important; } #app { visibility: hidden !important; } .scrim { display: none !important; }';
document.head.append(s);
})()`;
async function capture(lang) {
const suffix = lang === 'en' ? '' : `-${lang}`;
const b = await launch([`--lang=${lang}`]);
const { page, evaluate, go, waitSel } = b;
try {
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] });
await page.send('Emulation.setDeviceMetricsOverride', { width: WIDTH, height: 1400, deviceScaleFactor: SCALE, mobile: false });
// Where the page paints nothing (a sheet alone), the capture is transparent.
await page.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });
await serve(page);
await page.send('Page.addScriptToEvaluateOnNewDocument', { source: prelude(lang, demoDb(now())) });
await go(`${ORIGIN}/${CODE}`);
await waitSel('.dev[data-id]');
await sleep(2500);
await shoot(page, `portal${suffix}.png`, await evaluate(PAGE_CLIP));
// 1: Add a device, a phone, its name typed in.
await evaluate(`document.querySelector('.dev.add').click()`);
await waitSel('.sheet-root.open .kinds');
await sleep(900);
await evaluate(`document.querySelectorAll('.sheet-root.open .kind')[1].click()`);
await sleep(500);
await evaluate(`(() => { const i = document.querySelector('.sheet-root.open .field input'); i.focus(); i.select(); })()`);
await page.send('Input.insertText', { text: NEW });
await evaluate(`document.activeElement.blur()`);
await sleep(900);
await evaluate(ALONE);
await shoot(page, `portal-add-1${suffix}.png`, await evaluate(SHEET_CLIP));
await evaluate(`document.getElementById('alone').remove()`);
// 2: the set-up sheet, waiting for the phone, its link open as a code for the phone's camera (the page
// opens on the app's row, whose code a key makes too dense to read at this size).
await evaluate(`document.querySelector('.sheet-root.open .field .go').click()`);
await waitSel('.sheet-root.open .way');
await sleep(1200);
await evaluate(`document.querySelector('.sheet-root.open .acc-row:not(.open) .acc-head').click()`);
await sleep(1500);
await evaluate(ALONE);
await shoot(page, `portal-add-2${suffix}.png`, await evaluate(SHEET_CLIP));
await evaluate(`document.getElementById('alone').remove()`);
// 3: connected (the demo's phone does within 6-9 s), what was under the way folded away.
await waitSel('.sheet-root.open .way.done', 15000);
await sleep(1150);
await evaluate(ALONE);
await shoot(page, `portal-add-3${suffix}.png`, await evaluate(SHEET_CLIP));
page.close();
} finally {
await b.close();
}
}
async function main() {
if (args.build) execFileSync('npm', ['run', '--silent', 'build:demo'], { cwd: WEB, stdio: 'inherit' });
for (const lang of args.langs) await capture(lang);
}
main().catch((e) => die(e.message));
+44 -143
View File
@@ -1,29 +1,33 @@
#!/usr/bin/env node
// Capture the raw README screenshots from a live router into
// Capture the raw README screenshots of the admin pages from a live router into
// docs/screenshots/raw/<name>.png (2x PNG); scripts/frame-screenshots.py then
// puts them into a browser window for the README.
// frames them for the README. The portal's come from its demo instead
// (scripts/capture-portal.mjs): no one's real page, and adding a device there adds none.
//
// Drives a headless Chromium (BROWSER=/path/to/chrome, default: Brave or Chrome
// on macOS) over the DevTools protocol, no npm packages. Signs in to LuCI with
// on macOS) over the DevTools protocol (scripts/cdp.mjs). Signs in to LuCI with
// the password from LUCI_PASSWORD or asked on the terminal; the session lives
// only in a throwaway profile (LUCI_USER picks another user than root). Nothing on the router is changed.
//
// scripts/capture-screenshots.mjs [--router https://router.lan] [--person id]
// [--mask real=shown ...] [--name real=shown ...]
// [--only overview,people] [--demo]
// [--only overview,people] [--demo] [--lang ru]
//
// --lang asks LuCI for the pages in that language (its catalog, po/<lang>/dawnline.po;
// the router's LuCI language left on auto) and names the captures <name>-<lang>.png
// for that README (README_ru.md); English (the default) keeps <name>.png.
// --mask replaces text on every page before the capture (a domain, a name);
// --name does the same for a person's name in any case, and for their initials.
// Public IPv4 addresses are always swapped for documentation ones (203.0.113.x).
// --demo shows a made-up cast instead of the router's people (scripts/screenshot-demo.mjs):
// the router's answers are rewritten in the headless browser on their way to the page.
import { execFileSync, spawn } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { execFileSync } from 'node:child_process';
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createInterface } from 'node:readline';
import { die, launch, sleep } from './cdp.mjs';
import { demoRpc } from './screenshot-demo.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -37,6 +41,7 @@ const args = {
names: [],
only: [],
demo: false,
lang: 'en',
};
for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i];
@@ -47,8 +52,26 @@ for (let i = 2; i < process.argv.length; i++) {
else if (a === '--name') args.names.push(v().split('=', 2));
else if (a === '--only') args.only = v().split(',');
else if (a === '--demo') args.demo = true;
else if (a === '--lang') args.lang = v();
else die(`unknown argument ${a}`);
}
const SUFFIX = args.lang === 'en' ? '' : `-${args.lang}`;
/** The admin's catalog for --lang: msgid -> msgstr, the entries without a context (English: none). */
const CATALOG = (() => {
const out = new Map();
if (args.lang === 'en') return out;
let po;
try {
po = readFileSync(join(ROOT, 'package', 'luci-app-dawnline', 'po', args.lang, 'dawnline.po'), 'utf8');
} catch {
die(`no admin catalog for --lang ${args.lang}`);
}
for (const m of po.matchAll(/^(msgctxt .*\n)?msgid "(.*)"\nmsgstr "(.*)"$/gm)) if (!m[1] && m[3]) out.set(m[2], m[3]);
return out;
})();
/** A button's words as the page shows them in --lang (the pages are clicked by what they say). */
const tr = (id) => CATALOG.get(id) ?? id;
if ([...args.mask, ...args.names].some((m) => m.length !== 2 || !m[0])) die('--mask and --name take real=shown');
/** As shared/format initials(): first letters of the first and last word, or the first two of one word. */
@@ -60,11 +83,6 @@ for (const [real, shown] of args.names)
args.mask.push([real, shown], [real.toLowerCase(), shown.toLowerCase()], [real.toUpperCase(), shown.toUpperCase()]);
const INITIALS = args.names.map(([real, shown]) => [initials(real), initials(shown)]);
function die(msg) {
console.error(msg);
process.exit(1);
}
const LUCI = `${args.router}/cgi-bin/luci/admin/network/dawnline`;
const USER = process.env.LUCI_USER || 'root';
@@ -93,7 +111,7 @@ const SHOTS = [
ready: '.dl-srvov .dl-panel.flush .maplibregl-canvas',
// The map shows the last 30 days, not only who is online now.
prep: `(() => {
const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === '30 days');
const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === ${JSON.stringify(tr('30 days'))});
b?.click();
})()`,
settle: 6000,
@@ -113,7 +131,7 @@ const SHOTS = [
ready: '.dl-grid-person .dl-row',
// Where they connected from, on the map.
prep: `(() => {
const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === 'Show map');
const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === ${JSON.stringify(tr('Show map'))});
b?.click();
})()`,
settle: 6000,
@@ -131,25 +149,6 @@ const SHOTS = [
return { x: c.x, y: 0, width: c.w, height: cut };
})()`,
},
{
name: 'portal',
url: (s) => s.portal,
width: 1320,
ready: 'body',
settle: 3000,
// The content: everything but full-width or full-height wrappers, 36px around it.
clip: `(() => {
let l = innerWidth, r = 0, b = 0;
for (const e of document.body.querySelectorAll('*')) {
const x = e.getBoundingClientRect();
if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue;
l = Math.min(l, x.left);
r = Math.max(r, x.right);
b = Math.max(b, x.bottom);
}
return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 };
})()`,
},
];
const MASK = `((pairs, inits) => {
@@ -198,87 +197,20 @@ async function password() {
}
}
function findBrowser() {
const c = [
process.env.BROWSER,
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/usr/bin/chromium',
'/usr/bin/google-chrome',
];
return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome');
}
/** A page over the DevTools protocol: send(method, params) and waitFor(event). */
async function connect(wsUrl) {
const ws = new WebSocket(wsUrl);
await new Promise((ok, fail) => {
ws.onopen = ok;
ws.onerror = fail;
});
let id = 0;
const pending = new Map();
const waiters = [];
const listeners = [];
ws.onmessage = (m) => {
const msg = JSON.parse(m.data);
if (msg.id && pending.has(msg.id)) {
const { ok, fail } = pending.get(msg.id);
pending.delete(msg.id);
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
} else if (msg.method) {
for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
for (const w of waiters.filter((x) => x.method === msg.method)) {
waiters.splice(waiters.indexOf(w), 1);
w.ok(msg.params);
}
}
};
const send = (method, params = {}) =>
new Promise((ok, fail) => {
pending.set(++id, { ok, fail });
ws.send(JSON.stringify({ id, method, params }));
});
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
const on = (method, fn) => listeners.push({ method, fn });
return { send, waitFor, on, close: () => ws.close() };
}
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
async function main() {
const pass = await password();
const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-'));
const chrome = spawn(
findBrowser(),
[
'--headless=new',
'--remote-debugging-port=0',
`--user-data-dir=${profile}`,
// The router's certificate is usually for its public name, not router.lan.
'--ignore-certificate-errors',
'--hide-scrollbars',
'--no-first-run',
'--no-default-browser-check',
// MapLibre needs WebGL; headless gets it from SwiftShader.
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
'about:blank',
],
{ stdio: 'ignore' },
);
// The router's certificate is usually for its public name, not router.lan.
const b = await launch(['--ignore-certificate-errors', `--lang=${args.lang}`]);
const { page, evaluate, go, waitSel } = b;
try {
const portFile = join(profile, 'DevToolsActivePort');
for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100);
const port = readFileSync(portFile, 'utf8').split('\n')[0];
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
await page.send('Page.enable');
// LuCI on auto speaks the browser's language: this one, whatever this computer's is.
await page.send('Network.enable');
await page.send('Network.setExtraHTTPHeaders', { headers: { 'Accept-Language': args.lang } });
await page.send('Emulation.setEmulatedMedia', {
features: [{ name: 'prefers-color-scheme', value: 'dark' }],
});
// The person shown on the Person page; known once People has loaded (or from --person).
const s = { person: args.person, portal: '' };
const s = { person: args.person };
if (args.demo) {
page.on('Fetch.requestPaused', async (e) => {
try {
@@ -302,27 +234,6 @@ async function main() {
});
}
const evaluate = async (expression) => {
const r = await page.send('Runtime.evaluate', {
expression,
awaitPromise: true,
returnByValue: true,
});
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
return r.result.value;
};
const go = async (url) => {
const loaded = page.waitFor('Page.loadEventFired');
await page.send('Page.navigate', { url });
await loaded;
};
const waitSel = async (sel, ms = 20000) => {
for (let t = 0; t < ms; t += 250) {
if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return;
await sleep(250);
}
throw new Error(`timed out waiting for ${sel}`);
};
// A tall window: Outline scrolls #maincontent, not the page, so it must hold everything.
const viewport = (width, height = 2600) =>
page.send('Emulation.setDeviceMetricsOverride', {
@@ -350,24 +261,16 @@ async function main() {
);
}
// The person to show (the first one on People unless --person) and their personal link.
// The person to show: the first one on People unless --person.
await go(`${LUCI}/server?section=people`);
await waitSel('.dl-srvbody a[href*="dawnline/person"]');
if (!s.person)
s.person = await evaluate(`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`);
s.portal = await evaluate(`L.require('rpc').then((rpc) =>
rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)}))
.then((r) => r.link ?? r.links?.[0] ?? '')`);
for (const shot of SHOTS) {
if (args.only.length && !args.only.includes(shot.name)) continue;
const url = shot.url(s);
if (!url) {
console.log(`skip ${shot.name}: no URL (the portal is off?)`);
continue;
}
await viewport(shot.width);
await go(url);
await go(shot.url(s));
await waitSel(shot.ready);
await sleep(2000);
if (shot.prep) await evaluate(shot.prep);
@@ -379,14 +282,12 @@ async function main() {
clip: { ...clip, scale: 1 },
captureBeyondViewport: true,
});
writeFileSync(join(RAW, `${shot.name}.png`), Buffer.from(data, 'base64'));
console.log(`${shot.name}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
writeFileSync(join(RAW, `${shot.name}${SUFFIX}.png`), Buffer.from(data, 'base64'));
console.log(`${shot.name}${SUFFIX}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
}
page.close();
} finally {
chrome.kill();
await sleep(300);
rmSync(profile, { recursive: true, force: true });
await b.close();
}
}
+122
View File
@@ -0,0 +1,122 @@
// A headless Chromium driven over the DevTools protocol, no npm packages: what
// the README screenshot scripts share (capture-screenshots.mjs from a router,
// capture-portal.mjs from the portal demo). BROWSER=/path/to/chrome picks the
// browser (default: Brave or Chrome on macOS); its profile is a throwaway one.
import { spawn } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
export const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
export function die(msg) {
console.error(msg);
process.exit(1);
}
export function findBrowser() {
const c = [
process.env.BROWSER,
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/usr/bin/chromium',
'/usr/bin/google-chrome',
];
return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome');
}
/** A page over the DevTools protocol: send(method, params), waitFor(event) and on(event, fn). */
export async function connect(wsUrl) {
const ws = new WebSocket(wsUrl);
await new Promise((ok, fail) => {
ws.onopen = ok;
ws.onerror = fail;
});
let id = 0;
const pending = new Map();
const waiters = [];
const listeners = [];
ws.onmessage = (m) => {
const msg = JSON.parse(m.data);
if (msg.id && pending.has(msg.id)) {
const { ok, fail } = pending.get(msg.id);
pending.delete(msg.id);
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
} else if (msg.method) {
for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
for (const w of waiters.filter((x) => x.method === msg.method)) {
waiters.splice(waiters.indexOf(w), 1);
w.ok(msg.params);
}
}
};
const send = (method, params = {}) =>
new Promise((ok, fail) => {
pending.set(++id, { ok, fail });
ws.send(JSON.stringify({ id, method, params }));
});
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
const on = (method, fn) => listeners.push({ method, fn });
return { send, waitFor, on, close: () => ws.close() };
}
/**
* Start the browser headless on a fresh profile and connect to its first page. `flags` go on its command line
* (a language, certificate errors). Returns the page, its helpers, and close() that ends the browser and removes
* the profile.
*/
export async function launch(flags = []) {
const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-'));
const chrome = spawn(
findBrowser(),
[
'--headless=new',
'--remote-debugging-port=0',
`--user-data-dir=${profile}`,
'--hide-scrollbars',
'--no-first-run',
'--no-default-browser-check',
// MapLibre needs WebGL; headless gets it from SwiftShader.
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
...flags,
'about:blank',
],
{ stdio: 'ignore' },
);
const close = async () => {
chrome.kill();
await sleep(300);
rmSync(profile, { recursive: true, force: true });
};
try {
const portFile = join(profile, 'DevToolsActivePort');
for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100);
const port = readFileSync(portFile, 'utf8').split('\n')[0];
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
await page.send('Page.enable');
const evaluate = async (expression) => {
const r = await page.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
return r.result.value;
};
const go = async (url) => {
const loaded = page.waitFor('Page.loadEventFired');
await page.send('Page.navigate', { url });
await loaded;
};
const waitSel = async (sel, ms = 20000) => {
for (let t = 0; t < ms; t += 250) {
if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return;
await sleep(250);
}
throw new Error(`timed out waiting for ${sel}`);
};
return { page, evaluate, go, waitSel, close };
} catch (e) {
await close();
throw e;
}
}
+5
View File
@@ -20,6 +20,11 @@ ls -d /root/dawnline-predeploy-* 2>/dev/null | sort | head -n -5 | xargs -r rm -
tar -xozf /tmp/luci-app-dawnline.tar.gz -C /
rm -f /tmp/luci-app-dawnline.tar.gz
sh /etc/uci-defaults/90_dawnline && rm -f /etc/uci-defaults/90_dawnline
for f in /etc/uci-defaults/luci-i18n-dawnline-*; do
if [ -f "$f" ]; then sh "$f" && rm -f "$f"; fi
done
# LuCI reads a language's catalogs once per web server: the new ones need a fresh one.
/etc/init.d/uhttpd restart
sleep 1
ubus list luci.dawnline >/dev/null && echo "luci.dawnline registered (backup: /root/dawnline-predeploy-$ts)"
REMOTE
+8 -9
View File
@@ -2,7 +2,8 @@
"""Frame the README screenshots the way the portal draws its own surfaces.
Raw captures live in docs/screenshots/raw/<name>.png at SCALE device pixels
per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images
per CSS pixel (scripts/capture-screenshots.mjs takes the admin's from a router,
scripts/capture-portal.mjs the portal's from its demo); the framed images
are written to docs/screenshots/<name>.png at the same scale. Each page sits on
a panel like the portal's sheets (#121212, radius 36, 16px around it, the page
inside at radius 20) on the portal's own black. A shot in FLOWS gets its steps
@@ -22,14 +23,13 @@ import tempfile
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
RAW = os.path.join(ROOT, 'docs', 'screenshots', 'raw')
OUT = os.path.join(ROOT, 'docs', 'screenshots')
FONT = os.path.join(ROOT, 'package', 'luci-app-dawnline', 'root', 'usr', 'share', 'dawnline', 'portal', 'assets',
'geist-latin-wght-normal.woff2')
SHOTS = ['overview', 'people', 'person', 'portal']
# name -> the steps in front of its page, in order (raw captures). Taken with demo data, not on a router:
# adding a device there would add one.
SHOTS = ['overview', 'people', 'person', 'portal', 'overview-ru', 'people-ru', 'person-ru', 'portal-ru']
# name -> the steps in front of its page, in order (raw captures). The portal's come from its demo
# (scripts/capture-portal.mjs), not a router: adding a device there would add one. -ru: README_ru's.
FLOWS = {
'portal': ['portal-add-1', 'portal-add-2', 'portal-add-3'],
'portal-ru': ['portal-add-1-ru', 'portal-add-2-ru', 'portal-add-3-ru'],
}
PAD_X, PAD_Y, INSET = 96, 80, 16 # canvas around the panel; panel around the page
FLOW_MARGIN = (56, 40, 56, 72) # around a step's sheet in its capture: left, top, right, bottom
@@ -45,7 +45,6 @@ CANDIDATES = [
]
TEMPLATE = """<!doctype html><html><head><meta charset="utf-8"><style>
@font-face{{font-family:Geist;src:url('file://{font}') format('woff2');font-weight:100 900}}
html,body{{margin:0;width:{w}px;height:{h}px;overflow:hidden}}
body{{position:relative;background:#080808}}
.panel{{position:absolute;left:{px}px;top:{py}px;width:{pw}px;height:{ph}px;
@@ -54,7 +53,7 @@ body{{position:relative;background:#080808}}
box-shadow:0 0 0 1px rgba(255,255,255,.04)}}
.sheet{{position:absolute;display:block;filter:drop-shadow(0 24px 48px rgba(0,0,0,.6))}}
.n{{position:absolute;width:34px;height:34px;border-radius:50%;display:grid;place-items:center;
font:600 16px Geist,sans-serif;color:#ededed;background:#232323;
font:600 16px system-ui,-apple-system,sans-serif;color:#ededed;background:#232323;
box-shadow:0 0 0 1px rgba(255,255,255,.12),0 6px 16px rgba(0,0,0,.5)}}
</style></head><body><div class="panel"></div><img class="page" src="file://{src}">{steps}</body></html>"""
@@ -111,7 +110,7 @@ def main():
html = os.path.join(tmp, f'{name}.html')
with open(html, 'w', encoding='utf-8') as f:
f.write(TEMPLATE.format(w=w, h=h, x=x, y=y, iw=iw, ih=ih, px=x - INSET, py=y - INSET, pw=iw + 2 * INSET,
ph=ih + 2 * INSET, src=src, font=FONT, steps=steps))
ph=ih + 2 * INSET, src=src, steps=steps))
out = os.path.join(OUT, f'{name}.png')
subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files',
f'--force-device-scale-factor={SCALE}', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'],
+9 -5
View File
@@ -41,9 +41,13 @@ def strip_comments(text):
return re.sub(r'//[^\n]*|/\*.*?\*/', '', text, flags=re.S)
def blank_comments(text):
"""Comments replaced by their newlines: line numbers stay, their text goes."""
return re.sub(r'//[^\n]*|/\*.*?\*/', lambda m: '\n' * m.group(0).count('\n'), text, flags=re.S)
def blank_comments_templates(text):
"""Comments and template literals replaced by their newlines, strings kept:
line numbers stay, and a `}` that starts a line of a template (nft rules)
ends no function. A template inside another one's `${…}` reads as code:
good enough for how Dawnline writes them."""
return re.sub(r"//[^\n]*|/\*.*?\*/|'(?:\\.|[^'\\\n])*'|\"(?:\\.|[^\"\\\n])*\"|`(?:\\.|[^`\\])*`",
lambda m: m.group(0) if m.group(0)[0] in '\'"' else '\n' * m.group(0).count('\n'), text, flags=re.S)
# A regex literal on one line: `/…/` with no slash inside, followed by flags or
@@ -66,7 +70,7 @@ for f in files:
problem(f"{f}:{line}: {name}() is used before its definition")
# In a module an exported function is an expression statement: its closing
# brace needs a semicolon ("Expecting ';'" breaks the whole module).
lines = blank_comments(open(f, encoding='utf-8').read()).split('\n')
lines = blank_comments_templates(open(f, encoding='utf-8').read()).split('\n')
inside = None
for n, text in enumerate(lines, 1):
if inside is None and re.match(r'^export function \w+\(', text):
@@ -146,7 +150,7 @@ if methods and os.path.exists(ACL):
# Layering (rules/backend.md): util, schema → core → store → domain modules →
# apply → entry points. A module importing one from a layer above it is
# reported, not failed, until the existing edges are untangled.
LAYER = {'util': 0, 'schema': 1, 'core': 2, 'store': 3, 'apply': 5}
LAYER = {'util': 0, 'i18n': 0, 'schema': 1, 'core': 2, 'store': 3, 'apply': 5}
LAYER_NAME = {0: 'util', 1: 'schema', 2: 'core', 3: 'store', 4: 'domain', 5: 'apply'}
notes = 0
for f in modules:
+36 -4
View File
@@ -129,16 +129,31 @@ const seen = (when, now) => {
}[k] ?? 0
);
};
/** A week of daily totals that adds up to about a quarter of the month, today last (nothing before it was first seen). */
/**
* A week of daily [rx, tx] that adds up to about a quarter of the month, today last (nothing before it was first
* seen), rx (from the device) about an eighth.
*/
const week = (gb, last, now) =>
[0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => (!gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7)));
[0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => {
const b = !gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7);
return [Math.round(b * 0.12), b - Math.round(b * 0.12)];
});
/**
* One second of the cast's traffic through a server (the k-th), [rx, tx] in bytes/s: a few devices streaming,
* their uploads small. The same for a second whichever call asks, so the live chart keeps its shape.
*/
const meterRate = (ts, k) => {
const wave = (a, b) => Math.sin(ts / a + k) * 0.45 + Math.sin(ts / b + 2 * k) * 0.25;
const noise = (((ts * 7919 + k * 104729) % 1000) / 1000 - 0.5) * 0.35;
return [Math.round(Math.max(0, 1.8e5 * (1 + wave(7, 17) + noise))), Math.round(Math.max(0, 1.6e6 * (1 + wave(9, 23) + noise)))];
};
let ipN = 10;
/** A documentation address (the capture swaps public addresses for these anyway). */
const ip = () => `203.0.113.${ipN++}`;
const where = (city) => `${city} · ${CITIES[city][4]}`;
/** What the last status made of the router's ids, for the calls that come after it (events, usage). */
const demo = { events: [], people: new Map(), days: [], now: 0 };
/** What the last status made of the router's ids, for the calls that come after it (events, usage, the meter). */
const demo = { events: [], people: new Map(), days: [], now: 0, servers: [] };
/**
* Daily traffic over `days` (oldest first) for `gb` this month: busier some days of the week, today
@@ -255,6 +270,12 @@ function demoStatus(st, first) {
total: [Math.round(gb * 0.3 * GB), Math.round(gb * 2.2 * GB)],
spark: week(gb, hs, now),
hostname: hs ? `${slug(name)}.${slug(c.name.split(' ')[0])}.lan` : '',
// As set up: nothing failing, its own link values the server's, its data flowing while online.
link: null,
setup: online ? { state: 'flowing', since: hs } : null,
lan_bypass: false,
mtu: 0,
keepalive: null,
};
});
for (const [name, ago, by] of c.added ?? []) {
@@ -313,6 +334,7 @@ function demoStatus(st, first) {
demo.events = events;
points.sort((a, b) => b.ts - a.ts);
demo.now = now;
demo.servers = (st.servers ?? []).map((x) => x.id);
demo.days = (st.series ?? []).map((x) => x.day);
if (!demo.days.length) for (let k = 29; k >= 0; k--) demo.days.push(date(now - k * DAY));
const all = CAST.reduce((s, c) => s + c.devices.reduce((t, d) => t + d[3], 0), 0);
@@ -384,6 +406,16 @@ export function demoRpc(request, response, first) {
},
],
};
// Speed now, live: the last two minutes of the cast's traffic, not the router's.
if (method === 'meter' && Array.isArray(data.points)) {
const ids = demo.servers.length ? demo.servers : [...new Set(data.points.flatMap((p) => Object.keys(p.servers ?? {})))];
const keep = data.keep > 1 ? data.keep : 120;
const since = +args?.since || 0;
const points = [];
for (let ts = data.now - keep + 1; ts <= data.now; ts++)
if (ts > since) points.push({ ts, servers: Object.fromEntries(ids.map((id, k) => [id, meterRate(ts, k)])) });
return { ...r, result: [r.result[0], { ...data, ts: data.now, points }] };
}
if (method === 'events' && Array.isArray(data.events)) {
const mine = demo.events.filter((e) => !args?.person || e.person === args.person);
return {
+67
View File
@@ -0,0 +1,67 @@
// dawnline.access: the Check access walk for a device that keeps its own
// local network out of the tunnel (lan_bypass), and the way its internet
// leaves, on a model and a network snapshot of the test's own (nothing read
// from the container).
import * as access from 'dawnline.access';
const KEY_TV = 'a8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=', KEY_PHONE = 'b8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=';
/** Bob (Internet only) on a server that sends everyone direct: a TV with lan_bypass and a phone without. */
function model() {
return {
settings: { portal_enabled: false },
servers: {
home: { id: 'home', name: 'Home', ifname: 'awghome', subnet: '10.9.0.0/29', private_key: 'k', enabled: true, lan_like: false,
auto_wan: false, wan_device: 'eth1', auto_lan: false, lan_devices: [ 'br-lan' ], mesh: 'all', device_mesh: true, dns: [] },
},
people: { bob: { id: 'bob', name: 'Bob', server: 'home', access: 'internet', services: [], devices: [ 'tv', 'phone' ] } },
devices: {
tv: { id: 'tv', person: 'bob', name: 'TV', address: '10.9.0.2', public_key: KEY_TV, lan_bypass: true },
phone: { id: 'phone', person: 'bob', name: 'Phone', address: '10.9.0.3', public_key: KEY_PHONE, lan_bypass: false },
},
services: {},
circles: {},
};
}
const CTX = {
states: { bob: 'active' },
dmp: { peers: {}, windows: {} },
snap: {
devices: {
'br-lan': { nets: [ '192.168.1.0/24' ], zone: 'lan', addrs: [ '192.168.1.1/24' ] },
eth1: { nets: [ '203.0.113.0/24' ], zone: 'wan', addrs: [ '203.0.113.7/24' ] },
awghome: { nets: [ '10.9.0.0/29' ], addrs: [ '10.9.0.1/29' ] },
},
lan: 'br-lan',
wan: 'eth1',
},
};
function last(r) {
return r.steps[length(r.steps) - 1];
}
test('check: a device with its local network outside the tunnel', () => {
let m = model();
let r = access.check(m, 'tv', '192.168.1.20', CTX);
eq([ r.ok, last(r).ok, last(r).title ], [ false, false, "Its configuration doesn't send it to the router" ],
'a home address: on its own network, not blocked in the tunnel');
ok(index(last(r).detail, "the device's own network handles it") >= 0, 'says where it goes');
r = access.check(m, 'tv', '192.168.1.1:80', CTX);
eq(last(r).title, "Its configuration doesn't send it to the router", 'the router\'s LAN address is on its own network too');
r = access.check(m, 'tv', '10.9.0.1:53', CTX);
eq([ r.ok, r.steps[1].title ], [ true, '10.9.0.1 is this router: DNS is open to everyone' ], 'its DNS stays in the tunnel');
r = access.check(m, 'tv', '8.8.8.8', CTX);
eq([ r.ok, last(r).title, last(r).detail ], [ true, '8.8.8.8 is on the internet', 'It leaves through eth1.' ], 'the internet through the tunnel');
r = access.check(m, 'phone', '192.168.1.20', CTX);
eq([ r.ok, last(r).title ], [ false, '192.168.1.20 is at home (br-lan)' ], 'without it: into the tunnel, and blocked there');
});
test('check: the way out is the server\'s', () => {
let m = model();
eq(last(access.check(m, 'phone', '8.8.8.8', CTX)).detail, 'It leaves through eth1.', 'direct');
m.servers.home.lan_like = true;
eq(last(access.check(m, 'phone', '8.8.8.8', CTX)).detail, 'It leaves like a home device would.', 'like a home device');
});
+478 -27
View File
@@ -1,8 +1,18 @@
// dawnline.awg: disguise presets against their own validation, the parser
// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP), and Reconnect.
// dawnline.awg: disguise presets against their own validation, the values
// AmneziaWG refuses (obf_unsafe, one case per rule), the parser of `awg show
// <ifname> dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1 and how
// each tunnel's read went (the stand-in awg in fixtures/bin prints the
// fixture put at AWG_DUMP), the devices a tunnel should hold, Reconnect, a
// device's configuration from the fixture model, what the server's interface
// and the read-only status get of it.
import { readfile, writefile, unlink } from 'fs';
import { cursor } from 'uci';
import { valid_key, cidr_any } from 'dawnline.util';
import * as awg from 'dawnline.awg';
import * as core from 'dawnline.core';
import * as backup from 'dawnline.backup';
import * as rpc_status from 'dawnline.rpc.status';
import * as nft from 'dawnline.nft';
const AWG_DUMP = '/tmp/dawnline-tests/awg-dump';
let fixtures = sourcepath(0, true) + '/fixtures';
@@ -32,7 +42,8 @@ test('obf_preset balanced', () => {
test('obf_preset max', () => {
let o = awg.obf_preset('max');
eq(o.header_protection_key, 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=', 'key from awg genkey');
ok(valid_key(o.header_protection_key), 'a header protection key');
ok(o.header_protection_key != awg.obf_preset('max').header_protection_key, 'made for each server, without awg genkey');
ok(+o.jc >= 4 && +o.jc <= 6, 'jc');
ok(substr(o.i1, 0, 3) == '<r ', 'DNS-like first packet');
eq([ o.random_trailers, o.disable_cookies, o.content_padding_addition ], [ 'on', 'on', '10-100' ], '3.1 options');
@@ -44,55 +55,279 @@ test('obf_preset max', () => {
shapes[awg.obf_preset('max').i1] = true;
ok(length(keys(shapes)) > 1, 'signature packets differ between servers');
// The preset passes the server's own validation (jmin/jmax may be small: 0.5.2).
eq(awg.obf_errors(o), [], 'max is valid');
for (let i = 0; i < 25; i++)
eq(awg.obf_errors(awg.obf_preset('max')), [], 'max is valid');
});
test('obf_errors', () => {
test('obf_errors: Dawnline\'s own bounds on top of obf_unsafe', () => {
eq(awg.obf_errors({}), [], 'nothing set');
eq(awg.obf_errors({ jc: '11' }), [ 'jc=11 (0-10)' ], 'jc range');
eq(awg.obf_errors(null), [], 'no values');
eq(awg.obf_errors({ jc: '11' }), [ 'Jc must be from 0 to 10.' ], 'jc range');
eq(awg.obf_errors({ jmin: '0', jmax: '0' }), [], 'zero junk sizes are allowed');
eq(awg.obf_errors({ jmin: '2000' }), [ 'jmin=2000 (0-1024)' ], 'jmin range');
eq(awg.obf_errors({ jmin: '200', jmax: '100' }), [ 'jmin > jmax' ], 'order');
eq(awg.obf_errors({ s1: '5', s2: '61' }), [ 's1 + 56 = s2' ], 'the handshake size clash');
eq(awg.obf_errors({ s4: '33' }), [ 's4=33 (0-32)' ], 's4 range');
eq(awg.obf_errors({ jc: 'x' }), [ 'jc=x (0-10)' ], 'not a number');
eq(awg.obf_errors({ h1: '7', h2: '7' }), [ 'h1-h4 must be distinct' ], 'duplicate headers');
eq(awg.obf_errors({ h1: '7-9', h2: 'abc' }), [ 'h2 must be a number or range' ], 'header ranges');
eq(awg.obf_errors({ jmin: '2000', jmax: '3000' }), [ 'Jmin must be from 0 to 1024.', 'Jmax must be from 0 to 1024.' ], 'junk sizes');
eq(awg.obf_errors({ s1: '5', s2: '61' }), [ 'S2 must not be S1 + 56: the handshake initiation and response would have the same size.' ],
'the handshake size clash');
eq(awg.obf_errors({ s4: '33' }), [ 'S4 must be from 0 to 32.' ], 's4 range');
// What AmneziaWG refuses comes first, said once.
eq(awg.obf_errors({ jc: 'x' }), [ 'Jc must be a whole number from 0 to 65535.' ], 'not a number');
eq(awg.obf_errors({ jmin: '200', jmax: '100' }), [ 'Jmin must not be larger than Jmax.' ], 'order');
eq(awg.obf_errors({ h1: '7', h2: '7' }), [ 'H1 and H2 overlap: each packet type needs values of its own.' ], 'duplicate headers');
eq(awg.obf_neutral({ jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }), true, 'off is neutral');
eq(awg.obf_neutral({ jc: '4', jmin: '64', jmax: '128' }), false, 'junk is not neutral');
});
// One case per rule of obf_unsafe: what an import, a restore or a hand edit must never hand to the kernel.
const HPK = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
const MAX = { s1: '12', s2: '12', s3: '12', s4: '12', header_protection_key: HPK };
test('obf_unsafe: what the presets and older servers hold passes', () => {
eq(awg.obf_unsafe(null), [], 'no values');
eq(awg.obf_unsafe(awg.obf_preset('off')), [], 'off');
for (let i = 0; i < 25; i++) {
eq(awg.obf_unsafe(awg.obf_preset('balanced')), [], 'balanced');
eq(awg.obf_unsafe(awg.obf_preset('max')), [], 'max');
}
// Values from before 0.8 and hand-tuned ones the kernel takes: none of Dawnline's own bounds here.
let old = { jc: '12', jmin: '50', jmax: '1400', s1: '100', s2: '156', h1: '1234567', h2: '2345678', h3: '3456789', h4: '4567890' };
eq(awg.obf_unsafe(old), [], 'older and hand-tuned values');
ok(length(awg.obf_errors(old)) > 0, 'which a new server would not get');
});
test('obf_unsafe: 16-bit numbers', () => {
eq(awg.obf_unsafe({ jc: '65535', s4: '0' }), [], 'the ends');
eq(awg.obf_unsafe({ jc: '65536' }), [ 'Jc must be a whole number from 0 to 65535.' ], 'too large');
eq(awg.obf_unsafe({ s3: '-1' }), [ 'S3 must be a whole number from 0 to 65535.' ], 'negative');
eq(awg.obf_unsafe({ jmax: '1e3' }), [ 'Jmax must be a whole number from 0 to 65535.' ], 'not digits');
});
test('obf_unsafe: Jmin not above Jmax', () => {
eq(awg.obf_unsafe({ jmin: '50', jmax: '50' }), [], 'equal');
eq(awg.obf_unsafe({ jmin: '51', jmax: '50' }), [ 'Jmin must not be larger than Jmax.' ], 'the kernel would write past its junk buffer');
eq(awg.obf_unsafe({ jmin: '51' }), [], 'Jmax not given');
});
test('obf_unsafe: header values are numbers or ranges', () => {
eq(awg.obf_unsafe({ h1: '100-200', h2: '300', h3: '4294967295', h4: '0' }), [], 'numbers and ranges');
eq(awg.obf_unsafe({ h1: '200-100' }), [ 'H1 must be a number or a range like 100-200, up to 4294967295.' ], 'reversed');
eq(awg.obf_unsafe({ h2: '4294967296' }), [ 'H2 must be a number or a range like 100-200, up to 4294967295.' ], 'past 32 bits');
eq(awg.obf_unsafe({ h3: '5-6-7' }), [ 'H3 must be a number or a range like 100-200, up to 4294967295.' ], 'two dashes');
eq(awg.obf_unsafe({ h4: 'abc' }), [ 'H4 must be a number or a range like 100-200, up to 4294967295.' ], 'not a number');
});
test('obf_unsafe: header values do not overlap', () => {
eq(awg.obf_unsafe({ h1: '10-20', h2: '20-30', h3: '40', h4: '50' }), [ 'H1 and H2 overlap: each packet type needs values of its own.' ], 'a shared end');
eq(awg.obf_unsafe({ h1: '10-20', h2: '30', h3: '15', h4: '50' }), [ 'H1 and H3 overlap: each packet type needs values of its own.' ], 'one inside a range');
// One not given keeps WireGuard's type: 1-4.
eq(awg.obf_unsafe({ h1: '1-10' }), [ 'H1 and H2 overlap: each packet type needs values of its own.', 'H1 and H3 overlap: each packet type needs values of its own.',
'H1 and H4 overlap: each packet type needs values of its own.' ], 'over the default types');
eq(awg.obf_unsafe({ h1: '5-10' }), [], 'clear of them');
});
test('obf_unsafe: header protection needs a key and 12-byte padding', () => {
eq(awg.obf_unsafe(MAX), [], 'the 3.1 values');
eq(awg.obf_unsafe({ ...MAX, header_protection_key: 'abc' }), [ 'The header protection key is not a key.' ], 'not a key');
eq(awg.obf_unsafe({ ...MAX, s3: '11' }), [ 'S3 must be at least 12 with header protection.' ], 'too little padding');
eq(awg.obf_unsafe({ ...MAX, s4: null }), [ 'S4 must be at least 12 with header protection.' ], 'no padding');
eq(awg.obf_unsafe({ s1: '0', s2: '0' }), [], 'none needed without the key');
});
test('obf_unsafe: 3.1 timers and counts', () => {
eq(awg.obf_unsafe({ rekey_after_time: '100-120', rekey_timeout: '3', keepalive_timeout: '0', max_handshake_attempts: '0-0' }), [],
'numbers, ranges and 0 (the default)');
eq(awg.obf_unsafe({ rekey_timeout: '0-7' }), [ 'RekeyTimeout must be a number or a range like 5-15, from 1 to 65535.' ], 'a 0 in a range');
eq(awg.obf_unsafe({ keepalive_timeout: '15-5' }), [ 'KeepaliveTimeout must be a number or a range like 5-15, from 1 to 65535.' ], 'reversed');
eq(awg.obf_unsafe({ max_handshake_attempts: '70000' }), [ 'MaxHandshakeAttempts must be a number or a range like 5-15, from 1 to 65535.' ], 'past 16 bits');
eq(awg.obf_unsafe({ content_padding_addition: '0-100' }), [], 'padding may start at 0');
eq(awg.obf_unsafe({ content_padding_addition: '10-x' }), [ 'ContentPaddingAddition must be a number or a range like 10-100, up to 65535.' ], 'padding');
});
test('obf_unsafe: RejectAfterTime up to 180 seconds', () => {
eq(awg.obf_unsafe({ reject_after_time: '150-180' }), [], 'the preset');
eq(awg.obf_unsafe({ reject_after_time: '150-181' }), [ 'RejectAfterTime must be at most 180 seconds.' ], 'the kernel drops keys after 180 seconds');
});
test('obf_unsafe: switches', () => {
eq(awg.obf_unsafe({ random_trailers: 'on', disable_cookies: '0' }), [], 'on, off, 1, 0');
eq(awg.obf_unsafe({ random_trailers: 'yes' }), [ 'RandomTrailers must be on or off.' ], 'what the .conf parser refuses');
eq(awg.obf_unsafe({ disable_cookies: 'true' }), [ 'DisableCookies must be on or off.' ], 'the same for cookies');
});
test('obf_unsafe: signature packet tags', () => {
let bad = (name, tag) => `${name}: <${tag}> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>.`;
eq(awg.obf_unsafe({ i1: '<b 0xC0ffee><r 1><rc 1000><rd 12><t>', i2: 'text between tags <r 2> is skipped' }), [], 'every tag both parsers know');
eq(awg.obf_unsafe({ i1: '<b 0xabc>' }), [ bad('I1', 'b 0xabc') ], 'an odd number of hex digits');
eq(awg.obf_unsafe({ i1: '<b 0x>' }), [ bad('I1', 'b 0x') ], 'no bytes');
eq(awg.obf_unsafe({ i1: '<b ff00>' }), [ bad('I1', 'b ff00') ], 'no 0x (the kernel needs it)');
eq(awg.obf_unsafe({ i1: '<b 0xzz>' }), [ bad('I1', 'b 0xzz') ], 'not hex');
eq(awg.obf_unsafe({ i2: '<r -5>' }), [ bad('I2', 'r -5') ], 'a negative length writes past the packet');
eq(awg.obf_unsafe({ i2: '<rc 0>' }), [ bad('I2', 'rc 0') ], 'no length');
eq(awg.obf_unsafe({ i2: '<rd 1001>' }), [ bad('I2', 'rd 1001') ], 'too long');
eq(awg.obf_unsafe({ i3: '<r 5>' }), [ bad('I3', 'r 5') ], 'two spaces');
eq(awg.obf_unsafe({ i3: '<t >' }), [ bad('I3', 't ') ], 'a space after t');
eq(awg.obf_unsafe({ i4: '<c>' }), [ bad('I4', 'c') ], 'the kernel\'s counter, which amneziawg-go refuses');
for (let t in [ 'd', 'ds', 'dz' ])
eq(awg.obf_unsafe({ i4: `<${t}>` }), [ bad('I4', t) ], `amneziawg-go's <${t}>, which the kernel refuses`);
eq(awg.obf_unsafe({ i5: '<>' }), [ bad('I5', '') ], 'an empty tag');
eq(awg.obf_unsafe({ i5: '<r <5>' }), [ bad('I5', 'r <5') ], 'a tag inside a tag');
eq(awg.obf_unsafe({ i5: '<b 0x0102030405060708090a0b0c0d0e0f>' }), [], 'long tags are fine');
eq(awg.obf_unsafe({ i5: '<x 0x0102030405060708090a0b0c0d0e0f>' }), [ bad('I5', 'x 0x0102030405060708090a…') ], 'shown cut short');
eq(awg.obf_unsafe({ i1: '<r 5' }), [ 'I1 has a tag that is not closed with >.' ], 'not closed');
eq(awg.obf_unsafe({ i1: '<r 5><b 0x00> # note' }), [ 'I1 may not contain # or a line break.' ], 'a comment in a .conf');
eq(awg.obf_unsafe({ i1: '<r 5>\n<t>' }), [ 'I1 may not contain # or a line break.' ], 'a line break');
});
test('obf_unsafe: I1-I5 fit one configuration', () => {
// A tag of 100 characters.
let tag = '<b 0x';
for (let n = 0; n < 47; n++)
tag += 'ab';
tag += '>';
let many = (n) => {
let out = '';
for (let k = 0; k < n; k++)
out += tag;
return out;
};
let four = many(4);
eq(awg.obf_unsafe({ i1: four, i2: four, i3: four, i4: four, i5: four }), [], '2000 characters');
eq(awg.obf_unsafe({ i1: four, i2: four, i3: four, i4: four, i5: many(5) }), [ 'I1-I5 together must be at most 2000 characters, not 2100.' ], 'over 2000');
});
test('obf_unsafe: an import or restore with such values is refused', () => {
let dir = '/tmp/dawnline-tests/import';
let errs = (text) => {
system(`rm -rf ${dir}; mkdir -p ${dir}/.delta`);
writefile(`${dir}/dawnline`, text);
let c = cursor(dir, `${dir}/.delta`);
c.load('dawnline');
let out = backup.config_errors(c);
system(`rm -rf ${dir}`);
return out;
};
let fixture = readfile('/etc/config/dawnline');
let bad = errs(replace(fixture, "option jmax '128'", "option jmax '32'"));
ok(index(bad, 'Server Main: Jmin must not be larger than Jmax.') >= 0, `refused: ${join(' ', bad)}`);
eq(filter(errs(fixture), (e) => index(e, 'Jmin') >= 0), [], 'the fixture as it is');
});
// The stand-in's call log and failures (fixtures/bin/awg).
const AWG_CALLS = '/tmp/dawnline-tests/awg-calls';
const AWG_FAIL = '/tmp/dawnline-tests/awg-fail-';
const SERVER_KEY = 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=';
const PEER_ON = 'HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=', PEER_NEW = 'TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0=';
// A fixture's lines as another interface's (`show all` prints the ifname first).
function lines_as(name, ifname) {
let out = '';
for (let l in split(readfile(`${fixtures}/awg-dump-${name}.txt`), '\n'))
if (l != '')
out += `${ifname}${substr(l, length('awgmain'))}\n`;
return out;
}
// lo is in every container's /sys/class/net (index 1), and is no AmneziaWG
// interface: the stand-in prints the fixture's lines for it, as for a tunnel.
function dump_of(name) {
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-${name}.txt`));
return awg.dump();
writefile(AWG_DUMP, lines_as(name, 'lo'));
return awg.dump([ 'lo' ]);
}
test('dump: AmneziaWG 1.0 (14 interface fields)', () => {
let d = dump_of('1.0');
eq(d.ok, true, 'ok');
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
eq(d.peers['HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw='],
{ ifname: 'awgmain', endpoint: '203.0.113.7:41821', handshake: 1760000000, rx: 123456, tx: 654321 }, 'peer with a session');
eq(d.peers['TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0='],
{ ifname: 'awgmain', endpoint: '', handshake: 0, rx: 0, tx: 0 }, 'peer that never connected');
eq(d.reads, { lo: 'read' }, 'read');
eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface; its index is the epoch of its counters');
eq(d.peers[PEER_ON], { ifname: 'lo', endpoint: '203.0.113.7:41821', handshake: 1760000000, rx: 123456, tx: 654321 },
'peer with a session, with the ifname the lines leave out');
eq(d.peers[PEER_NEW], { ifname: 'lo', endpoint: '', handshake: 0, rx: 0, tx: 0 }, 'peer that never connected');
});
test('dump: AmneziaWG 2.0 (33 interface fields)', () => {
let d = dump_of('2.0');
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
eq(keys(d.peers), [ 'HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=' ], 'one peer');
eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface');
eq(keys(d.peers), [ PEER_ON ], 'one peer');
});
test('dump: AmneziaWG 3.1 (33 interface fields, protection on)', () => {
let d = dump_of('3.1');
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface');
eq(length(d.peers), 2, 'two peers');
});
test('dump: the tool fails', () => {
// awgmain is not in the container's /sys/class/net, as a tunnel netifd could not bring up.
test('dump: a tunnel that is not there is down, without a process', () => {
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-1.0.txt`));
unlink(AWG_CALLS);
eq(awg.dump([ 'awgmain' ]), { ok: true, reads: { awgmain: 'down' }, ifaces: {}, peers: {} }, 'its counters are gone');
eq(readfile(AWG_CALLS), null, 'awg is not asked about a link the kernel does not have');
eq(awg.dump([]), { ok: true, reads: {}, ifaces: {}, peers: {} }, 'no tunnel runs');
});
test('dump: each tunnel on its own', () => {
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-1.0.txt`) + lines_as('2.0', 'lo'));
let d = awg.dump([ 'awgmain', 'lo' ]);
eq([ d.ok, d.reads ], [ true, { awgmain: 'down', lo: 'read' } ], 'one down, one read');
eq(keys(d.ifaces), [ 'lo' ], 'only what was read');
eq(filter(values(d.peers), (p) => p.ifname != 'lo'), [], 'no peers of the one that is down');
});
// The tool says "Operation not supported" for lo on a real system.
test('dump: a tunnel that exists but cannot be read', () => {
writefile(AWG_DUMP, lines_as('2.0', 'lo'));
writefile(`${AWG_FAIL}lo`, 'Unable to access interface: Operation not supported\n');
let d = awg.dump([ 'awgmain', 'lo' ]);
unlink(`${AWG_FAIL}lo`);
eq(d.ok, false, 'not every tunnel was read');
eq(d.reads, { awgmain: 'down', lo: 'error' }, 'each on its own');
eq([ d.ifaces, d.peers ], [ {}, {} ], 'nothing of the failed one');
});
// The agent's watcher reads every second: with one server, one process.
test('dump: only the tunnels asked for, one process each', () => {
writefile(AWG_DUMP, lines_as('1.0', 'lo') + lines_as('2.0', 'wgclient'));
unlink(AWG_CALLS);
let d = awg.dump([ 'lo' ]);
// The tests after these find no tunnel, as on a router without AmneziaWG running.
unlink(AWG_DUMP);
let d = awg.dump();
eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known');
eq(readfile(AWG_CALLS), 'show lo dump\n', 'one call, never `all`');
eq(keys(d.ifaces), [ 'lo' ], 'the other tunnel is not read');
eq(d.peers[PEER_ON].ifname, 'lo', 'its peers stand in for none of ours');
});
test('tunnel_devices: what sync_peers loads', () => {
let m = {
servers: { s: { public_key: SERVER_KEY } },
people: { a: { id: 'a', server: 's' }, b: { id: 'b', server: 's' }, c: { id: 'c', server: 'other' } },
devices: {
on: { person: 'a', public_key: PEER_ON, address: '10.9.0.2' },
own: { person: 'a', public_key: SERVER_KEY, address: '10.9.0.8' },
off: { person: 'a', public_key: PEER_NEW, address: '10.9.0.3', disabled: true },
paused: { person: 'b', public_key: SERVER_KEY, address: '10.9.0.4' },
elsewhere: { person: 'c', public_key: PEER_NEW, address: '10.9.0.5' },
badkey: { person: 'a', public_key: 'not a key', address: '10.9.0.6' },
badaddr: { person: 'a', public_key: PEER_NEW, address: '' },
nobody: { person: 'gone', public_key: PEER_NEW, address: '10.9.0.7' },
},
};
let st = { a: 'quota', b: 'paused', c: 'active' };
eq(map(awg.tunnel_devices(m, 's', st), (d) => d.address), [ '10.9.0.2' ],
'over the limit stays; off, paused, other servers, lines syncconf would refuse and the server\'s own key (ignored by the kernel) do not');
eq(map(awg.tunnel_devices(m, 'other', st), (d) => d.address), [ '10.9.0.5' ], 'the other server');
eq(awg.tunnel_devices(m, 'none', st), [], 'none');
});
test('peer_diff: by key, per tunnel', () => {
let dmp = { peers: {} };
dmp.peers[PEER_ON] = { ifname: 'awgmain' };
dmp.peers[SERVER_KEY] = { ifname: 'awgmain' };
dmp.peers[PEER_NEW] = { ifname: 'awgother' };
let devs = (...ks) => map(ks, (k) => ({ public_key: k }));
eq(awg.peer_diff(devs(PEER_ON, SERVER_KEY), dmp, 'awgmain'), { loaded: 2, missing: 0, extra: 0 }, 'the same');
eq(awg.peer_diff(devs(PEER_ON, PEER_NEW), dmp, 'awgmain'), { loaded: 2, missing: 1, extra: 1 },
'a stale peer standing in for a missing one');
eq(awg.peer_diff(devs(PEER_ON), dmp, 'awgmain'), { loaded: 2, missing: 0, extra: 1 }, 'one too many');
eq(awg.peer_diff(devs(PEER_NEW), dmp, 'awgdown'), { loaded: 0, missing: 1, extra: 0 }, 'a tunnel with no peers read');
eq(awg.peer_diff([], { peers: {} }, 'awgmain'), { loaded: 0, missing: 0, extra: 0 }, 'nothing either way');
});
test('handshake_since: Reconnect hides older handshakes', () => {
@@ -103,3 +338,219 @@ test('handshake_since: Reconnect hides older handshakes', () => {
eq(awg.handshake_since(1600, 1500), 1600, 'connected after');
eq(awg.handshake_since(0, 1500), 0, 'never connected');
});
test('blocked reasons', () => {
let srv = (b) => ({ name: 'Home', blocked: b });
eq(awg.blocked_text(srv(null)), null, 'not kept down');
eq(awg.blocked_text(srv({ code: 'ifname', ifname: 'bad name' })), 'Home has an invalid interface name "bad name".', 'interface name');
eq(awg.blocked_text(srv({ code: 'taken', ifname: 'wg0' })), "Home can't use the network interface wg0: it exists and isn't Dawnline's.", 'foreign interface');
eq(awg.blocked_text(srv({ code: 'disguise', need: '3.1', installed: '2.0' })), 'Home is kept down: its disguise needs AmneziaWG 3.1 (installed: 2.0).', 'disguise');
eq(awg.blocked_text(srv({ code: 'disguise', need: '3.1' })), 'Home is kept down: its disguise needs AmneziaWG 3.1 (installed: none).', 'disguise, none installed');
// Files of older versions hold the English fragment after the name.
eq(awg.blocked_text(srv('has an invalid interface name "x"')), 'Home has an invalid interface name "x".', 'old fragment');
eq(awg.blocked_note({ code: 'ifname', ifname: 'x' }), 'has an invalid interface name "x"', 'the log keeps the fragment');
// Values AmneziaWG refuses: which ones, from the server's own when read.
let bad = { name: 'Home', obf: { jmin: '60', jmax: '50' }, blocked: { code: 'disguise_invalid' } };
eq(awg.blocked_text(bad), 'Home is kept down: its disguise has values AmneziaWG cannot take. Jmin must not be larger than Jmax.', 'invalid values');
eq(awg.blocked_text({ ...bad, obf: {} }), 'Home is kept down: its disguise has values AmneziaWG cannot take.', 'fixed since');
eq(awg.blocked_note(bad.blocked), 'is kept down: its disguise has values AmneziaWG cannot take', 'the log');
eq(awg.blocked_fix(bad.blocked), 'Choose a disguise on the Server page: it replaces the values set by hand.', 'what to do about it');
eq(awg.blocked_fix({ code: 'taken', ifname: 'wg0' }), 'Choose another interface name in the server settings.', 'what to do about a name');
});
test('netifd_options: the server keeps its defence against handshake floods', () => {
let m = core.load();
let srv = m.servers.main;
srv.obf = awg.obf_preset('max');
let o = awg.netifd_options(srv);
ok('awg_disable_cookies' in o, 'named, so netifd.sync takes it off an interface that had it');
eq(o.awg_disable_cookies, null, 'no DisableCookies on the server');
eq([ o.awg_header_protection_key, o.awg_jc, o.awg_i1, o.awg_random_trailers ], [ srv.obf.header_protection_key, srv.obf.jc, srv.obf.i1, 'on' ],
'the rest of the disguise stays');
ok(index(split(awg.client_config(m, m.devices.alice_phone).conf, '\n'), 'DisableCookies = on') >= 0, 'devices keep it');
});
test('client_config: one keep-alive for the .conf and the AmneziaVPN key', () => {
let m = core.load();
let srv = m.servers.main, dev = m.devices.alice_phone;
let ka = () => {
let c = awg.client_config(m, dev);
return [ match(c.conf, /\nPersistentKeepalive = ([^\n]*)\n/)?.[1], c.amnezia.persistent_keep_alive ];
};
eq(ka(), [ '25', '25' ], 'a number without header protection');
srv.obf = awg.obf_preset('max');
eq(ka(), [ '25-35', '25-35' ], 'jittered with 3.1');
srv.keepalive = 0;
eq(ka(), [ null, '0' ], 'off');
});
test('status: the header protection key stays out of what read-only users get', () => {
eq(awg.obf_public({ jc: '4', header_protection_key: HPK }), { jc: '4' }, 'obf_public');
eq(awg.obf_public(null), {}, 'no values');
// Server main on Maximum, as a uci change not committed (the fixture file stays as it is).
let c = cursor();
c.load('dawnline');
let o = awg.obf_preset('max');
for (let k, v in o)
c.set('dawnline', 'main', k, v);
c.save('dawnline');
let out = rpc_status.methods.status.call({ args: { days: 30 } });
c.revert('dawnline');
eq(out.error, null, 'status answers');
let srv = filter(out.servers ?? [], (x) => x.id == 'main')[0];
eq([ srv?.hpk, srv?.obf?.header_protection_key, srv?.obf?.disable_cookies ], [ true, null, 'on' ], 'whether there is a key, not which');
let text = sprintf('%J', out);
ok(index(text, o.header_protection_key) < 0, 'the key is nowhere in the answer');
let found = uniq(map(match(text, /[A-Za-z0-9+\/]{43}=/g) ?? [], (x) => x[0]));
eq(found, [ srv.public_key ], 'no key but the server\'s public one');
});
test('client_config: an IPv6 endpoint in brackets, without a regex', () => {
let m = core.load();
let srv = m.servers.main, dev = m.devices.alice_phone;
let ep = (h) => {
srv.endpoint = h;
return match(awg.client_config(m, dev).conf, /\nEndpoint = ([^\n]*)\n/)?.[1];
};
eq(ep('vpn.example.com'), 'vpn.example.com:51820', 'a name');
eq(ep('203.0.113.7'), '203.0.113.7:51820', 'IPv4');
eq(ep('2001:db8::1'), '[2001:db8::1]:51820', 'IPv6');
eq(ep('[2001:db8::1]'), '[2001:db8::1]:51820', 'IPv6 in brackets already');
eq(ep(''), 'vpn.example.com:51820', 'the portal name when the server has none');
// The regexes it stands for, on hosts changed at each character.
for (let h in [ '2001:db8::1', '[::1]', 'a.b' ])
for (let i = 0; i <= length(h); i++)
for (let c in [ ':', '[', ']', 'a', '' ]) {
let s = `${substr(h, 0, i)}${c}${substr(h, i + 1)}`;
let want = match(s, /:/) && !match(s, /^\[/) ? `[${s}]` : s;
eq(ep(s), `${want || 'vpn.example.com'}:51820`, s);
}
});
test('config_fingerprint leaves out the private key and the junk', () => {
let m = core.load();
let dev = m.devices.alice_phone;
let f = awg.config_fingerprint(m, dev);
ok(match(f, /^[0-9a-f]{8}$/), 'eight hex digits');
dev.private_key = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
eq(awg.config_fingerprint(m, dev), f, 'a private key');
m.servers.main.obf.jc = '7';
eq(awg.config_fingerprint(m, dev), f, 'another junk count');
m.servers.main.port = 51821;
ok(awg.config_fingerprint(m, dev) != f, 'another port');
eq(awg.config_fingerprint(m, null), null, 'no device');
});
/* ---------- a device's local network, MTU and keep-alive ---------- */
// Exactly the complement: aligned prefixes, none overlapping another or a
// private range, and all of them together the whole address space.
test('BYPASS4: every IPv4 address outside the private ranges, once', () => {
let nets = [ ...map(awg.BYPASS4, (n) => [ n, false ]), ...map(nft.PRIVATE4, (n) => [ n, true ]) ];
let total = 0;
for (let i = 0; i < length(nets); i++) {
let a = cidr_any(nets[i][0]);
ok(a && a.ip == a.net, `${nets[i][0]}: a prefix`);
total += a.size;
for (let j = i + 1; j < length(nets); j++) {
let b = cidr_any(nets[j][0]);
ok(a.net + a.size <= b.net || b.net + b.size <= a.net, `${nets[i][0]} and ${nets[j][0]} apart`);
}
}
eq(total, 4294967296, 'together: every address');
});
test('BYPASS6: every IPv6 address outside fc00::/7, fe80::/10 and ff00::/8, once', () => {
// Each of them is /16 or wider: the first 16 bits decide.
let span = (n) => {
let p = split(n, '/'), len = +p[1];
ok(len >= 1 && len <= 16 && substr(p[0], -2) == '::', `${n}: a prefix of the first 16 bits`);
let g = substr(p[0], 0, length(p[0]) - 2);
let start = g == '' ? 0 : hex(g), size = 1 << (16 - len);
ok(start % size == 0, `${n}: aligned`);
return [ start, size ];
};
let nets = map([ ...awg.BYPASS6, 'fc00::/7', 'fe80::/10', 'ff00::/8' ], span);
let total = 0;
for (let i = 0; i < length(nets); i++) {
total += nets[i][1];
for (let j = i + 1; j < length(nets); j++)
ok(nets[i][0] + nets[i][1] <= nets[j][0] || nets[j][0] + nets[j][1] <= nets[i][0], `${i} and ${j} apart`);
}
eq(total, 65536, 'together: every address');
});
test('allowed_ips: the local network outside the tunnel', () => {
let m = core.load();
let srv = m.servers.main;
// No home network from the container's own interfaces.
srv.auto_lan = false;
srv.lan_devices = [];
let alice = m.people.alice, bob = m.people.bob;
eq(awg.allowed_ips(m, srv, bob), [ '0.0.0.0/0', '::/0' ], 'no device: everything');
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: false }), [ '0.0.0.0/0', '::/0' ], 'as before');
let dns = (list) => [ ...slice(list, 0, 2), '10.9.0.1/32', ...slice(list, 2) ];
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: true }), [ ...dns(awg.BYPASS4), ...awg.BYPASS6 ], 'internet: the rest, and its DNS');
eq(awg.allowed_ips(m, srv, alice, { lan_bypass: true }), [ ...slice(awg.BYPASS4, 0, 2), '10.9.0.0/29', ...slice(awg.BYPASS4, 2), ...awg.BYPASS6 ],
'home too: the tunnel network with the other devices (the DNS is in it)');
srv.mesh = 'off';
srv.device_mesh = false;
eq(awg.allowed_ips(m, srv, alice, { lan_bypass: true }), [ ...dns(awg.BYPASS4), ...awg.BYPASS6 ], 'no mesh: the router');
srv.dns = [ '192.168.1.1', '192.168.1.53', 'fd00::53', '2001:4860:4860::8888', 'fe80::1' ];
let all = awg.allowed_ips(m, srv, bob, { lan_bypass: true });
ok(index(all, '192.168.1.1/32') >= 0 && index(all, '192.168.1.53/32') >= 0, 'every private IPv4 DNS server stays in the tunnel, not only the first');
eq(slice(all, length(all) - length(awg.BYPASS6) - 2), [ ...awg.BYPASS6, 'fd00::53/128', 'fe80::1/128' ],
'a private IPv6 one too; a public IPv6 one is in the rest already');
eq(length(all), length(awg.BYPASS4) + 2 + length(awg.BYPASS6) + 2, 'nothing else');
srv.dns = [ '1.1.1.1' ];
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: true }), [ ...awg.BYPASS4, ...awg.BYPASS6 ], 'a public DNS is in the rest already');
alice.access = 'lan';
alice.dns_mode = 'home';
let lan = awg.allowed_ips(m, srv, alice, { lan_bypass: true });
eq(lan, awg.allowed_ips(m, srv, alice), 'Home only: the same either way');
let c = awg.client_config(m, { ...m.devices.alice_phone, person: 'bob', lan_bypass: true });
eq(c.amnezia.allowed_ips, [ ...awg.BYPASS4, ...awg.BYPASS6 ], 'in the AmneziaVPN key');
ok(index(c.conf, `AllowedIPs = ${join(', ', [ ...awg.BYPASS4, ...awg.BYPASS6 ])}\n`) >= 0, 'in the .conf');
});
test('keepalive_range and idle_handshake', () => {
let srv = { keepalive: 25, obf: {} };
eq(awg.keepalive_range(srv, {}), [ 25, 25 ], 'the server\'s, no range');
eq(awg.keepalive_range(srv, { keepalive: 120 }), [ 120, 120 ], 'the device\'s own');
eq(awg.keepalive_range(srv, { keepalive: 0 }), null, 'off for the device');
eq(awg.keepalive_range({ keepalive: 0, obf: {} }, {}), null, 'off on the server');
let max = { keepalive: 25, obf: awg.obf_preset('max') };
eq(awg.keepalive_range(max, {}), [ 25, 35 ], 'jittered with 3.1');
eq(awg.keepalive_range(max, { keepalive: 60 }), [ 60, 70 ], 'the device\'s own, jittered');
// The first keep-alive after the rekey time (120 s; RekeyAfterTime's upper end) starts a handshake.
eq(awg.idle_handshake(srv, {}), 145, 'within the rekey time: up to one keep-alive past it');
eq(awg.idle_handshake(max, {}), 155, 'Maximum: RekeyAfterTime 100-120, keep-alive up to 35');
eq(awg.idle_handshake(srv, { keepalive: 100 }), 220, 'every second keep-alive');
eq(awg.idle_handshake(srv, { keepalive: 300 }), 300, 'every keep-alive once they are further apart');
eq(awg.idle_handshake({ keepalive: 25, obf: { rekey_after_time: '200-400' } }, {}), 205, 'past 180 s the key is refused anyway');
eq(awg.idle_handshake(srv, { keepalive: 0 }), null, 'no keep-alive: none');
});
test('client_config: the device\'s own MTU and keep-alive', () => {
let m = core.load();
let dev = m.devices.alice_phone;
let line = (c, k) => match(c.conf, regexp(`\n${k} = ([^\n]*)\n`))?.[1];
let c = awg.client_config(m, dev);
eq([ line(c, 'MTU'), line(c, 'PersistentKeepalive'), c.amnezia.mtu ], [ '1280', '25', '1280' ], 'the server\'s (a phone)');
let fp = awg.config_fingerprint(m, dev);
let old = { ...dev };
delete old.mtu;
delete old.keepalive;
delete old.lan_bypass;
eq(awg.config_fingerprint(m, old), fp, 'a device without values of its own keeps its fingerprint (as before the options)');
dev.mtu = 1420;
dev.keepalive = 0;
c = awg.client_config(m, dev);
eq([ line(c, 'MTU'), line(c, 'PersistentKeepalive'), c.amnezia.mtu, c.amnezia.persistent_keep_alive ], [ '1420', null, '1420', '0' ],
'its own; keep-alive off');
ok(awg.config_fingerprint(m, dev) != fp, 'a change asks it to import again');
m.servers.main.obf = awg.obf_preset('max');
dev.keepalive = 120;
c = awg.client_config(m, dev);
eq([ line(c, 'PersistentKeepalive'), c.amnezia.persistent_keep_alive ], [ '120-130', '120-130' ], 'jittered with 3.1');
});
+59
View File
@@ -0,0 +1,59 @@
// dawnline.awg_builds: the AmneziaWG generation of package and kernel module
// versions, whether an installed update waits for a reboot (its old module
// stayed loaded) and the generation that really runs meanwhile, which is
// what caps() reports.
import * as builds from 'dawnline.awg_builds';
import * as awg from 'dawnline.awg';
// The live router's module (3.1) after an update from a 2.0 one that could not be swapped.
const KMOD_31 = '6.12.94.3.1.20260906-r1';
const WAITING = { reloaded: false, boot: 'boot-1', prev_gen: '2.0', prev_core: 98304 };
test('gen of package versions', () => {
eq(builds.gen(null), null, 'not installed');
eq(builds.gen('3.1.20260812-r1'), '3.1', 'amneziawg-tools 3.1');
eq(builds.gen('3.1.0-r1'), '3.1', 'luci-proto-amneziawg 3.1');
eq(builds.gen('1.0.20250722-r1'), '2.0', 'July 2025 on: 2.0');
eq(builds.gen('1.0.20250901'), '2.0', 'no release suffix');
eq(builds.gen('1.0.20250610-r1'), '1.0', 'before July 2025');
eq(builds.gen('1.0.20241112-r2'), '1.0', '2024');
});
test('gen of kernel module versions', () => {
eq(builds.gen(KMOD_31), '3.1', 'kernel release in front');
eq(builds.gen('6.12.94.3.1.20260906'), '3.1', 'no release suffix');
eq(builds.gen('6.6.73.1.0.20250722-r1'), '2.0', '2.0 module');
eq(builds.gen('6.6.73.1.0.20250612-r1'), '1.0', 'first generation module');
eq(builds.gen('5.15.150.1.0.20240711-r3'), '1.0', '2024 module on an older kernel');
eq(builds.gen('3.1.20260812'), '3.1', 'the version.h string of a 3.1 module');
});
test('pending: an update waits for a reboot', () => {
ok(builds.pending(WAITING, 'boot-1', 98304), 'the old module still loaded, same boot');
ok(!builds.pending(WAITING, 'boot-2', 98304), 'rebooted');
ok(!builds.pending(WAITING, 'boot-1', null), 'no module loaded: the next one is the new one');
ok(!builds.pending(WAITING, 'boot-1', 110592), 'another module loaded (reloaded by hand)');
ok(!builds.pending({ ...WAITING, reloaded: true }, 'boot-1', 98304), 'the install swapped it');
ok(!builds.pending({ ...WAITING, reloaded: null }, 'boot-1', 98304), 'a record of a module Dawnline did not install');
ok(!builds.pending({ osrelease: '6.12.94', source: 'slava', tag: 'v25.12.5', installed: 1 }, 'boot-1', 98304),
'a record from before boots were kept');
ok(!builds.pending({ ...WAITING, boot: null }, null, 98304), 'the kernel gave no boot id');
ok(!builds.pending(null, 'boot-1', 98304), 'no record');
});
test('caps: the generation that runs while a reboot is pending', () => {
eq(builds.running_gen(WAITING, 'boot-1', 98304, KMOD_31), '2.0', 'the 2.0 module runs, not the 3.1 package');
eq(builds.running_gen(WAITING, 'boot-2', 98304, KMOD_31), '3.1', 'after the reboot: the package');
eq(builds.running_gen(WAITING, 'boot-1', null, KMOD_31), '3.1', 'nothing loaded: the package loads');
eq(builds.running_gen(null, 'boot-1', 98304, KMOD_31), '3.1', 'no record: the package');
eq(builds.running_gen({ ...WAITING, prev_gen: null }, 'boot-1', 98304, KMOD_31), null,
'a module installed by hand before: unknown, the tools are believed');
eq(builds.running_gen(null, null, null, null), null, 'nothing installed');
});
test('caps in a container without AmneziaWG', () => {
let c = awg.caps();
eq(c.kmod, null, 'no module package');
eq(c.pending, false, 'nothing waits for a reboot');
eq(builds.module_core(), null, 'no module loaded');
});
Loaded 100 of 302 files, more files were not shown because too many files have changed in this diff. Show more