Compare commits

24 Commits
Author SHA1 Message Date
Aemeath f2b5ba101b Dawnline 0.16.2
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 switches to a renewed HTTPS certificate on its own:
  after ACME issues or renews one, the page restarts with it instead of
  serving the old certificate until Dawnline restarts
2026-10-26 07:39:32 +03:00
Aemeath 0fd22b917a Dawnline 0.16.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
- Checking one component for updates in Components no longer fails
  with "XHR request timed out": the check starts at once instead of
  keeping the page waiting twenty seconds
- On a router without curl, updates and the installer download release
  files through GitHub's API: GitHub's own download links can make
  OpenWrt's built-in downloader hang
- Adding a device in the admin offers the same four types as the
  personal page: PC, Mobile, Router and Other (phones and tablets are
  one choice)
2026-10-26 06:41:54 +03:00
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
Aemeath 4f12ca19e7 Dawnline 0.10.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
- Portal redesigned from scratch. No header bar: the page opens with the
  server's name and the person's and fades under the edges. Device cards
  show the status, the last 7 days (hover a day for its figures) and a
  Connect or Update button; "Your access" folds into rows: what they can
  reach (with the names at home), data this month day by day, and when
  access ends. The page follows the system's light or dark theme
- Adding a device: pick the kind (PC, Mobile, Router, Other) and a name, or
  add it from the device itself with the page's QR code. The set-up sheet
  then shows the app for that system and the connection, waits for the
  first connection, says "<device> connected" and closes on its own
- Switching apps in the set-up sheet changes only what differs: the old
  words blur into the new ones, and the menu path is shown for iOS and
  Android in one line. Names, numbers and statuses that change on the page
  morph in place
- Dialogs open in the middle on a computer, on the same spring as the menu;
  buttons that wait for the router show a spinner at once
- A paused account gets one card that says so; the page's messages are
  short and no longer send people to the admin. A QR code of the page sits
  beside the breadcrumb, to open it on another device
- Allowed hours are shown in the visitor's own time zone
- The portal's Title setting is gone: the page and its tab take the
  server's name. A title set before is removed on upgrade
- The admin names .conf files after the server too, as the portal does
  (Outline-Home.conf); its device menu says "Download AmneziaWG config" and
  "Copy AmneziaVPN config", and its QR codes use the portal's round look in
  the admin's light or dark colours
- README rewritten, with screenshots made from a demo cast
  (scripts/capture-screenshots.mjs --demo)
2026-10-19 21:07:14 +03:00
Aemeath edeb1506fd Dawnline 0.9.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
- Portal: Reconnect replaces New keys and the connection sheet (QR, Key,
  File, and the menu's QR, key and .conf items). It gives the device new
  keys, shows it as "Not set up yet" until it connects with them (in the
  admin too) and opens the set-up sheet on the new configuration; "Update
  the connection" goes the same way. Reconnect is orange in the menu
- iPhone: "Open in AmneziaVPN" is "Send to AmneziaVPN": the key goes in as
  a .vpn file from the share sheet. AmneziaVPN takes vpn:// links only on
  Android; on iOS Safari said the address was invalid, or another app that
  claims vpn:// got the key. The desktop "Open in AmneziaVPN" link is gone
- A computer set up from a phone: get the app, add the connection, then
  "Or open your link on the computer"; "Another app" offers AmneziaWG and
  WireGuard there too and step 2 follows the pick. "Other" devices pick any
  system (iPhone/iPad, Android, Windows, Mac, Linux); the page counts as the
  device in hand only when the pick is its own system
- Import steps in each app's own words (iOS "+ → Create from file or
  archive", Android "+ → Import from file or archive", Mac, Windows "Add
  Tunnel → Import tunnel(s) from file"); Linux gets the awg-quick command
- Files are shared only on iOS (on Android the apps take no shared files:
  a download there), and alone: with a title, "Save to Files" also wrote
  the title as a .txt
- Files and tunnels are named after the server ("Outline Home" →
  Outline-Home.conf and .vpn) in the form every client accepts: letters,
  digits and "-", 15 characters, no Windows device names. The admin's
  downloads keep the device in the name. The AmneziaVPN key's description
  is the server's name alone
- The AmneziaVPN QR code holds the key without "vpn://": AmneziaVPN's
  scanner decodes the text as it is and failed on the prefix
- "This device" also when the page is opened beside the tunnel: the apps
  route the VPN's own address, which the portal shares, around their
  tunnel, so the one online device whose tunnel comes from the page's
  address is the one
- Fixed: "Already has AmneziaVPN?Copy the key" lost its space
2026-10-19 05:19:08 +03:00
Aemeath 7a6370aa9e Dawnline 0.8.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
- Fixed: the Overview's map stayed empty after leaving the page and coming
  back (the map freed on leaving was never made again); a map still loading
  when freed no longer draws into a dropped element
- A new connection's city shows within seconds: the agent looks its address
  up the moment the device connects or roams, in a child process so the
  watcher never waits, and open pages refresh once the place is known; the
  connection's entry in the activity log gets its place too. Since 0.7.0 the
  lookup waited for the minute tick and the pages for their 30-second poll
- Device window: each place has a strip of when the device was there (from
  the log's connections) and its share of the time; ▶ replays the period on
  the map: the place it leaves goes gray, a blue shimmer runs along a dotted
  arc to the next one, which lights up. A click or a drag on a strip goes to
  that moment; short visits are folded only past 24 moves. The fixed trail
  line is gone, and place names are no longer cut off at the map's edges
- Overview: the disguise tile's icon is gray when the disguise is Off
- People: "Add device" is a dashed chip with its label; "Send invite" is gone
  from the card (the invite card stays in its ⋯ menu)
2026-10-19 00:48:09 +03:00
Aemeath 466ca6c7b0 Dawnline 0.8.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
- Every field says what is wrong as you type, in the router's own words,
  and Save refuses what the router would: UDP port when editing a server,
  MTU, keep-alive, public address, DNS for devices, person name, device
  limit, end date and data limit, device names (the next free "Phone 2"
  is offered), home services, circles, portal title, redirect and other
  addresses, defaults, update time
- Cyrillic names give Latin ids, hostnames and file names; names are
  counted in characters, the rule names the characters it refuses; end
  dates must exist on the calendar; a mistyped extra portal address is
  refused instead of dropped
- The public address is checked on the router as it is typed: points at
  this router, at another address, behind Cloudflare, or the WAN is
  private or CGNAT; the wizard says so before the first step, never
  pre-fills a private WAN address and says where its suggestion came
  from; the Connection card says when the server was last reached from
  the internet; IPv6 names and literals work throughout
- A person can be moved to another server from their page; a server's
  tunnel network can be changed in the Danger zone (devices are
  renumbered and marked "Update config"); WAN and LAN zones come from the
  router's actual devices; when the public IPv4 changed, one click puts
  the new one in
- Over the data limit or outside the allowed hours the tunnel stays
  connected and the portal explains why nothing gets through, instead of
  a silent handshake failure; Health's "devices loaded" compares the
  peers themselves, not their count
- Portal: install links for this platform, two first steps on a first
  visit, the phone's back button closes a sheet, the file goes through
  the share sheet into the app, two QR codes (AmneziaVPN camera, AmneziaWG
  and WireGuard apps), the sheet notices the first connection
- Admin: Enter submits a dialog, arrow keys walk the menus, Find in People
  ("/" focuses it), a device of a paused, ended or over-limit person says
  so, "Keep access" past its end date is said on the Overview, Allowed
  hours enforce nothing until saved, the invite card shares the link
- Health warns when another package's policy routing (mwan3, pbr) sends
  tunnel traffic past the home-device path
- CLI: person ls, device ls, log with -n, --since, --level, --src and
  --json; exit code 2 for an unknown command and 1 when health finds an
  error; person rm asks for --yes when devices would go; devices added
  from the command line get their event and "issued" marker like the
  UI's
- Three disguises: Off, Balanced and Maximum. Standard and Strong (1.0-style
  junk only, which networks learned to spot) are no longer offered; a server
  still on one keeps running and its card says to switch. A new server gets
  the strongest disguise its router can run
- Portal: setting up a device is one sheet with two steps. Get the app
  (AmneziaVPN first; AmneziaWG, and WireGuard with the disguise off, behind
  "Another app") from the store of the device in hand, with the GitHub release
  where no store has it and the version the server needs said once; then add
  the connection (open in AmneziaVPN, copy the key, share or download the
  file). A device set up from another device gets its link to take there, as a
  QR code for a phone; a phone set up from a computer also gets the connection
  as a code, one code revealed at a time so the camera cannot read the wrong one
- Portal motion: the first visit comes in once (blocks in reading order,
  meters fill, the sun rises in the logo); a repaint glides cards to their
  new places and brings changed values into focus; sheets slide up on
  phones and can be pulled down, come into focus on a computer, follow
  their content's height and turn into the next sheet in place; tabs and
  segments slide, menus, tooltips and toasts grow out of what opened them,
  copy buttons turn into a check, buttons waiting for the router spin;
  with reduced motion only the fades remain
- Portal: while a device is set up, a card at the top shows the way from
  it to the router with a light running along it; on the first connection
  the way fills green, the steps fold away and the sheet closes by itself.
  The first connection is the first fresh handshake, so it is no longer
  missed while the watcher catches up (or after new keys), and the device's
  card goes on to Connected
- Portal: QR codes are light dots on a black card, fuller on dense keys,
  with "Show a light code" for scanners that read only dark on light (every
  code switches, the choice is kept); the link and code a set-up sheet
  hands to another device open that device's set-up there at once
- Portal: Remove and New keys ask in a small alert with the action's icon;
  the open one of two cards is not a button; device names are no longer
  repeated in every line of the set-up sheet; the code card lines up with
  the rest of its card (a class clash gave it the page's padding); text
  keeps the arrow cursor, store badges and link buttons are not underlined
2026-10-18 23:28:10 +03:00
Aemeath fd9543ce68 Dawnline 0.7.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
- Balanced, a new disguise for AmneziaWG 2.0 apps (AmneziaVPN 4.8.12 and
  newer): junk packets, padded cookie and data packets and DNS-shaped
  signature packets, for networks that learned to spot 1.0-style junk;
  offered when both the tools and the kernel module are 2.0 or newer
- The junk count and sizes in a device's configuration are the device's own
  (shifted a little, deterministically), so two phones of one family do not
  share one profile; they never require importing again
- Components remembers which AmneziaWG build was installed on which kernel;
  after a firmware upgrade Health says the build was for the old one and
  offers the build for the new firmware. A SNAPSHOT firmware is told there are
  no builds for it
- Location lookups moved off the agent's 1-second watcher to its minute tick,
  a few per minute within a time budget; the cache lives in tmpfs and goes to
  flash hourly, and addresses still shown on the map are never pushed out of
  it (and looked up again)
- The map library from the CDN is checked against its expected hash before it
  runs inside the LuCI page
- The activity log is copied to flash only when something was logged; the
  person page and the device drawer fetch only that person's events
- Admin UI: live updates survive the theme's in-page navigation, pollers stop
  with their page and sleep while the tab is hidden, the map is freed when
  leaving the Overview, a router that stops answering is said once (and when
  it is back), and an update of Dawnline under an open page asks for a reload
- Watchdog: no repairs while an update runs; a target that keeps failing keeps
  its back-off (repairs are forgotten after ten good minutes, not one); the
  LuCI link is reloaded or restarted three times at most, not every hour for
  good; the one-click "ifup" fix accepts only Dawnline's own tunnels
- Health warns when the router's flash is nearly full (settings would stop
  saving); the portal runs two processes instead of four on routers with
  little memory
- "Remove their devices" at an end date is never done on a clock that has not
  been set yet
2026-10-18 16:04:58 +03:00
Aemeath 31a2065f05 Dawnline 0.6.0
- Access rules fail closed: when the table cannot load, no device is loaded
  into the tunnels (the firewall alone would let every loaded device reach
  everything); an older table that survived a failed rebuild keeps its rules
  and a revoked device still leaves. The agent re-syncs within a minute when
  the table is gone
- A change the router saved but could not put into effect (access rules that
  did not load, a server that refused its devices) is said in the admin UI
  instead of a plain "Saved"
- The guard judges every packet, not only a connection's first: a change of
  access, a pause or a limit now cuts open connections too
- Each server's home networks are its own: with several servers, "all home"
  on one no longer reaches the other's networks where firewall zones overlap
- People limited to some home networks reach the router only on the
  addresses in those networks (LuCI and SSH on the main LAN stay closed)
- Internet-only people can open their personal portal with the VPN on
- Tunnel DNS reaches the resolver and the LAN's DNS from servers that do not
  forward to those zones on their own (Home-only names on servers without
  "like a home device", LAN DNS on servers with no home network)
- A new personal link offers to remove the devices added through the old one,
  so a leaked link is really contained
- Import and restore refuse an inconsistent file (devices with addresses
  outside their server, shared addresses, malformed keys, broken references);
  Health reports one, and the sync leaves such a device out instead of
  failing its server. A config write that did not reach flash is an error,
  not a silent success
- Backups are kept per kind (nightly ones no longer push out manual or
  pre-delete ones), nightly and pre-change backups hold the config only,
  archives are written whole or not at all, and a failed nightly backup is
  logged. A restore no longer has its history overwritten by the agent's
  in-memory counters
- Settings defaults and ranges come from one place (dawnline.schema)
- Portal: anything not shaped like a personal link is answered by a shell
  before ucode starts (a scan on the root costs nothing); 4 portal processes
  at once instead of 16; a link may make 40 changes a quarter hour; over
  plain HTTP the page shows but configurations, new devices and new keys are
  refused with the HTTPS twin of the link; the connect sheet polls only while
  the first connection is awaited, with backoff, and stops once the link
  stopped working
- Updates: after Dawnline's own package changes, a shell checks that LuCI
  reaches it and the agent runs, and puts the kept previous version back when
  they do not (automatic runs always keep it); the AmneziaWG module reload
  verifies rmmod and modprobe; installs check free space; on apk a reinstall
  that changed nothing is an error; uninstall.sh hands the update lock to the
  removal it calls; an upgrade restarts the service only where it was
  enabled; the release workflow pins the SDK images by digest and the actions
  by commit
- AmneziaWG: features count only when both the tools and the kernel module
  have them; a server whose disguise this build cannot run (a 3.1 preset
  after a rollback to 2.0) is kept down and reported; Components tells 1.0
  builds from 2.0 ones; `awg show dump` is parsed by shape; Maximum's
  DNS-shaped signature packets are made for each server and its keep-alive
  is a 25-35 s range
- CI compiles every ucode file and runs the new tests/ucode unit tests (54
  tests on the real libuci) in OpenWrt 24.10 and 25.12 rootfs containers;
  scripts/compile-ucode.sh does the same wherever ucode runs and
  scripts/ucode-container.sh locally with docker; lint-ucode checks POSIX
  regexes and module layering; a tag builds only after CI passes
2026-10-18 15:32:27 +03:00
Aemeath 2b98abdba4 Dawnline 0.5.2
- Fixed: a new server with the Maximum disguise could not be created ("jmin=10
  (64-1024)"): the 3.1 preset's small junk packets failed Dawnline's own check
- Fixed: guesses from a shared address (every visitor behind Cloudflare) could
  lock people with valid links out of the portal for 15 minutes; a valid link
  always opens now, only wrong guesses are counted
- Fixed: a disabled Dawnline still loaded every device into the tunnels when
  netifd brought them up, with nothing enforcing end dates or limits afterwards
- Fixed: an MTU of 1380 chosen by hand was deleted on every apply (the one-time
  switch to automatic MTU now runs once)
- Locations (city lookups) are off by default on new installs: they send
  people's addresses to a third party. Routers that had them on keep them on
- "Don't warn" before an end date is honoured, and the warning window is the
  one chosen for the person on the Overview, People, the person page and the
  portal alike (People and Overview used to warn 3 days before whatever was set)
- "Ends today" and "ends tomorrow" instead of "ends in 1 day"
- Renaming a person keeps the dialog open when the router refuses the name
- Settings → Portal no longer saves a listening port its own help line marks
  as taken
- "Remove Dawnline" is live only once "remove" is typed
- Downloaded .conf files are named after the device first, and two devices
  whose names only differ past the 15th character no longer get the same file
  (and tunnel name in the app)
2026-10-18 14:42:01 +03:00
Aemeath 1a2f0b327e README: new screenshots for 0.5.1
- scripts/capture-screenshots.mjs takes the raw screenshots from a live router (headless Chromium over DevTools, 2x PNG), hides the domain with --mask and public IPs
- Overview now shows the whole connection map; the separate map screenshot is gone
- frame-screenshots.py frames 2x captures
2026-10-17 07:39:24 +03:00
Aemeath 5768856d76 Dawnline 0.5.1
Build packages / Version (push) Waiting to run
- The map places everyone within their city: the IP gives the city
  alone, so each person gets a fixed spot of their own in it (1.5-5 km
  from its centre, clear of the server and of each other)
- People who would cover each other share one plate with their avatars
  and the city once, and people on top of the server ride in the
  server's plate (no more pointers, repeated labels or counts); zooming
  in they part to their own spots
- Avatars in a plate keep their device badges (round for one device);
  a click on an avatar opens that person's card, flying to them first
  when they are elsewhere, and a click on a plate brings its people into
  view, at city level when they share one, close enough to part
- Plates follow the zoom: compact far out (small avatars, no badges or
  place names), small badges at country level, full size closer in
- Plates slide, grow and shrink smoothly: avatars glide to their places,
  "+N" changes in place, and the plate's width follows
- Fixed: a hovered person could stay highlighted (everyone else faded)
  after their plate split under the pointer
- Overview's Online tile: small avatars light up with a halo round their
  ring, and the device badge no longer cuts a dark square into the hover
2026-10-17 03:55:24 +03:00
Aemeath 972e522518 Dawnline 0.5.0
Build packages / Version (push) Waiting to run
- Where people connect from is a globe map now: live arcs from each
  person to the server, grey ones for the last 24 h, 7 or 30 days, avatars
  instead of dots, the server's own marker, and a light map in light mode;
  it zooms to fit the people shown and follows them as they come and go
- Markers that overlap move apart with a pointer to their spot; people
  next to the server fold into a count on it; a click zooms in and opens a
  floating card (never clipped by the map), closing flies back
- The person page maps where they connected from, older places fading;
  the device panel lists its places in order, and connections from the LAN
  or through the router's own address stay off the maps ("LAN" in grey)
- Setup and new servers check the UDP port (taken by another program, a
  forward or another server) and the subnet (three numbers + .x, a private
  range not in use) as you type; the default port is 4500
- The personal portal can share the server's port number (TCP beside UDP);
  its port is checked against forwards and other services
- A new server comes up at once: the kernel module is loaded and the
  network restarted when OpenWrt doesn't know AmneziaWG yet
- A turned-off server is a state of its own: no "tunnel down" or DNS
  warnings, "Turned off" in yellow, a white Turn on, and people on it are
  not shown as paused
- Pause everyone is removed: turning a server off does the same (a router
  left paused keeps its servers off after the update)
- People: a stopped person's card fades and says why across its bottom,
  with the one action that lifts it (Resume, +10 GB, Extend 1 month);
  people held by a limit or end date sort below the others, paused last
- The person page shows the state as text ("Paused") with a Resume
  button, also while their server is off
- The portal tells a paused or ended person just that, even with the
  server off, and lets them change nothing until the admin lifts it (the
  router refuses too); its notices look like Overview's
- Automatic MTU: with the field empty the tunnel, computers and routers
  get 1380 minus AmneziaWG S4 (1368 on Maximum), phones and tablets 1280;
  a typed MTU still caps phones and tablets at 1280, and servers on the
  old default 1380 move to automatic (phones and tablets get "Update
  config", their old files keep working)
- Only procd's agent runs: a second copy (started by hand or left over)
  refuses to start or is ended within 5 minutes, so no more stray paused
  and resumed events; a device that leaves the tunnel is offline at once
- The installer picks the newest release (it took the lowest), DNS
  lookups can't hang, and tooltips and floating cards close on scroll and
  on leaving the page
2026-10-17 01:03:23 +03:00
350 changed files with 58534 additions and 7203 deletions

No files matched your search

+27 -16
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.
@@ -12,10 +13,19 @@ on:
workflow_dispatch:
# Read-only by default; only the release job may write (publish the release).
# Everything that runs here is pinned to a digest or a commit: the packages
# it publishes are installed as root on every router with automatic updates
# on, so a re-pointed tag must not be able to change what gets built.
permissions:
contents: read
jobs:
# The same checks as on main (ci.yml), on the tag itself: nothing is built or
# published until they pass.
ci:
name: CI
uses: ./.github/workflows/ci.yml
version:
name: Version
runs-on: ubuntu-24.04
@@ -23,7 +33,7 @@ jobs:
version: ${{ steps.version.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
@@ -44,23 +54,23 @@ jobs:
build:
name: Build ${{ matrix.type }}
runs-on: ubuntu-24.04
needs: version
needs: [version, ci]
strategy:
fail-fast: true
matrix:
include:
- { type: ipk, sdk: 'itdoginfo/openwrt-sdk-ipk:24.10.6' }
- { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3' }
- { type: ipk, sdk: 'itdoginfo/openwrt-sdk-ipk:24.10.6@sha256:a6bd28c380b251ebdb1d6d5f83e55ecb0a3c1808b5a8f4841424abc8019a903f' }
- { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3@sha256:6d832008ddd1b8ec4edc84f5e6e0bf22a13ba2d6888083a8e69fa26d752c276f' }
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@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
@@ -77,10 +87,11 @@ jobs:
run: scripts/build-packages.sh ${{ matrix.type }}
- name: Upload
uses: actions/upload-artifact@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
@@ -94,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@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
fetch-depth: 0
@@ -105,7 +116,7 @@ jobs:
cat notes.md
- name: Download packages
uses: actions/download-artifact@v4
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: package-*
path: release
@@ -114,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@v2
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
with:
name: Dawnline ${{ github.ref_name }}
tag_name: ${{ github.ref_name }}
+95 -20
View File
@@ -1,9 +1,12 @@
name: CI
# Every push to main and every pull request; also called by build.yml, so a
# tag never publishes a release without these checks passing on it.
on:
push:
branches: [main]
pull_request:
workflow_call:
permissions:
contents: read
@@ -21,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
@@ -43,20 +46,49 @@ jobs:
exit 1
fi
# Sources and the test files (tsconfig.test.json).
- name: Type check
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
- 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
if ! git diff --exit-code -- ../package; then
echo "::error::The committed bundles are out of date. Run 'npm run build' in web/ and commit the result."
changed="$(git status --porcelain --untracked-files=all -- ../package)"
if [ -n "$changed" ]; then
echo "$changed"
echo "::error::The build changed a tracked file under package/ or wrote one .gitignore does not cover."
exit 1
fi
@@ -70,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"
@@ -79,45 +114,85 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# Every shell script by its shebang (the init script's is "/bin/sh
# /etc/rc.common"), so a new hotplug or libexec script is covered the
# day it appears. Files without a shebang (keep.d lists) are not shell.
- name: ShellCheck
run: |
shellcheck --version
shellcheck -S warning \
install.sh \
uninstall.sh \
package/luci-app-dawnline/root/etc/init.d/dawnline \
package/luci-app-dawnline/root/etc/uci-defaults/90_dawnline \
files="$(grep -rlIE '^#!(/usr)?/bin/(sh|bash|env (sh|bash))( |$)' \
install.sh uninstall.sh package/luci-app-dawnline/root scripts tests | sort)"
echo "$files"
for f in package/luci-app-dawnline/root/etc/init.d/dawnline \
package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline \
package/luci-app-dawnline/root/usr/libexec/dawnline/resolver \
package/luci-app-dawnline/root/usr/libexec/dawnline/heartbeat \
scripts/*.sh
package/luci-app-dawnline/root/usr/libexec/dawnline/postupdate \
package/luci-app-dawnline/root/usr/share/dawnline/portal/www/cgi-bin/portal; do
echo "$files" | grep -qx "$f" || { echo "::error file=$f::not found by the shebang scan"; exit 1; }
done
# shellcheck disable=SC2086
shellcheck -S warning $files
ucode:
name: ucode static checks
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Use before definition
- name: Lint (use before definition, exports, POSIX regexes, rpcd methods)
run: python3 scripts/lint-ucode.py
- name: Executables keep their mode
run: |
cd package/luci-app-dawnline/root
for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver usr/libexec/dawnline/heartbeat \
etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do
for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver usr/libexec/dawnline/heartbeat usr/libexec/dawnline/postupdate \
etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal usr/share/dawnline/portal/cgi.uc; do
[ -x "package/luci-app-dawnline/root/$f" ] || { echo "::error file=package/luci-app-dawnline/root/$f::not executable (git update-index --chmod=+x $f)"; exit 1; }
done
for f in scripts/check-ucode.sh scripts/compile-ucode.sh scripts/ucode-container.sh tests/ucode/run.sh tests/ucode/fixtures/bin/awg; do
[ -x "$f" ] || { echo "::error file=$f::not executable (git update-index --chmod=+x $f)"; exit 1; }
done
- name: Versions agree
run: |
v="$(sed -n 's/^PKG_VERSION:=//p' package/luci-app-dawnline/Makefile)"
grep -q "^export const VERSION = '$v';" package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc
grep -q "\"version\": \"$v\"" web/package.json
grep -q "^export const VERSION = '$v';" package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc ||
{ echo "::error::util.uc VERSION differs from the Makefile ($v)"; exit 1; }
grep -q "\"version\": \"$v\"" web/package.json ||
{ echo "::error::web/package.json version differs from the Makefile ($v)"; exit 1; }
python3 - "$v" <<'PY'
import json, sys
v = sys.argv[1]
lock = json.load(open('web/package-lock.json'))
got = (lock.get('version'), lock.get('packages', {}).get('', {}).get('version'))
if got != (v, v):
print(f"::error::web/package-lock.json says {got}, the Makefile {v}: run 'npm install' in web/")
sys.exit(1)
PY
echo "Version $v"
ucode-compile:
# scripts/compile-ucode.sh and tests/ucode on the release's own ucode and
# libuci, in the OpenWrt rootfs containers scripts/ucode-container.sh pins
# by digest (24.10 = opkg, 25.12 = apk: the two the packages are built for).
name: ucode compiles and tests pass (OpenWrt ${{ matrix.release }})
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
release: ['24.10', '25.12']
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Compile every ucode file and run tests/ucode
run: scripts/ucode-container.sh ${{ matrix.release }}
+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/
+12 -6
View File
@@ -9,27 +9,33 @@ 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`, `check-ucode.sh` (compiles every module on the router without installing), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`.
- `scripts/` — `lint-ucode.py`, `compile-ucode.sh` (compiles every ucode file of a tree wherever ucode runs), `check-ucode.sh` (the same on the router, without installing), `ucode-container.sh` (compile and unit tests in the OpenWrt rootfs containers CI uses), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`.
- `tests/ucode/` — unit tests of the ucode modules (`run.uc` runs every `*.test.uc`; fixtures for `/etc/config` and a stand-in `awg`), run in a container by `run.sh`.
## Checks before a commit or deploy
- `python3 scripts/lint-ucode.py` and `scripts/check-ucode.sh` (needs the router); new ucode entry points are added to the compile list there and to the executables list in `.github/workflows/ci.yml`.
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm test`, `npm run build` — and commit the rebuilt bundles.
- `shellcheck -S warning` for the shell scripts (CI runs it).
- `python3 scripts/lint-ucode.py` (use before definition, exports, POSIX regexes, rpcd methods; layering notes are informational).
- `scripts/ucode-container.sh` (needs docker): compiles every ucode file and runs `tests/ucode` on OpenWrt 24.10 and 25.12, exactly what CI does. `scripts/check-ucode.sh` compiles on the router instead when there is no docker. New ucode entry points are added to the compile list in `scripts/compile-ucode.sh`, to `lint-ucode.py`, and to the executables list in `.github/workflows/ci.yml`; a pure function gets a case in `tests/ucode/<module>.test.uc`.
- In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm run 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`).
## Releases
- A release is one commit on `main` titled `Dawnline X.Y.Z`; its body is `- ` points, which become the GitHub release notes and the Components "What's new". Work from a branch is squashed into that one commit.
- Bump the version in `package/luci-app-dawnline/Makefile` (`PKG_VERSION`), `util.uc` (`VERSION`), `web/package.json` and `web/package-lock.json` (CI checks they agree).
- No `Co-Authored-By` or other agent attribution in commits.
- Push `main`, then an annotated tag `vX.Y.Z` ("Dawnline X.Y.Z"); the "Build packages" workflow publishes the `.ipk`, `.apk` 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
+327 -118
View File
@@ -1,90 +1,192 @@
# Dawnline
<div align="center">
[![CI](https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml/badge.svg)](https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml)
[![Build packages](https://github.com/tickcount/luci-app-dawnline/actions/workflows/build.yml/badge.svg)](https://github.com/tickcount/luci-app-dawnline/actions/workflows/build.yml)
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
<img alt="Dawnline" src="docs/assets/logo-light.svg" width="88" height="88">
</picture>
Your OpenWrt router as a private VPN for the people you choose.
<h1>Dawnline</h1>
Dawnline runs an [AmneziaWG](https://docs.amnezia.org/) server on the router
and gives every person a personal link. They open it, add their own devices
(up to the limit you set) and connect with AmneziaVPN or AmneziaWG. You decide
what each person may reach: the home network, the internet, or both.
**Your OpenWrt router as a private VPN for the people you choose.**
Dawnline is the successor of [Liminal](https://github.com/tickcount/openwrt-liminal):
the same idea rebuilt around people instead of peers, with a personal portal,
limits, live traffic and a LuCI admin that follows a modern design.
<a href="https://github.com/tickcount/luci-app-dawnline/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Latest release" src="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<a href="https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="CI" src="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<a href="https://github.com/tickcount/luci-app-dawnline/releases"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Downloads" src="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<a href="LICENSE"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="License" src="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<br>
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 24.10" src="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 25.12" src="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
<a href="https://docs.amnezia.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=dark"><img alt="AmneziaWG 2.0 and 3.1" src="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=light"></picture></a>
![Overview](docs/screenshots/overview.png)
[**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)
| People | A person |
**English** &nbsp;·&nbsp; [Русский](README_ru.md)
</div>
<br>
Dawnline runs an [AmneziaWG] server on your OpenWrt router and gives every
person you invite **a personal link**. They open it, **add their own phones and
computers** and connect with AmneziaVPN, AmneziaWG or WireGuard. You decide
**what each of them may reach** (the home network, the internet, or both) and
**for how long, how much and when**.
<p align="center">
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal.png" alt="The personal portal: devices and access, and adding a phone in three steps" width="860"></a>
<br>
<sub>A person's own page: their devices and access. Adding a phone takes three steps, and the page sees it connect.
<a href="https://dawnline-demo.vercel.app"><b>Try it in the live demo</b></a>: nothing installs and nothing connects.</sub>
</p>
## 💡 Why Dawnline?
Sharing a home VPN usually means making a config file by hand, sending it over
a messenger and hoping nobody shares it further. Dawnline turns that around:
| | A VPN by hand | With Dawnline |
|---|---|---|
| **Setting up a device** | You make a config and send it | They add it themselves from their link |
| **Who can do what** | Everyone gets the same | Home, internet or both, per person |
| **Ending access** | Find and delete their peers | A date, a data limit, or one click |
| **Knowing what goes on** | Read `wg show` | Who is online, traffic, places, a log |
| **When something breaks** | You find out from them | A watchdog notices and repairs it |
It is the successor of [Liminal]: the same idea rebuilt around people instead
of peers, with a personal portal, limits, live traffic and a LuCI admin that
follows a modern design.
## 🚀 Quick start
1. **Install** on the router (it asks before it changes anything):
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
2. **Set up** in LuCI: <kbd>Network</kbd> › <kbd>Dawnline</kbd>, and follow the
wizard. It suggests the port, the public address and the networks.
3. **Invite** someone: <kbd>Add person</kbd>, then send them the link or the
invite card with its QR code. They do the rest.
> [!TIP]
> Behind Cloudflare, give the portal a port Cloudflare proxies: 2053, 2083,
> 2087, 2096 or 8443.
## ✨ Features
<table>
<tr>
<td width="50%" valign="top">
<h3>🔗 A link, not an account</h3>
<p>Three words, like <code>vpn.example.com/kamiro-telosu-bavine</code>. The link is the key: no sign-up, no password, and a new link locks the old one out at once.</p>
</td>
<td width="50%" valign="top">
<h3>📱 Their own devices</h3>
<p>People add, rename and remove devices up to their limit. Adding one walks them through it: the right app, then a QR code, a link, a key or a file.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>👥 People, not peers</h3>
<p>One card per person with their devices, who is online, traffic, end date and data limit. Filter by who needs attention or is paused.</p>
</td>
<td valign="top">
<h3>🧭 Who reaches what</h3>
<p>The home network, the internet or both; only some networks or devices at home (a NAS, Home Assistant). Family sees family, guests see guests.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>⏳ Limits</h3>
<p>End dates, monthly or total data limits, allowed hours, a pause button. Changes apply at once, without dropping anyone else's connection.</p>
</td>
<td valign="top">
<h3>🕶️ Disguise</h3>
<p>Presets that make the VPN traffic harder to spot and block, with what each one needs from the apps.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🏠 Internet like a home device</h3>
<p>Turn it on and people's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too. Off by default: it costs speed.</p>
</td>
<td valign="top">
<h3>🗺️ Overview and places</h3>
<p>Who is online with what, speed now, the last 30 days, and a map of where people connect from, at city level.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🩺 Repairs itself</h3>
<p>Health checks with one-click fixes, and a watchdog that checks the tunnels, access rules and portal every minute and mends them.</p>
</td>
<td valign="top">
<h3>📦 Updates and backups</h3>
<p>Dawnline and AmneziaWG built for your firmware in one place; nightly backups, and export and import to move to another router.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🌐 English and Russian</h3>
<p>The portal follows the visitor's language and switches in its header. The admin pages and the router's messages come in Russian with the <code>luci-i18n-dawnline-ru</code> package.</p>
</td>
<td valign="top"></td>
</tr>
</table>
## 🧩 How it works
```mermaid
flowchart LR
you(["🛠️ You, in LuCI"]) -- "add a person" --> link["🔗 Their link"]
link -- "they open it" --> portal["📱 Their portal"]
portal -- "add a device" --> app["App and connection"]
app == "AmneziaWG tunnel" ==> router["🌅 Dawnline<br>on your router"]
router -- "if allowed" --> home["🏠 Home network"]
router -- "if allowed" --> net["🌍 Internet"]
```
1. **You add a person** in LuCI and choose what they may reach, their device
limit, an end date or a data limit.
2. **They open their link** on any device. The portal is theirs alone: it shows
their devices and their access; access and limits stay yours to change.
3. **They add a device.** The portal points them to the app for that system and
hands over the connection; the router gives each device its own keys.
4. **The device connects** through the router's AmneziaWG server, and Dawnline
lets through what that person may reach, counts their traffic and keeps to
their limits.
## 📸 A closer look
<p align="center">
<img src="docs/screenshots/overview.png" alt="Overview: who is online, speed, the last 30 days and where people connect from" width="720">
<br>
<sub><b>Overview</b>: who is online, speed now, the last 30 days and a map of where people connect from.</sub>
</p>
<table>
<tr>
<td width="50%" valign="top">
<img alt="People: everyone on the server, with their devices, data and state" src="docs/screenshots/people.png">
<p align="center"><sub><b>People</b>: online, ending soon, over the limit, outside their hours, paused.</sub></p>
</td>
<td width="50%" valign="top">
<img alt="A person: their devices, traffic, places and limits" src="docs/screenshots/person.png">
<p align="center"><sub><b>A person</b>: their devices, traffic, places and limits.</sub></p>
</td>
</tr>
</table>
## 📋 Requirements
| | What Dawnline needs |
|---|---|
| ![People](docs/screenshots/people.png) | ![Person](docs/screenshots/person.png) |
| **OpenWrt** | 24.10 (opkg, `.ipk`) or 25.12 (apk, `.apk`) |
| **AmneziaWG** | `kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`: the installer adds a build made for your firmware when they are missing |
| **Free flash** | about 2 MB |
| Personal portal | Home network access |
|---|---|
| ![Personal portal](docs/screenshots/portal.png) | ![Access](docs/screenshots/access.png) |
![Where people connect from](docs/screenshots/map.png)
## Features
- **People, not peers.** One card per person with device chips, live status,
traffic, end date and data limit. Add a person, send them the link or the
invite card (QR code), and they do the rest.
- **Personal portal.** Every person gets a link made of three words
(`https://vpn.example.com/kamiro-telosu-bavine`). The link is the key: no
accounts, no sessions, and a new link locks the old one out at once. People
add, rename and remove their devices and get each one as a QR code,
"Open in AmneziaVPN" (`vpn://`), a key or a `.conf` file. They cannot change
access or limits. Links work on the portal's own port with a Let's Encrypt
certificate (via ACME), several addresses at once (a Cloudflare-proxied name,
a plain IP), the same link at home, and wrong links can redirect to your
website. Behind Cloudflare, pick a port it proxies (2053, 2083, 2087, 2096 or
8443).
- **Access per person**, enforced in an `inet dawnline` nftables table on the
tunnel interface: home network only, internet only, or both, and optionally
only some home networks or home services (picked from the devices the router
sees over DHCP). Devices of different people reach each other never, always,
or within circles (family sees family, guests see guests). "Who reaches what"
sums up the rules and "Check access" walks them step by step for a device
and an address.
- **Limits.** End dates (pause, keep, or remove devices when they pass), monthly
or total data limits, allowed hours, pause one person or everyone. Devices
drop off the tunnel at once (`awg syncconf`, no interface restart).
- **Disguise presets** for AmneziaWG obfuscation (junk packets,
header and padding parameters), with what each preset needs from the apps.
- **Internet like a home device.** Tunnel clients' internet traffic enters the
router from the LAN, through a small network namespace on the LAN bridge
(needs `kmod-veth`). Whatever handles LAN traffic on the router (proxies, DPI
bypass, DNS filters, the `lan` zone) handles VPN clients too, with no
per-tool integration.
- **Overview.** Who is online with what, speed now, today and the last 30 days,
and a map of where people connect from (city level).
- **Diagnostics.** Health checks with one-click fixes, including the ones that
matter for reaching the portal from outside (DNS, port forwards, reply
routing behind proxies such as SSClash/Mihomo, certificate coverage). A
watchdog checks the tunnels, access rules, portal, resolver and LuCI link
every minute and repairs them on its own (a cron job looks after the agent
itself). One log holds people's activity and the service log: tunnel starts
and stops with netifd's reasons, repairs and errors (`dawnline log` on the
router).
- **Updates.** Dawnline itself, AmneziaWG builds for your firmware (choose
between [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt)
and [2Grey](https://github.com/2Grey/awg-openwrt), AmneziaWG 2.0 or 3.1), and
the few OpenWrt packages Dawnline adds.
- **Backups** nightly and before risky operations, JSON export/import to move
to another router.
## Requirements
- OpenWrt **24.10** (opkg, `.ipk`) or **25.12** (apk, `.apk`)
- AmneziaWG (`kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`):
the installer adds a build made for your firmware when it is missing
- About 2 MB of free flash
## Install
On the router:
## 📥 Install
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
@@ -92,17 +194,22 @@ sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline
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 Dawnline package for your package manager,
checks it against `sha256sums.txt`, installs AmneziaWG built for your firmware
if it is missing, then installs Dawnline with its dependencies and checks that
LuCI can reach it. Then open **LuCI → Network → Dawnline** and run the setup
wizard.
changes anything. It downloads the package for your package manager, checks it
against `sha256sums.txt`, installs AmneziaWG built for your firmware if it is
missing, then installs Dawnline (with its Russian translation when LuCI is in
Russian) and checks that LuCI can reach it.
Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
and the service state to `/etc/dawnline/installer-backups/` (the newest three
are kept); if a step fails, it puts them back. Packages are not rolled back: to
return to an older release, run the installer with `--tag`. Everything it does
is logged to `/tmp/dawnline-install.log`.
> [!NOTE]
> Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
> and the service state to `/etc/dawnline/installer-backups/` (the newest three
> are kept), and puts them back if a step fails. Packages are not rolled back:
> to return to an older release, run the installer with `--tag`. Everything it
> does is logged to `/tmp/dawnline-install.log`.
<details>
<summary><b>Installer options</b></summary>
<br>
With options, download it first:
@@ -111,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 | |
@@ -119,39 +227,68 @@ 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](https://github.com/Slava-Shchipunov/awg-openwrt), then [2Grey](https://github.com/2Grey/awg-openwrt) (`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 |
When GitHub is slow or blocked, the installer retries downloads through
`ghfast.top` and `gh-proxy.com` on its own. To fetch the installer itself
through a mirror:
</details>
<details>
<summary><b>When GitHub is slow or blocked</b></summary>
<br>
The installer retries downloads through `ghfast.top` and `gh-proxy.com` on its
own. To fetch the installer itself through a mirror:
```sh
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)"
sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
By hand, from a [release](https://github.com/tickcount/luci-app-dawnline/releases):
</details>
<details>
<summary><b>Installing by hand</b></summary>
<br>
From a [release](https://github.com/tickcount/luci-app-dawnline/releases):
```sh
opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
```
**Upgrade** from **Dawnline → Updates**, or run the installer again. Settings,
keys and history are kept, and a backup is made first.
The Russian translation is `luci-i18n-dawnline-ru-<version>` from the same
release, installed the same way after the app (then `/etc/init.d/uhttpd restart`).
**Remove** on the router:
</details>
**Upgrade** from <kbd>Dawnline</kbd> › <kbd>Components</kbd>, or run the installer
again. Settings, keys and history are kept, and a backup is made first.
### Remove
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
```
It backs up the configuration to `/etc/dawnline/backups`, runs Dawnline's own
removal (the same as **Settings → Remove Dawnline from this router**), removes
the package and cleans up what is left. AmneziaWG stays installed, since other
tunnels may use it. After installing Dawnline again, restore the backup in
**Settings → Backups**. With options, download it first:
removal (the same as <kbd>Settings</kbd> › <kbd>Remove Dawnline from this router</kbd>),
removes the package and cleans up what is left. After installing Dawnline
again, restore the backup in <kbd>Settings</kbd> › <kbd>Backups</kbd>.
> [!IMPORTANT]
> AmneziaWG stays installed, since other tunnels may use it. Add `--remove-awg`
> to take it away too.
<details>
<summary><b>Uninstaller options</b></summary>
<br>
With options, download it first:
```sh
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
@@ -165,25 +302,83 @@ sh /tmp/dawnline-uninstall.sh --dry-run
| `--remove-awg` | Also remove AmneziaWG, unless another interface still uses it (`--keep-awg`, the default, keeps it) |
| `-n`, `--dry-run` | Show what would be removed; change nothing |
By hand: **Settings → Remove Dawnline from this router** (keeps a backup), then
`opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`.
By hand: <kbd>Settings</kbd> › <kbd>Remove Dawnline from this router</kbd>
(keeps a backup), then `opkg remove luci-app-dawnline` or
`apk del luci-app-dawnline`.
## What Dawnline changes on the router
</details>
## ❓ FAQ
<details>
<summary><b>Which apps do people use?</b></summary>
<br>
AmneziaVPN or AmneziaWG on phones and computers, and plain WireGuard when the
disguise is off. The portal shows each person the app for their system and how
to add the connection in it.
</details>
<details>
<summary><b>What happens when someone loses their link?</b></summary>
<br>
Make a new one on their page. The old link stops working at once; their devices
keep working, unless you tick the ones to remove with it.
</details>
<details>
<summary><b>Does it touch the rest of my router?</b></summary>
<br>
Only what it created, and `dawnline teardown` removes all of it. The full list
is under [What Dawnline changes on the router](#-what-dawnline-changes-on-the-router).
</details>
<details>
<summary><b>How do I move to another router?</b></summary>
<br>
<kbd>Export JSON</kbd> in <kbd>Settings</kbd> › <kbd>Backups</kbd> on the old
one, install Dawnline on the new one and import the file there.
</details>
<details>
<summary><b>Where do the places on the map come from?</b></summary>
<br>
From the address a device connects from, looked up at city level and cached on
the router. It can be turned off in <kbd>Settings</kbd>.
</details>
## 🧾 What Dawnline changes on the router
Only objects it created: network interfaces tagged `_dawnline`, firewall
sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline`,
the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the
latter a port of the LAN bridge), policy rules for the tunnel interfaces with
one routing table, a second dnsmasq instance on port 5354
(`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat check
and, while the portal is on, a uhttpd instance for it. `dawnline teardown`
removes all of them.
latter a port of the LAN bridge, which needs `kmod-veth`), policy rules for the
tunnel interfaces with one routing table, a second dnsmasq instance on port
5354 (`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat
check and, while the portal is on, a uhttpd instance for it.
`dawnline teardown` removes all of them.
Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and
`/etc/dawnline/` (usage, events, issued configurations, backups). Live counters
are kept in `/var/run/dawnline` and flushed to flash at most hourly.
are kept in `/var/run/dawnline` and flushed to flash at most hourly. Access
changes reach the tunnel with `awg syncconf`, without restarting the interface;
`dawnline log` on the router shows the service log.
## Development
## 🧰 Development
```
package/luci-app-dawnline/
@@ -194,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
```
@@ -203,19 +400,31 @@ 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/frame-screenshots.py # frame docs/screenshots/raw/*.png for this README
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`.
## License
---
[MIT](LICENSE)
<div align="center">
<sub>Made for OpenWrt · <a href="LICENSE">MIT license</a> · <a href="#readme">Back to top ↑</a></sub>
</div>
[AmneziaWG]: https://docs.amnezia.org/
[Liminal]: https://github.com/tickcount/openwrt-liminal
[Slava-Shchipunov]: https://github.com/Slava-Shchipunov/awg-openwrt
[2Grey]: https://github.com/2Grey/awg-openwrt
+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/ \;
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#ffffff"/><path d="M14 38a18 18 0 0 1 36 0z" fill="#0a0a0a"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#0a0a0a" fill-opacity=".5"/></svg>

After

Width:  |  Height:  |  Size: 254 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#0a0a0a"/><path d="M14 38a18 18 0 0 1 36 0z" fill="#ffffff"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#ffffff" fill-opacity=".5"/></svg>

After

Width:  |  Height:  |  Size: 254 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 287 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 427 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 446 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 283 KiB

After

Width:  |  Height:  |  Size: 457 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 419 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 283 KiB

After

Width:  |  Height:  |  Size: 397 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 436 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

After

Width:  |  Height:  |  Size: 430 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 403 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 274 KiB

After

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 344 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 423 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 158 KiB

After

Width:  |  Height:  |  Size: 435 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 395 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 159 KiB

After

Width:  |  Height:  |  Size: 373 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 412 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 200 KiB

After

Width:  |  Height:  |  Size: 407 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 147 KiB

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 KiB

+192 -23
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
}
@@ -451,18 +487,19 @@ check_tools() {
# ---------- downloads ----------
# fetch_once URL FILE [SECONDS]
# fetch_once URL FILE [SECONDS] [ACCEPT]
fetch_once() {
_fu="$1"
_fd="$2"
_ft="${3:-$DOWNLOAD_TIMEOUT}"
_fa="${4:-}"
rm -f "$_fd"
case "$FETCHER" in
curl)
run_logged download curl -fsSL --connect-timeout "$CONNECT_TIMEOUT" --max-time "$_ft" \
--speed-limit 1024 --speed-time 30 -o "$_fd" "$_fu"
--speed-limit 1024 --speed-time 30 ${_fa:+-H "Accept: $_fa"} -o "$_fd" "$_fu"
;;
*) run_logged download "$FETCHER" -q -T "$CONNECT_TIMEOUT" -O "$_fd" "$_fu" ;;
*) run_logged download "$FETCHER" -q -T "$CONNECT_TIMEOUT" ${_fa:+--header="Accept: $_fa"} -O "$_fd" "$_fu" ;;
esac
_frc=$?
[ "$_frc" -eq 0 ] && [ -s "$_fd" ] && return 0
@@ -495,16 +532,29 @@ asset_digest() {
jsonfilter -i "$1" -e "@.assets[@.name='$2'].digest" 2>/dev/null | head -n 1 | sed -n 's/^sha256:\([0-9a-f]\{64\}\)$/\1/p'
}
# download URL FILE LABEL [SHA256]: direct, then (only when the sha256 is
# known) two mirrors, then direct again. A file whose sha256 doesn't match is
# thrown away and the next source is tried; without a sha256 only GitHub
# itself is used.
# A release file's URL in the GitHub API, from release JSON (empty if unknown).
# Asked for application/octet-stream, it answers with the file itself.
asset_api_url() {
[ -s "$1" ] || return 0
jsonfilter -i "$1" -e "@.assets[@.name='$2'].url" 2>/dev/null | head -n 1 |
sed -n 's#^\(https://api\.github\.com/repos/[^/]*/[^/]*/releases/assets/[0-9][0-9]*\)$#\1#p'
}
# download URL FILE LABEL [SHA256] [API_URL]: without curl the API's URL
# first (github.com's redirect carries a Content-Security-Policy header that
# can outgrow uclient-fetch's 4 KB line buffer, and it stalls there), then
# direct, then (only when the sha256 is known) two mirrors, then direct again.
# A file whose sha256 doesn't match is thrown away and the next source is
# tried; without a sha256 only GitHub itself is used.
download() {
_du="$1"
_dd="$2"
_dl="$3"
_dw="${4:-}"
_da="${5:-}"
[ "$FETCHER" != curl ] || _da=""
set -- "$_du"
[ -z "$_da" ] || set -- "$_da" "$_du"
if [ -n "$_dw" ]; then
for _m in $MIRRORS; do set -- "$@" "$_m$_du"; done
fi
@@ -519,7 +569,9 @@ download() {
sleep 2
msg "Downloading $_dl via $(host_of "$_try") (attempt $_n/$_total)"
fi
if fetch_once "$_try" "$_dd"; then
_acc=""
[ "$_try" != "$_da" ] || _acc="application/octet-stream"
if fetch_once "$_try" "$_dd" "" "$_acc"; then
if [ -n "$_dw" ] && [ "$(sha256sum "$_dd" 2>/dev/null | awk '{ print $1 }')" != "$_dw" ]; then
warn "$(host_of "$_try") sent a file that doesn't match GitHub's sha256: discarded"
rm -f "$_dd"
@@ -779,8 +831,11 @@ select_release() {
}
_tags="$(jsonfilter -i "$_rl" -e '@[@.draft=false && @.prerelease=false].tag_name' 2>/dev/null)"
[ -n "$_tags" ] || _tags="$(jsonfilter -i "$_rl" -e '@[*].tag_name' 2>/dev/null)"
# Newest first. BusyBox sort ignores -t/-k numeric keys here (falls back to
# an ascending string sort), so pad each part and reverse-sort as strings.
_tags="$(printf '%s\n' "$_tags" | sed 's/^v//' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' |
sort -t. -k1,1nr -k2,2nr -k3,3nr | uniq | head -n 10)"
awk -F. '{ printf "%06d%06d%06d %s\n", $1, $2, $3, $0 }' | sort -r | cut -d' ' -f2 |
uniq | head -n 10)"
_count=0
for _t in $_tags; do _count=$((_count + 1)); done
[ "$_count" -gt 1 ] || return 0
@@ -892,6 +947,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() {
@@ -978,6 +1095,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)" ;;
@@ -1008,28 +1130,38 @@ 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")"
# The checksum: GitHub's own (API), else the release's sha256sums.txt straight from GitHub.
_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 "" \
"$(asset_api_url "$TMP_DIR/release.json" 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" "$(asset_api_url "$TMP_DIR/release.json" "$_name")" || {
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() {
@@ -1043,7 +1175,8 @@ download_awg() {
_f="$TMP_DIR/$_p$_pf"
# Verified when GitHub publishes the file's sha256 (then mirrors may serve it).
_want="$(asset_digest "$TMP_DIR/awg-$_s.json" "$_p$_pf")"
if download "https://github.com/$_repo/releases/download/v$OWRT_RELEASE/$_p$_pf" "$_f" "$_p ($_repo)" "$_want" &&
if download "https://github.com/$_repo/releases/download/v$OWRT_RELEASE/$_p$_pf" "$_f" "$_p ($_repo)" "$_want" \
"$(asset_api_url "$TMP_DIR/awg-$_s.json" "$_p$_pf")" &&
verify_archive "$_f"; then
_files="$_files $_f"
else
@@ -1133,15 +1266,36 @@ install_awg() {
ok "AmneziaWG $(pkg_version amneziawg-tools) installed"
}
# netifd reads its protocol handlers only when it starts: a network that was
# up before AmneziaWG was installed doesn't know the amneziawg protocol, and no
# tunnel can come up. Restarted detached and last, so an SSH session dropping
# with it can't cut the install short.
awg_netifd_restart() {
[ "$AWG_ACTION" != skip ] && [ -x /lib/netifd/proto/amneziawg.sh ] || return 0
ubus call network get_proto_handlers 2>/dev/null | grep -q '"amneziawg"' && return 0
msg "Restarting the network so it knows AmneziaWG (connections drop for a few seconds)"
log_line "INFO network restart: netifd has no amneziawg protocol handler"
(
trap '' HUP
sleep 2
/etc/init.d/network restart
) </dev/null >/dev/null 2>&1 &
}
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"
# 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() {
@@ -1182,6 +1336,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"
}
@@ -1196,6 +1353,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
@@ -1309,6 +1475,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
@@ -1329,6 +1496,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))
@@ -1350,6 +1518,7 @@ main() {
msg "Open LuCI → Network → Dawnline:"
fi
msg " $(lan_url)"
awg_netifd_restart
}
main "$@"
+4 -1
View File
@@ -6,9 +6,12 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.4.2
PKG_VERSION:=0.16.2
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 Oa=Object.create;var Gn=Object.defineProperty;var ja=Object.getOwnPropertyDescriptor;var Ua=Object.getOwnPropertyNames;var Wa=Object.getPrototypeOf,Ga=Object.prototype.hasOwnProperty;var qa=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Fa=(n,t,o,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ua(t))!Ga.call(n,r)&&r!==o&&Gn(n,r,{get:()=>t[r],enumerable:!(a=ja(t,r))||a.enumerable});return n};var Ka=(n,t,o)=>(o=n!=null?Oa(Wa(n)):{},Fa(t||!n||!n.__esModule?Gn(o,"default",{value:n,enumerable:!0}):o,n));var eo=qa((Zn,Xn)=>{"use strict";var Qn=(function(){var n=function(w,I){var C=236,T=17,b=w,A=o[I],u=null,f=0,N=null,P=[],H={},J=function(M,E){f=b*4+17,u=(function(k){for(var z=new Array(k),y=0;y<k;y+=1){z[y]=new Array(k);for(var B=0;B<k;B+=1)z[y][B]=null}return z})(f),W(0,0),W(f-7,0),W(0,f-7),G(),$(),oe(M,E),b>=7&&q(M),N==null&&(N=me(b,A,P)),O(N,E)},W=function(M,E){for(var k=-1;k<=7;k+=1)if(!(M+k<=-1||f<=M+k))for(var z=-1;z<=7;z+=1)E+z<=-1||f<=E+z||(0<=k&&k<=6&&(z==0||z==6)||0<=z&&z<=6&&(k==0||k==6)||2<=k&&k<=4&&2<=z&&z<=4?u[M+k][E+z]=!0:u[M+k][E+z]=!1)},te=function(){for(var M=0,E=0,k=0;k<8;k+=1){J(!0,k);var z=r.getLostPoint(H);(k==0||M>z)&&(M=z,E=k)}return E},$=function(){for(var M=8;M<f-8;M+=1)u[M][6]==null&&(u[M][6]=M%2==0);for(var E=8;E<f-8;E+=1)u[6][E]==null&&(u[6][E]=E%2==0)},G=function(){for(var M=r.getPatternPosition(b),E=0;E<M.length;E+=1)for(var k=0;k<M.length;k+=1){var z=M[E],y=M[k];if(u[z][y]==null)for(var B=-2;B<=2;B+=1)for(var Y=-2;Y<=2;Y+=1)B==-2||B==2||Y==-2||Y==2||B==0&&Y==0?u[z+B][y+Y]=!0:u[z+B][y+Y]=!1}},q=function(M){for(var E=r.getBCHTypeNumber(b),k=0;k<18;k+=1){var z=!M&&(E>>k&1)==1;u[Math.floor(k/3)][k%3+f-8-3]=z}for(var k=0;k<18;k+=1){var z=!M&&(E>>k&1)==1;u[k%3+f-8-3][Math.floor(k/3)]=z}},oe=function(M,E){for(var k=A<<3|E,z=r.getBCHTypeInfo(k),y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<6?u[y][8]=B:y<8?u[y+1][8]=B:u[f-15+y][8]=B}for(var y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<8?u[8][f-y-1]=B:y<9?u[8][15-y-1+1]=B:u[8][15-y-1]=B}u[f-8][8]=!M},O=function(M,E){for(var k=-1,z=f-1,y=7,B=0,Y=r.getMaskFunction(E),V=f-1;V>0;V-=2)for(V==6&&(V-=1);;){for(var ce=0;ce<2;ce+=1)if(u[z][V-ce]==null){var be=!1;B<M.length&&(be=(M[B]>>>y&1)==1);var X=Y(z,V-ce);X&&(be=!be),u[z][V-ce]=be,y-=1,y==-1&&(B+=1,y=7)}if(z+=k,z<0||f<=z){z-=k,k=-k;break}}},F=function(M,E){for(var k=0,z=0,y=0,B=new Array(E.length),Y=new Array(E.length),V=0;V<E.length;V+=1){var ce=E[V].dataCount,be=E[V].totalCount-ce;z=Math.max(z,ce),y=Math.max(y,be),B[V]=new Array(ce);for(var X=0;X<B[V].length;X+=1)B[V][X]=255&M.getBuffer()[X+k];k+=ce;var Se=r.getErrorCorrectPolynomial(be),Ce=s(B[V],Se.getLength()-1),jn=Ce.mod(Se);Y[V]=new Array(Se.getLength()-1);for(var X=0;X<Y[V].length;X+=1){var Un=X+jn.getLength()-Y[V].length;Y[V][X]=Un>=0?jn.getAt(Un):0}}for(var Wn=0,X=0;X<E.length;X+=1)Wn+=E[X].totalCount;for(var gn=new Array(Wn),Nt=0,X=0;X<z;X+=1)for(var V=0;V<E.length;V+=1)X<B[V].length&&(gn[Nt]=B[V][X],Nt+=1);for(var X=0;X<y;X+=1)for(var V=0;V<E.length;V+=1)X<Y[V].length&&(gn[Nt]=Y[V][X],Nt+=1);return gn},me=function(M,E,k){for(var z=l.getRSBlocks(M,E),y=d(),B=0;B<k.length;B+=1){var Y=k[B];y.put(Y.getMode(),4),y.put(Y.getLength(),r.getLengthInBits(Y.getMode(),M)),Y.write(y)}for(var V=0,B=0;B<z.length;B+=1)V+=z[B].dataCount;if(y.getLengthInBits()>V*8)throw"code length overflow. ("+y.getLengthInBits()+">"+V*8+")";for(y.getLengthInBits()+4<=V*8&&y.put(0,4);y.getLengthInBits()%8!=0;)y.putBit(!1);for(;!(y.getLengthInBits()>=V*8||(y.put(C,8),y.getLengthInBits()>=V*8));)y.put(T,8);return F(y,z)};H.addData=function(M,E){E=E||"Byte";var k=null;switch(E){case"Numeric":k=p(M);break;case"Alphanumeric":k=c(M);break;case"Byte":k=m(M);break;case"Kanji":k=v(M);break;default:throw"mode:"+E}P.push(k),N=null},H.isDark=function(M,E){if(M<0||f<=M||E<0||f<=E)throw M+","+E;return u[M][E]},H.getModuleCount=function(){return f},H.make=function(){if(b<1){for(var M=1;M<40;M++){for(var E=l.getRSBlocks(M,A),k=d(),z=0;z<P.length;z++){var y=P[z];k.put(y.getMode(),4),k.put(y.getLength(),r.getLengthInBits(y.getMode(),M)),y.write(k)}for(var B=0,z=0;z<E.length;z++)B+=E[z].dataCount;if(k.getLengthInBits()<=B*8)break}b=M}J(!1,te())},H.createTableTag=function(M,E){M=M||2,E=typeof E>"u"?M*4:E;var k="";k+='<table style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: "+E+"px;",k+='">',k+="<tbody>";for(var z=0;z<H.getModuleCount();z+=1){k+="<tr>";for(var y=0;y<H.getModuleCount();y+=1)k+='<td style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: 0px;",k+=" width: "+M+"px;",k+=" height: "+M+"px;",k+=" background-color: ",k+=H.isDark(z,y)?"#000000":"#ffffff",k+=";",k+='"/>';k+="</tr>"}return k+="</tbody>",k+="</table>",k},H.createSvgTag=function(M,E,k,z){var y={};typeof arguments[0]=="object"&&(y=arguments[0],M=y.cellSize,E=y.margin,k=y.alt,z=y.title),M=M||2,E=typeof E>"u"?M*4:E,k=typeof k=="string"?{text:k}:k||{},k.text=k.text||null,k.id=kLine truncated
`}return k%2&&M>0?Ce.substring(0,Ce.length-k-1)+Array(k+1).join("▀"):Ce.substring(0,Ce.length-1)};return H.createASCII=function(M,E){if(M=M||1,M<2)return ge(E);M-=1,E=typeof E>"u"?M*2:E;var k=H.getModuleCount()*M+E*2,z=E,y=k-E,B,Y,V,ce,be=Array(M+1).join("██"),X=Array(M+1).join(" "),Se="",Ce="";for(B=0;B<k;B+=1){for(V=Math.floor((B-z)/M),Ce="",Y=0;Y<k;Y+=1)ce=1,z<=Y&&Y<y&&z<=B&&B<y&&H.isDark(V,Math.floor((Y-z)/M))&&(ce=0),Ce+=ce?be:X;for(V=0;V<M;V+=1)Se+=Ce+`
`}return Se.substring(0,Se.length-1)},H.renderTo2dContext=function(M,E){E=E||2;for(var k=H.getModuleCount(),z=0;z<k;z++)for(var y=0;y<k;y++)M.fillStyle=H.isDark(z,y)?"black":"white",M.fillRect(z*E,y*E,E,E)},H};n.stringToBytesFuncs={default:function(w){for(var I=[],C=0;C<w.length;C+=1){var T=w.charCodeAt(C);I.push(T&255)}return I}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(w,I){var C=(function(){for(var b=R(w),A=function(){var $=b.read();if($==-1)throw"eof";return $},u=0,f={};;){var N=b.read();if(N==-1)break;var P=A(),H=A(),J=A(),W=String.fromCharCode(N<<8|P),te=H<<8|J;f[W]=te,u+=1}if(u!=I)throw u+" != "+I;return f})(),T=63;return function(b){for(var A=[],u=0;u<b.length;u+=1){var f=b.charCodeAt(u);if(f<128)A.push(f);else{var N=C[b.charAt(u)];typeof N=="number"?(N&255)==N?A.push(N):(A.push(N>>>8),A.push(N&255)):A.push(T)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var w=[[],[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]],I=1335,C=7973,T=21522,b={},A=function(u){for(var f=0;u!=0;)f+=1,u>>>=1;return f};return b.getBCHTypeInfo=function(u){for(var f=u<<10;A(f)-A(I)>=0;)f^=I<<A(f)-A(I);return(u<<10|f)^T},b.getBCHTypeNumber=function(u){for(var f=u<<12;A(f)-A(C)>=0;)f^=C<<A(f)-A(C);return u<<12|f},b.getPatternPosition=function(u){return w[u-1]},b.getMaskFunction=function(u){switch(u){case a.PATTERN000:return function(f,N){return(f+N)%2==0};case a.PATTERN001:return function(f,N){return f%2==0};case a.PATTERN010:return function(f,N){return N%3==0};case a.PATTERN011:return function(f,N){return(f+N)%3==0};case a.PATTERN100:return function(f,N){return(Math.floor(f/2)+Math.floor(N/3))%2==0};case a.PATTERN101:return function(f,N){return f*N%2+f*N%3==0};case a.PATTERN110:return function(f,N){return(f*N%2+f*N%3)%2==0};case a.PATTERN111:return function(f,N){return(f*N%3+(f+N)%2)%2==0};default:throw"bad maskPattern:"+u}},b.getErrorCorrectPolynomial=function(u){for(var f=s([1],0),N=0;N<u;N+=1)f=f.multiply(s([1,i.gexp(N)],0));return f},b.getLengthInBits=function(u,f){if(1<=f&&f<10)switch(u){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+u}else if(f<27)switch(u){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+u}else if(f<41)switch(u){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+u}else throw"type:"+f},b.getLostPoint=function(u){for(var f=u.getModuleCount(),N=0,P=0;P<f;P+=1)for(var H=0;H<f;H+=1){for(var J=0,W=u.isDark(P,H),te=-1;te<=1;te+=1)if(!(P+te<0||f<=P+te))for(var $=-1;$<=1;$+=1)H+$<0||f<=H+$||te==0&&$==0||W==u.isDark(P+te,H+$)&&(J+=1);J>5&&(N+=3+J-5)}for(var P=0;P<f-1;P+=1)for(var H=0;H<f-1;H+=1){var G=0;u.isDark(P,H)&&(G+=1),u.isDark(P+1,H)&&(G+=1),u.isDark(P,H+1)&&(G+=1),u.isDark(P+1,H+1)&&(G+=1),(G==0||G==4)&&(N+=3)}for(var P=0;P<f;P+=1)for(var H=0;H<f-6;H+=1)u.isDark(P,H)&&!u.isDark(P,H+1)&&u.isDark(P,H+2)&&u.isDark(P,H+3)&&u.isDark(P,H+4)&&!u.isDark(P,H+5)&&u.isDark(P,H+6)&&(N+=40);for(var H=0;H<f;H+=1)for(var P=0;P<f-6;P+=1)u.isDark(P,H)&&!u.isDark(P+1,H)&&u.isDark(P+2,H)&&u.isDark(P+3,H)&&u.isDark(P+4,H)&&!u.isDark(P+5,H)&&u.isDark(P+6,H)&&(N+=40);for(var q=0,H=0;H<f;H+=1)for(var P=0;P<f;P+=1)u.isDark(P,H)&&(q+=1);var oe=Math.abs(100*q/f/f-50)/5;return N+=oe*10,N},b})(),i=(function(){for(var w=new Array(256),I=new Array(256),C=0;C<8;C+=1)w[C]=1<<C;for(var C=8;C<256;C+=1)w[C]=w[C-4]^w[C-5]^w[C-6]^w[C-8];for(var C=0;C<255;C+=1)I[w[C]]=C;var T={};return T.glog=function(b){if(b<1)throw"glog("+b+")";return I[b]},T.gexp=function(b){for(;b<0;)b+=255;for(;b>=256;)b-=255;return w[b]},T})();function s(w,I){if(typeof w.length>"u")throw w.length+"/"+I;var C=(function(){for(var b=0;b<w.length&&w[b]==0;)b+=1;for(var A=new Array(w.length-b+I),u=0;u<w.length-b;u+=1)A[u]=w[u+b];return A})(),T={};return T.getAt=function(b){return C[b]},T.getLength=function(){return C.length},T.multiply=function(b){for(var A=new Array(T.getLength()+b.getLength()-1),u=0;u<T.getLength();u+=1)for(var f=0;f<b.getLength();f+=1)A[u+f]^=i.gexp(i.glog(T.getAt(u))+i.glog(b.getAt(f)));return s(A,0)},T.mod=function(b){if(T.ge Line truncated
`)}function rr(n){let t=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:t,devices:o}}function je(n,t,o,a="",r=[]){let i=rr(n),s=[...t.map(c=>({ts:c.ts,category:$t(c.type),type:c.type,person:c.person?i.people.get(c.person)??c.pname??c.person:"",device:c.device?i.devices.get(c.device)??c.dname??c.device:"",detail:c.detail??"",where:c.where??"",by:Le(c)??""})),...r.map(c=>({ts:c.ts,category:"system",type:`${c.src}.${c.level}`,person:"",device:"",detail:`${c.who?`${c.who} `:""}${c.msg}${c.detail?`
${c.detail}`:""}`,where:_t[c.src]??c.src,by:""}))].sort((c,m)=>c.ts-m.ts).map(({ts:c,...m})=>({time:new Date(c*1e3).toISOString(),...m})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){$e(d,JSON.stringify(s,null,2),"application/json");return}$e(d,ro(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var ir=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],io=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function Fe(n,t,o,a,r,i=!1){let s=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...pt.map(d=>e("option",{value:d,selected:d===r?"selected":null},nt[d])),i?e("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=e("select",{class:"cbi-input-select"},ir.map(([d,p])=>e("option",{value:d},p)));ae(n,[e("p",{class:"dl-muted"},`${t} This cannot be undone; export first if you want a copy.`),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Category"),s]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),l])],[se()," ",D("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await S.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(p){Q(ve(p),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await S.serviceLogClear(l.value)).removed}catch(p){le(),Q(`${s.value==="system"?"":`Activity: ${io(d).toLowerCase()}. `}The service log was not cleared: ${ve(p)}`,"error",1e4),a();return}le(),Q(io(d),"success",3e3),a()},"negative")])}function ut(n,t,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'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.";ae(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[e("p",{class:"dl-muted"},r)],[se()," ",D("Reset",async()=>{await U(()=>S.usageClear(n,t),"Traffic history reset")&&(le(),a())},"negative")])}function fe(n,t,o){let a=e("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":t,click:()=>{let r=!a.classList.contains("on");Sn(a,r),o?.(r)}},e("i"));return a}function Sn(n,t){n.classList.toggle("on",t),n.setAttribute("aria-checked",t?"true":"false")}var Ee=n=>n.classList.contains("on");function xe(n,t,o={}){n.some(([i])=>i===t)||(n=[...n,[t,t]]);let a=e("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":t}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(e("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function Ue(n,t,o,a={}){return e("button",{type:"button",...a,class:`dl-chipbtn${t?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":t?"true":"false",click:o},n)}function Wt(n,t){n.classList.toggle("on",t),n.setAttribute("aria-pressed",t?"true":"false")}function re(n,t={}){return e("input",{type:"text",class:"cbi-input-text",value:n,...t})}var sr={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:""},lr={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 dr(n){let t={};for(let[o,a]of Object.entries(lr))n[o]!=null&&n[o]!==""&&(t[a]=String(n[o]));return t}function cr(n,t){let o=n.amnezia,a=o.obfuscation??{},r=d=>a[d]!=null&&a[d]!==""?String(a[d]):sr[d],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...dr(a),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function pr(n){let t="";for(let o=0;o<n.length;o+=32768)t+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ur(n){let t=globalThis;if(typeof t.CompressionStream>"u")return null;try{let o=new t.Blob([n]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function Cn(n,t,o=!0){let a=new TextEncoder().encode(JSON.stringify(cr(n,t))),r=o?await ur(a):null;return`vpn://${pr(r??a)}`}var lo=[{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:"standard",title:"Standard",ic:"shield",stealth:2,speed:4,text:"Junk packets and random headers. Gets through most VPN blocking with no speed cost.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"strong",title:"Strong",ic:"shieldplus",stealth:3,speed:3,text:"More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{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"}],Et=n=>lo.find(t=>t.id===n),mr={v2:"Needs AmneziaWG 1.5 or newer on the router.",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},hr={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function so(n,t){return e("span",{class:"dl-dots",title:`${t}: ${n} of 4`},[e("span",{class:"dl-dots-label"},t),e("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>e("i",{class:o<n?"on":""})))])}function Gt(n,t,o,a,r=!0){let i=e("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,lo.map(l=>{let d=!l.needs||n[l.needs],p=l.id===t;return e("button",{type:"button",role:"radio","aria-checked":p?"true":"false","aria-disabled":d?null:"true",class:`dl-method${p?" on":""}${d?"":" off"}`,click:()=>{!d||p||(t=l.id,s(),o(l.id))}},[e("div",{class:"dl-method-head"},[e("span",{class:"dl-method-ic"},g(l.ic)),e("b",{},l.title),l.id===a?e("span",{class:"dl-pill ok"},"Current"):""]),e("p",{},l.text),e("div",{class:"dl-method-meters"},[so(l.stealth,"Stealth"),so(l.speed,"Speed")]),e("div",{class:"dl-method-foot"},d?[g("phone"),e("span",{},l.apps)]:[g("alert"),e("span",{},(r?mr:hr)[l.needs])])])}));return s(),i}function co(n,t,o,a){return e("div",{class:"dl-corehead"},[e("h3",{},n),e("span",{class:`dl-pill ${t}`},o),a?e("span",{class:"dl-sub"},a):""])}var po=[["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 fr(n){let t=p=>n[p]!=null&&n[p]!=="",o=po.filter(([p])=>t(p));if(!o.length)return null;let a=(p,c)=>e("span",{class:"dl-pv"},[e("i",{},c),e("b",{},p==="header_protection_key"?`${n[p].slice(0,6)}••••`:n[p])]),r=(p,c,m,v)=>{let h=po.filter(([x])=>v.includes(x)&&t(x));return h.length?e("div",{class:"dl-pgroup"},[e("div",{class:"dl-pgroup-head"},[g(c),e("b",{},p)]),e("p",{},m),e("div",{class:"dl-pvals"},h.map(([x,R])=>a(x,R)))]):""},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=o.map(([p,c])=>`${c} = ${n[p]}`).join(`
`),d=e("div",{class:"dl-pgrid"},[r("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"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("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"]),r("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(o.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:p=>{p.preventDefault(),pe(l,"Parameters copied")}},"Copy as config")]),d])}function uo(n,t){if(/^\s*\[.+\]\s*$/.test(n))return e("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return e("span",{},[e("span",{class:"dl-conf-k"},o[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function gr(n){let t=!1,o=e("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(`
`).flatMap((s,l)=>l?[`
`,uo(s,t)]:[uo(s,t)])),r=e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),t=!t,dom.content(r,[g(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[g("key"),"Show key"]);a();let i=new Blob([n.conf]).size;return e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-filecard"},[e("span",{class:"dl-filecard-ic"},".conf"),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono dl-ellipsis"},n.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([g("download")," Download"],()=>$e(n.filename,n.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),r,e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),pe(n.conf,"Configuration copied")}},[g("copy"),"Copy"])]),o])])}async function vr(n,t="file"){if(!n.has_private_key)return e("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await Cn(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>e("div",{class:"dl-qr-pane"},[qe(ct(n.conf),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-linkbox"},[e("span",{class:"dl-mono"},o),D("Copy",()=>pe(o,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>gr(n)},r=e("div",{class:"dl-connect-body"}),i=e("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,a[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(e("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(t),e("div",{class:"dl-stack gap12"},[i,r])}async function br(n,t,o,a){let r=Et(o),s=n.st.people.filter(d=>d.server===t.id).reduce((d,p)=>d+p.devices.length,0);await ne(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await U(()=>S.serverObfuscation(t.id,o),a?"New values applied":`${r.title} applied`)&&(Q("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function xr(n,t){let o=n.st,a=re(String(t.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=re(String(t.mtu??""),{placeholder:"1380",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=re(String(t.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=Et(t.preset)?t.preset:void 0,l=s??"standard",d=D("",()=>br(n,t,l,l===s),"neutral"),p=()=>dom.content(d,l===s?[g("reset")," Generate new values"]:[`Switch to ${Et(l).title}`]);p();let c=o.people.filter(v=>v.server===t.id).reduce((v,h)=>v+h.devices.length,0),m=o.awg_state?.tools!==!1;return kt("",[co("AmneziaWG",t.up?"ok":"bad",t.up?"Running":"Not running",`${t.ifname} · ${c} device${c===1?"":"s"}`),he("globe","Listening","Where devices reach this core from the internet",[Z("UDP port",a,"Opened on the WAN firewall automatically.")]),he("file","In every device configuration","Changing these marks devices “Update config” until they import again",[Z("MTU",r,"Lower it if some sites hang on mobile networks."),Z("Keep-alive",i,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Gt(o.awg,l,v=>{l=v,p()},s,m),m&&!o.awg.v3?dt("info",["This router runs an older AmneziaWG. ",e("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",fr(t.obf??{})??"",e("div",{class:"dl-row-end"},[e("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Tunnel"),e("span",{class:"dl-pcount"},"3")]),e("div",{class:"dl-params-body"},[Z("Interface",e("span",{class:"dl-mono"},`${t.ifname} · router ${t.address}`)),Z("Tunnel subnet",e("span",{class:"dl-mono"},t.subnet),"Device addresses come from it."),Z("Server public key",e("span",{class:"dl-keyrow"},[e("code",{class:"dl-mono"},t.public_key),D([g("copy")],()=>pe(t.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[e("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:i.value},"AmneziaWG saved"),"positive")])}function wr(n){let t=Et(n.preset),o=n.obf??{},a=(s,l)=>e("span",{class:`dl-segs ${l}`},[0,1,2,3].map(d=>e("i",{class:d<s?"on":""}))),r=[];+o.jc&&r.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);let i=["s1","s2","s3","s4"].filte Line truncated
`),"Log copied"))]),c,m]),[v],"wide"),x([e("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let _=o??null,j=o?.id,w,I=0,C=u=>{j!==u.id&&(j=u.id,t.onJob?.(u))};if(o)t.onJob?.(o);else try{let u=await S.updatesStatus().catch(()=>null);w=u?.job?.id,I=u?.now??0;let f=await S.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==w&&(_=f.job,C(f.job))}catch(u){return h=[ve(u)],c.textContent=h[0],dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},ve(u))])),x([R(!0)]),Q(ve(u),"error"),null}let T=null,b=0;for(;;){if(await Mo(1e3),T=await S.updatesStatus().catch(()=>null),!T){if(++b>60)break;continue}b=0;let u=T.job;if(!u||!To(u,j,w,I)){if(Date.now()-i>15e3)break;continue}if(C(u),_=u,u.log.length){h=u.log;let f=c.scrollTop+c.clientHeight>=c.scrollHeight-8;c.textContent=h.join(`
`),f&&(c.scrollTop=c.scrollHeight)}if(l.textContent=Co(u,t.version??""),!l.isConnected&&l.textContent&&s.after(l),p.textContent=So((u.finished??T.now)-u.started),u.state==="running"){d.hidden=!u.phase,d.textContent=u.phase;continue}break}if(c.scrollTop=c.scrollHeight,d.hidden=!1,!_||_.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),x([R()]),t.onDone?.(T),_;if(_.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(m,e("div",{class:"dl-comp-status bad"},[g("x"),e("span",{},[e("b",{},_.error??"Operation failed"),r?"":". Nothing else was changed."])])),x([D("Copy log",()=>pe(h.join(`
`),"Log copied")),R(!0)]),Q(`${Qt[a]??"Update"}: ${_.error??"failed"}`,"error"),t.onDone?.(T),_;if(d.className="dl-pill ok",d.textContent="Finished",r&&T){let u=Lo(T,a);if(dom.content(m,e("div",{class:`dl-comp-status ${u.tone}`},[g(u.tone==="ok"?"check":u.tone==="warn"?"alert":"download"),e("span",{},u.text)])),Q(u.text,u.tone==="warn"?"warning":"success"),t.onDone?.(T),u.update&&t.onUpdate){let f=T;x([R(),D(`Update to ${u.update}`,()=>t.onUpdate(f),"positive")])}else x([R()]),u.tone==="ok"&&setTimeout(()=>m.isConnected&&le(),1200);return _}if(a==="app"&&_.to){let u=_.to,f=e("span",{},"Waiting for the router to restart its services…");dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},[e("b",{},`Dawnline ${u} is installed. `),f])]));let N=()=>{ui.menu?.flushCache(),location.reload()};x([R(),D("Reload now",N,"positive")]),Q(`Dawnline updated to ${u}`,"success",6e3);for(let P=1;P<=30;P++)if(f.textContent=`Waiting for the router to restart its services (${P} of 30)…`,await Mo(1500),(await S.updatesStatus().catch(()=>null))?.version===u)return f.textContent="Services are back. Reloading…",setTimeout(N,800),_;return f.textContent="Services restarted. Reload the page to use the new version.",_}let A=a==="pkgs"?`Updated ${[..._.result?.pkgs?.updated??[],..._.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${_.to?` ${_.to}`:""} is installed`:"Operation completed";return dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},A)])),x([R()]),Q(A,"success"),t.onDone?.(T),_}var Rr={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function Po(n,t,o,a){return!await ne(`Install ${t}?`,o,"Install")||(await Mt(n,{title:`Installing ${t}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function Xt(n){return Po("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 Pt(n,t,o){return n==="awg"?Xt(o):t.length?Po(`pkgs:${t.join(",")}`,Rr[n],`${t.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function Do(n,t){if(n==="awg")return Xt(t);let o=await U(()=>S.updatesStatus());return o?Pt(n,o.needs?.[n]??[],t):!1}var Hr=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Ir={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Ao(n,t,o){let a=n.id,r=t,i=e("div",{class:"dl-stack gap16"},e("section",{class:"dl-setsec"},e("div",{class:"dl-setsec-body"},e("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",p=!0,c=!0,m="all",v=!1,h=$o(r,a,o),x=new Set,R="",_=()=>JSON.stringify([c,l,l?"":d,p,[...x].sort()]),j=()=>s.detected.lan||s.saved.lan||"",w=()=>(l?s.detected.wan||s.saved.wan:d)||"",I=()=>new Map(s.devices.map($=>[$.name,$])),C=()=>{let $=I();return[...p&&j()?[j()]:[],...[...x].filter(q=>q!==j())].filter(q=>q!==w()).map(q=>$.get(q)??{name:q,nets:[],missing:!0})},T=($,G)=>{s=$,G&&(l=$.config.auto_wan,d=$.config.wan_device||$.detected.wan||$.saved.wan||"",p=$.config.auto_lan,c=$.config.lan_like,m=$.config.mesh??($.config.device_mesh?"all":"off"),x=new Set($.config.lan_devices),R=_()),W()},b=async $=>{let G=await S.interfaces(a).catch(q=>(Q(q.message,"error"),null));G&&T(G,$)};function A($){let G=p&&$.name===j(),q=!!$.own||!!$.master||$.name===w()||G;return G||x.has($.name)||!q&&($.nets.length>0||!!$.missing)}function u($){let G=p&&$.name===j(),q=$.name===w(),oe=!G&&x.has($.name),F=!(!!$.own||!!$.master||q||G)&&($.nets.length>0||oe||!!$.missing),me=(oe||G)&&!$.zone&&!$.missing,ie=$.missing?"Not present right now":$.own?"This server":$.master?`Port of ${$.master}`:q?`Internet${$.zone?` · zone ${$.zone}`:""}`:$.nets.length?$.nets.join(", "):"No IPv4 network",ge=e("button",{type:"button",class:`dl-if${oe?" sel":""}${G?" auto":""}${!F&&!oe&&!G?" off":""}${me?" warn":""}`,"aria-pressed":oe||G?"true":"false","aria-disabled":F?null:"true",click:()=>{F&&(x.has($.name)?x.delete($.name):x.add($.name),W())}},[e("span",{class:"dl-if-ic"},g(Ir[$.kind]??"link")),e("span",{class:"dl-if-main"},[e("span",{class:"dl-if-name"},$.name),e("span",{class:"dl-if-sub"},ie)]),G?e("span",{class:"dl-if-badge ok"},"Auto"):oe?e("span",{class:"dl-if-check"},g("check")):""]);return ue(ge,()=>[e("div",{class:"dl-tip-title"},$.name),e("div",{class:"dl-muted"},[$.logical?`Interface ${$.logical}`:"No netifd interface",$.zone?` · zone ${$.zone}`:" · no firewall zone"]),$.members.length?e("div",{class:"dl-muted"},`Ports: ${$.members.join(", ")}`):"",$.nets.length?e("div",{class:"dl-mono"},$.nets.join(", ")):"",me?e("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",$.master?e("div",{class:"dl-muted"},`Choose ${$.master} to include it.`):""]),ge}function f(){let $=s.like_home;return!c||!s.config.lan Line truncated
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(t.push(e("pre",{},i.join(`
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let p=/^(#{1,6})\s+(.*)$/.exec(d),c=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);p?(s(),t.push(e("h5",{},o(p[2])))):c?(r.length&&s(),a||(a=e("ul",{}),t.push(a)),a.appendChild(e("li",{},o(c[1])))):d.trim()?(a&&(a=null),r.push(d.trim())):s()}return i&&t.push(e("pre",{},i.join(`
`))),s(),t}function Zo(n){let t=[],o=!1;for(let a of n.replace(/\r/g,"").split(`
`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||t.push(a)}return t.join(`
`).replace(/\n{3,}/g,`
`).trim()}async function zt(n,t,o,a){let r=e("div",{class:"dl-notes"},e("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=e("div",{class:"dl-op-head"}),s="";ae(o,[i,r],[D([g("copy")," Copy"],()=>pe(s,"Release notes copied"))," ",se("Close")],"wide");try{let l=await S.updatesNotes(n,t,a??"");s=Zo(l.body||"");let d=Yo(l.url);dom.content(i,[l.published?e("span",{class:"dl-pill"},Ae(l.published)):"",l.prerelease?e("span",{class:"dl-pill warn"},"Pre-release"):"",e("span",{class:"dl-spacer"}),d?e("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",g("open")]):""]),dom.content(r,s.trim()?Qo(s):e("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,e("p",{class:"dl-muted"},ve(l)))}}var Xo={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Hn=n=>n?Ae(n):"";function ri(n){let t=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return t||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function ta(n,t){let o=n.st,a=o.policy,r=o.kept?.app,i=t?.update&&t.tag?t.tag:o.version,s=v=>()=>zt("app",v,`What’s new in Dawnline ${v.replace(/^v/,"")}`),l=t?.tag&&(t.update||t.status==="latest")?ii(n,t.tag,t.update?o.version:""):null,d=t?.tag??i,p=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,c=(v,h)=>e("div",{class:"dl-stack gap4"},[e("span",{class:"dl-metric-label"},v),e("span",{class:"dl-comp-side-v"},h)]),m=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return e("section",{class:"dl-panel flush dl-comp-hero"},[e("div",{class:"dl-comp-hero-main"},[e("div",{class:"dl-comp-hero-head"},[e("span",{class:"dl-group-ic"},g("sunrise")),e("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",t,t?.latest??""),e("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),m,!0)]),e("div",{class:"dl-comp-verrow"},[e("div",{class:"dl-stack"},[e("div",{class:"dl-comp-big"},[o.version,t?.update?e("small",{},`→ ${t.latest}`):t?.status==="dev"&&t.latest?e("small",{class:"dl-faint"},`release ${t.latest}`):""]),e("span",{class:"dl-faint dl-comp-meta"},t?.error?"":t?.update?t.published?`released ${Hn(t.published)}`:"":t?.status==="dev"?"ahead of the latest release":t?`latest release${t.published?` · released ${Hn(t.published)}`:""}`:"not checked yet")])]),l?.items.length?e("div",{class:"dl-stack gap4"},[e("ul",{class:"dl-comp-bullets"},l.items.map(v=>e("li",{},v))),l.total>l.items.length?e("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",t?.error?e("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},t.error):"",t?.update?e("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",si(n)]),e("div",{class:"dl-comp-hero-side"},[c("Source",[g("globe"),e("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),c("Auto-update",[a.auto?ke("ok","On"):ke("","Off"),e("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${Xo[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${Xo[a.interval]}`:"checks off")]),c("Last check",o.check?[de(o.check.time,o.now),p>o.now?e("span",{class:"dl-faint"},`· next in ${st(p-o.now)}`):""]:["Never"]),c("Rollback",r?[e("span",{class:"dl-mono"},r.version),e("span",{class:"dl-faint"},"kept on flash")]:[e("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function ii(n,t,o){if(n.notes.has(t))return n.notes.get(t)??null;n.notes.set(t,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await S.updatesNotes("app",t,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await S.updatesChanges(o,t).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>ri(a(l))),total:i.length};n.notes.set(t,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function si(n){let t=e("div",{class:"dl-params-body"}),o=e("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[e("summary",{},[g("chevron"),e("span",{},"Versions"),e("span",{class:"dl-sub"},"install any release")]),t]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&dn(n,t)}),n.versOpen&&dn(n,t),o}async function dn(n,t){let o=re("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=c=>{if(c=c.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(c))return Q("Enter a release tag like 0.3.1","warning");ea(n,c)};o.addEventListener("keydown",c=>{c.key==="Enter"&&(c.preventDefault(),a(o.value))});let r=e("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=c=>{n.versPage=Math.max(1,n.versPage+c),dn(n,t)},l=c=>e("div",{class:"dl-comp-pager"},[e("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),e("span",{class:"dl-faint"},`Page ${i}`),e("button",{type:"button",class:"dl-linkbtn",disabled:c?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(t,[r,e("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await S.updatesReleases(i)).releases}catch(c){if(i!==n.versPage||!t.isConnected)return;dom.content(t,[r,e("div",{class:"dl-row-actions"},[e("span",{class:"dl-muted"},`Failed to load versions: ${ve(c)}`),D("Try again",()=>dn(n,t))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!t.isConnected)return}if(!d.length)return dom.content(t,[r,e("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let p=n.st.version;dom.content(t,[r,...d.map(c=>{let m=c.tag.replace(/^v/,"");return e("div",{class:"dl-comp-ver"},[e("span",{class:"dl-mono"},m),e("span",{class:"dl-sub"},Hn(c.published)),c.prerelease?ke("warn","Pre-release"):"",e("span",{class:"dl-comp-ic"},ye("file","What’s new",()=>zt("app",c.tag,`What’s new in Dawnline ${m}`))),m===p?ke("ok","Installed"):D("Install",()=>ea(n,c.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function ea(n,t){let o=t.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await ne(`Install Dawnline ${o}?`,`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@${t}`,`Installing Dawnline ${o}`,n.st.version)}function na(n,t){let o=n.st,a=o.kept?.amneziawg,r=t?.sources??{},i=Object.keys(r),s=t?.current??null,l=s?r[s]:void 0,d=!!t?.ru,p=o.needs?.awg??[],c=p.length?null:t?.installed??null,m=[];s&&c&&m.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",c)}),a&&m.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back AmneziaWG to ${a.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",c??void 0)}});let v=[t?.release?{label:"What’s new",ic:"file",run:()=>zt("amneziawg",t.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")},...m.length?[null,...m]:[]].filter((u,f,N)=>u!==null||f>0&&N[f-1]!==null),h=o.tunnels??[],x=h.length?`Switching restarts ${h.length===1?"the tunnel":`${h.length} tunnels`} for a few seconds: ${h.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",R=h.length>1?`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`:h[0],_=h.length?`Switching restarts ${R} for a few seconds.`:"Switching takes a few seconds.",j=async u=>{let f=r[u];await ne(c?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${x}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,c?"Switch":"Install")&&n.op(`amneziawg:${u}${d?":ru":""}`,c?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",c??void 0)},w=u=>{let f=r[u],N=s===u&&!!c;return e("div",{class:"dl-row"},[e("span",{class:"dl-row-main dl-stack"},[e("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),e("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),e("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),e("span",{class:"dl-comp-bact"},N?ke("ok","Active"):f.version?D(c?"Switch":"Install",()=>j(u),c?"neutral":"positive",{disabled:n.busy}):ke("","No build"))])},I=i.map(u=>r[u]?.newer?`${r[u].label} moves to ${r[u].newer.gen} with OpenWrt ${r[u].newer.tag.replace( Line truncated
`)}r.push(c),l+=p-1}let s=D([g("more")],()=>we(s,[{label:"Export CSV",icon:g("download"),run:()=>je(o,a,"csv",t.id)},{label:"Export JSON",icon:g("download"),run:()=>je(o,a,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:g("trash"),danger:!0,run:()=>Fe(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),e("span",{class:"dl-spacer"}),s]),r.length?r:e("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var pn=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(t){let[o,a,r]=await Promise.all([S.status(30),t?S.events(5e3).catch(()=>null):Promise.resolve(null),t?S.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(t){this.take(t);let o=this.st.people.find(s=>s.id===this.id);if(!o)return e("div",{class:"dl-empty"},[e("h3",{},"Person not found"),e("p",{},"They may have been removed."),e("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=e("div",{});this.parts.devices.className="dl-person-devices";let a=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:ht(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:ht(o.server)},"People"),e("span",{},"/"),e("span",{},o.name)]),this.parts.head,e("div",{class:"dl-grid-person"},[e("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),e("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>He(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>ot(this.p,this.deviceOpts()),50),this.poller=Ke({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>a.isConnected,apply:(s,l)=>this.apply(s,l)}),a}take(t){this.st=t.st,t.ev&&(this.events=t.ev),t.use&&(this.series=t.use.person,this.devSeries=t.use.devices)}apply(t,o){this.take(t);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=ht(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(t,o){var i;this.poller?.claim();let a=await U(()=>S.personUpdate(this.p.id,t),o);if(!a)return;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint()}get today(){return Ne(this.series.length?this.series:this.st.series)}get core(){return mt(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}}paint(t=!1){_e(this.parts.head,pa(this),t),_e(this.parts.traffic,ua(this),t),_e(this.parts.devices,ma(this),t),_e(this.parts.limits,wa(this),t),this.paintPlaces(t),_e(this.parts.activity,ka(this),t)}paintPlaces(t=!1){let o=ya(this);o&&_e(this.parts.places,o,t&&!this.mapOpen)}};var bi={ok:"check",warn:"alert",error:"x",skip:"pause"},un=class{constructor(t,o,a,r){this.el=e("div",{});this.wdEl=e("div",{});this.checksEl=e("div",{class:"dl-panel"});this.recentEl=e("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=e("div",{});this.open=new Set;this.st=t,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,e("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(t){let o=t?await rn(t):await S.health().catch(()=>null);o&&(this.take(o),t==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(t){this.checks=t.checks,this.paintChecks(),this.paintLive(t,this.events)}paintChecks(){let t=this.checks;if(!t){dom.content(this.summary,""),dom.content(this.checksEl,[e("div",{class:"dl-panel-head"},[e("h3",{},"Checks")]),e("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=t.filter(s=>s.status==="error").length,a=t.filter(s=>s.status==="warn").length;dom.content(this.summary,o?dt("error",`${o} problem${o>1?"s":""} need attention.`):a?dt("warn",`${a} warning${a>1?"s":""}.`):dt("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog.repairs)r.set(s.id Line truncated
`);function Ia(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=Ri,n}function rt(n){return()=>{let t=new n;return Object.assign({load:()=>t.load(),render:async a=>{let r=await t.render(a),i=document.createElement("div");return i.className="dl-root",i.append(Ia(),r),i},addFooter(){return t.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Uf=rt(At),Wf=rt(at),Gf=rt(At),qf=rt(ln),Ff=rt(pn),Kf=rt(fn),Jf=rt(cn);function Ba(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 Vf=Ba(""),Yf=Ba("log");return baseclass.extend({ activity: Yf, diagnostics: Kf, health: Vf, overview: Uf, people: Wf, person: Ff, server: Gf, settings: qf, updates: Jf });
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -5,5 +5,7 @@ case "$ACTION" in ifup|ifdown|ifup-failed) ;; *) exit 0 ;; esac
[ -n "$(uci -q get "network.$INTERFACE._dawnline")" ] || exit 0
# In order (a quick down/up must not log up first).
/usr/bin/dawnline iface-event "$ACTION" "$INTERFACE" >/dev/null 2>&1
[ "$ACTION" = ifup ] && /usr/bin/dawnline sync >/dev/null 2>&1 &
# A disabled Dawnline leaves the tunnels empty: nothing would enforce end
# dates, limits or hours once the devices were loaded.
[ "$ACTION" = ifup ] && /etc/init.d/dawnline enabled && /usr/bin/dawnline sync >/dev/null 2>&1 &
exit 0
@@ -21,9 +21,15 @@ start_portal() {
hport="$(/usr/bin/dawnline portal-http-port 2>/dev/null)"
[ -n "$hport" ] && http="-p 0.0.0.0:$hport -p [::]:$hport"
# Portal processes at once: each loads the whole model (a burst of 16 could
# empty a 128 MB router), so four, and two on a router with little memory;
# the rest of 64 connections wait their turn.
local procs=4 mem
mem="$(awk '/^MemTotal:/ { print int($2 / 1024) }' /proc/meminfo 2>/dev/null)"
[ -n "$mem" ] && [ "$mem" -le 160 ] && procs=2
procd_open_instance portal
procd_set_param command /usr/sbin/uhttpd -f -h "$PORTAL_ROOT" -x /cgi-bin -E /cgi-bin/portal \
-D -n 16 -N 64 -t 20 -T 30 -k 10 -A 1 \
-D -n "$procs" -N 64 -t 20 -T 30 -k 10 -A 1 \
-s "0.0.0.0:$port" -s "[::]:$port" -C "$cert" -K "$key" $http
procd_set_param file "$cert"
procd_set_param respawn 3600 5 0
@@ -36,7 +42,8 @@ start_resolver() {
procd_open_instance dns
procd_set_param command /usr/libexec/dawnline/resolver
procd_set_param file /var/etc/dawnline-dns.conf
procd_set_param respawn 3600 5 0
# A new config kills it (dawnline.resolver): back within a second, not five.
procd_set_param respawn 3600 1 0
procd_close_instance
}
@@ -59,6 +66,8 @@ start_service() {
stop_service() {
mkdir -p /var/run/dawnline
date +%s > /var/run/dawnline/agent.stopped
# Copies procd doesn't know about (started by hand, or left by an older version) go too.
pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent' | xargs -r kill 2>/dev/null
}
reload_service() {
@@ -68,4 +77,8 @@ reload_service() {
service_triggers() {
procd_add_reload_trigger dawnline
# The portal's uhttpd reads its certificate once: an issued or renewed one needs a
# reload (procd restarts the portal alone, its cert file having changed).
procd_add_raw_trigger acme.issue 5000 /etc/init.d/dawnline reload
procd_add_raw_trigger acme.renew 5000 /etc/init.d/dawnline reload
}
@@ -1,6 +1,13 @@
#!/bin/sh
# Dawnline first-run / upgrade housekeeping.
# Locations are off by default since 0.5.2 (lookups send addresses to a third
# party); a router that had them on by the old default keeps them on.
if [ -f /etc/config/dawnline ] && [ -z "$(uci -q get dawnline.settings.geo_enabled)" ]; then
uci -q set dawnline.settings.geo_enabled=1
uci -q commit dawnline
fi
[ -f /etc/config/dawnline ] || cat > /etc/config/dawnline <<'CFG'
config settings 'settings'
option portal_enabled '0'
@@ -17,6 +24,13 @@ uci -q commit dawnline
rm -f /etc/dawnline/alerts.json
# Backups moved into Settings.
rm -f /www/luci-static/resources/view/dawnline/backups.js
# "Pause everyone" is gone: turning a server off does the same, so a
# router left paused keeps its servers off instead of letting everyone in.
if [ "$(uci -q get dawnline.settings.paused_all)" = 1 ]; then
for s in $(uci -q show dawnline | sed -n 's/^dawnline\.\([^.=]*\)=server$/\1/p'); do uci -q set "dawnline.$s.enabled=0"; done
fi
uci -q delete dawnline.settings.paused_all
uci -q commit dawnline
# Portal assets moved out of the web root (served only with a valid code).
rm -rf /usr/share/dawnline/portal/www/assets
@@ -43,6 +57,12 @@ grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root || {
# A reload keeps LuCI logins but sometimes misses the plugin; restart only then.
sleep 2
ubus list luci.dawnline >/dev/null 2>&1 || { /etc/init.d/rpcd restart; sleep 2; }
# A fresh install starts the service; an upgrade restarts it only where the
# admin had it on (a disabled Dawnline stays that way).
if [ "$PKG_UPGRADE" = 1 ]; then
/etc/init.d/dawnline enabled && /etc/init.d/dawnline restart
else
/etc/init.d/dawnline enable
/etc/init.d/dawnline restart
fi
exit 0
+171 -35
View File
@@ -12,11 +12,32 @@ import * as pc from 'dawnline.portalcert';
import * as watchdog from 'dawnline.watchdog';
import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store';
import * as devices from 'dawnline.devices';
import { L_ } from 'dawnline.i18n';
import {
VERSION, slog, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
VERSION, slog, slog_read, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
} from 'dawnline.util';
const args = ARGV;
/** Options that take no value. */
const FLAGS = [ 'json', 'yes', 'conf' ];
// Options (--name value, or a bare --flag) can go anywhere; what is left are the words.
const opts = {};
const args = [];
for (let i = 0; i < length(ARGV); i++) {
let a = ARGV[i];
if (a == '-n')
a = '--n';
if (substr(a, 0, 2) == '--') {
let name = substr(a, 2);
if (index(FLAGS, name) >= 0)
opts[name] = true;
else
opts[name] = ARGV[++i] ?? '';
}
else
push(args, a);
}
const cmd = args[0] ?? 'help';
function out(v) {
@@ -24,10 +45,41 @@ function out(v) {
}
function opt(name, dflt) {
for (let i = 1; i < length(args); i++)
if (args[i] == `--${name}`)
return args[i + 1];
return dflt;
return opts[name] ?? dflt;
}
/** Fixed-width columns: a header, then one line per row. */
function table(cols, rows) {
let w = map(cols, (c) => length(c));
for (let r in rows)
for (let i, v in r)
w[i] = max(w[i], length(`${v}`));
let line = (r) => rtrim(join(' ', map(r, (v, i) => sprintf(`%-${w[i]}s`, `${v}`))));
out(line(cols));
for (let r in rows)
out(line(r));
}
/** `--since 30m|2h|3d|YYYY-MM-DD` as a time, or null. */
function since_time(s) {
if (!s)
return null;
let m = match(s, /^([0-9]+)([mhd])$/);
if (m)
return time() - +m[1] * { m: 60, h: 3600, d: 86400 }[m[2]];
m = match(s, /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/);
if (m)
return timelocal({ year: +m[1], mon: +m[2], mday: +m[3], hour: 0, min: 0, sec: 0 });
die('--since takes 30m, 2h, 3d or a date like 2026-10-18.');
}
/** "5m", "3h", "2d": how long ago, for the lists. */
function ago(secs) {
return secs < 3600 ? `${int(secs / 60)}m` : secs < 86400 ? `${int(secs / 3600)}h` : `${int(secs / 86400)}d`;
}
function the_person(m, slug) {
return m.people[slug ?? ''] ?? die(slug ? `Unknown person: ${slug}.` : 'Which person? Give their id (dawnline person ls).');
}
function help() {
@@ -39,19 +91,24 @@ Usage: dawnline <command>
sync Push devices and access rules to the tunnels
status People and devices with live state (JSON)
health Run health checks (JSON)
person ls [--json] Everyone: id, name, access, state, devices, last seen
person add <name> [--slug s] [--access lan|internet|both] [--devices n]
[--expires YYYY-MM-DD] [--quota GB]
person link <slug> Print the personal portal link
person rm <slug> Remove a person and their devices
device add <slug> <name> [--kind phone|computer|tablet|router]
[--expires YYYY-MM-DD] [--quota GB] [--server id]
person link <id> Print the personal portal link
person rm <id> [--yes] Remove a person and their devices (--yes when they have any)
device ls [person] [--json]
device add <person> <name> [--kind phone|computer|tablet|router] [--conf]
device conf <id> Print a device configuration (.conf)
device rm <id> Remove a device
backup Create a backup in /etc/dawnline/backups
portal-cert Print the certificate and key the portal uses
portal-http-port Print the plain-HTTP port when an IP is among the portal addresses
log Service log: tunnel and service starts, stops, repairs (newest first)
log [-n N] [--since 2h|3d|date] [--level error|down|repair|up|info] [--src awg|dawnline|portal] [--json]
Service log: tunnel and service starts, stops, repairs (newest first)
teardown Remove everything Dawnline created on the router
version`);
version
Exit codes: 0 done, 1 refused or failed, 2 unknown command. health exits 1 when a check fails.`);
}
/*
@@ -83,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);
}
@@ -106,40 +163,100 @@ try {
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })));
}
else if (cmd == 'health')
out(health.health());
else if (cmd == 'health') {
let checks = health.health();
out(checks);
if (length(filter(checks, (c) => c.status == 'error')))
exit(1);
}
else if (cmd == 'person' && args[1] == 'ls') {
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
let people = sort(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })), (a, b) => a.name < b.name ? -1 : 1);
if (opts.json)
out(people);
else
table([ 'ID', 'NAME', 'SERVER', 'ACCESS', 'STATE', 'DEVICES', 'LAST SEEN' ], map(people, (p) => [
p.id, p.name, p.server, p.access, p.state, `${length(p.devices)}${p.online ? ` (${p.online} online)` : ''}`,
p.online ? 'now' : p.last_seen ? ago(time() - p.last_seen) + ' ago' : 'never',
]));
}
else if (cmd == 'person' && args[1] == 'add') {
let id = store.transact((c, m) => core.create_person(c, m, {
name: args[2], slug: opt('slug'), access: opt('access', 'internet'),
name: args[2], slug: opt('slug'), access: opt('access', 'internet'), server: opt('server'),
device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'),
}));
let m2 = core.load();
out(core.portal_url(m2, m2.people[id]) ?? id);
live.add_event({ type: 'person_added', person: id, detail: m2.people[id].name, by: 'admin' });
out(`Added ${m2.people[id].name} (${id})`);
out(core.portal_url(m2, m2.people[id]) ?? 'No personal link: the portal is off.');
}
else if (cmd == 'person' && args[1] == 'link') {
let m = core.load();
let p = m.people[args[2]] ?? die('Unknown person.');
out(core.portal_url(m, p) ?? 'Set settings.portal_host first.');
let p = the_person(m, args[2]);
out(core.portal_url(m, p) ?? 'No personal link: the portal is off.');
}
else if (cmd == 'person' && args[1] == 'rm') {
store.transact((c, m) => core.delete_person(c, m, args[2]));
apply.sync();
let m = core.load();
let p = the_person(m, args[2]);
let n = length(p.devices);
if (n && !opts.yes)
die(`${p.name} has ${n} device${n == 1 ? '' : 's'}: add --yes to remove them too.`);
store.transact((c, m) => core.delete_person(c, m, p.id));
live.add_event({ type: 'person_removed', person: p.id, detail: p.name, pname: p.name, by: 'admin' });
let s = apply.sync();
out(`Removed ${p.name}${n ? ` and ${n} device${n == 1 ? '' : 's'}` : ''}.`);
if (s.warning)
warn(`dawnline: ${s.warning}\n`);
}
else if (cmd == 'device' && args[1] == 'ls') {
let m = core.load(), d = live.dump(m);
let who = args[2] ? the_person(m, args[2]) : null;
let rows = [];
for (let id, dev in m.devices) {
let p = m.people[dev.person];
if (!p || (who && p.id != who.id))
continue;
let peer = d.peers[dev.public_key];
let online = live.online(d, id, peer);
push(rows, { id, person: p.id, name: dev.name, kind: dev.kind, address: dev.address, disabled: dev.disabled,
online, handshake: +(peer?.handshake ?? 0) });
}
rows = sort(rows, (a, b) => (a.person < b.person ? -1 : a.person > b.person ? 1 : 0) || (a.name < b.name ? -1 : 1));
if (opts.json)
out(rows);
else
table([ 'ID', 'PERSON', 'NAME', 'KIND', 'ADDRESS', 'STATE' ], map(rows, (r) => [
r.id, r.person, r.name, r.kind, r.address,
r.disabled ? 'off' : r.online ? 'online' : r.handshake ? `seen ${ago(time() - r.handshake)} ago` : 'never connected',
]));
}
else if (cmd == 'device' && args[1] == 'add') {
// Keys first: generating them runs the awg tool, not worth holding the config lock for.
let keys = awg.new_keys();
let id = store.transact((c, m) => core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin', keys }));
apply.sync();
out(id);
// Through the same door as LuCI and the portal: event, "issued" marker, capability check.
let m = core.load();
let p = the_person(m, args[2]);
if (!args[3])
die('Which name? dawnline device add <person> <name>.');
let r = devices.add(p.id, args[3], opt('kind', 'phone'), { by: 'admin' });
if (opts.conf)
print(r.config.conf);
else
out(`${r.id} (dawnline device conf ${r.id} prints its configuration)`);
if (r.warning)
warn(`dawnline: ${r.warning}\n`);
}
else if (cmd == 'device' && args[1] == 'conf') {
let m = core.load();
let d = m.devices[args[2]] ?? die('Unknown device.');
let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
awg.mark_issued(m, d.id);
print(awg.client_config(m, d).conf);
}
else if (cmd == 'device' && args[1] == 'rm') {
store.transact((c, m) => core.delete_device(c, m, args[2]));
apply.sync();
let m = core.load();
let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
let r = devices.remove(d.id, { by: 'admin' });
out(`Removed ${d.name} (${m.people[d.person]?.name ?? d.person}).`);
if (r.warning)
warn(`dawnline: ${r.warning}\n`);
}
else if (cmd == 'backup')
out(backup.backup_create(opt('reason')));
@@ -153,7 +270,22 @@ try {
out(`${core.portal_http_port(m)}`);
}
else if (cmd == 'log') {
for (let e in watchdog.view(core.load()).log) {
let n = +opt('n', 0) || 0;
let since = since_time(opt('since'));
let level = opt('level'), src = opt('src');
if (level && index([ 'info', 'up', 'down', 'repair', 'error' ], level) < 0)
die('--level takes error, down, repair, up or info.');
if (src && index([ 'awg', 'dawnline', 'portal' ], src) < 0)
die('--src takes awg, dawnline or portal.');
let log = filter(slog_read(n && !since && !level && !src ? n : null),
(e) => (!since || e.ts >= since) && (!level || e.level == level) && (!src || e.src == src));
if (n && length(log) > n)
log = slice(log, 0, n);
if (opts.json) {
out(log);
exit(0);
}
for (let e in log) {
let t = localtime(e.ts);
let text = e.by == 'admin'
? join(' ', filter([ 'You', e.msg, e.kind, e.who, e.note ? '· ' + e.note : null ], (x) => x))
@@ -177,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);
}
@@ -197,8 +329,12 @@ try {
apply.teardown();
else if (cmd == 'version')
out(VERSION);
else
else if (cmd == 'help' || cmd == '--help' || cmd == '-h')
help();
else {
warn(`dawnline: unknown command "${join(' ', slice(args, 0, 2))}" (dawnline help)\n`);
exit(2);
}
}
catch (e) {
warn(`dawnline: ${e.message}\n`);
@@ -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
@@ -11,9 +15,9 @@
'use strict';
import * as uloop from 'uloop';
import { readfile, writefile, stat, unlink } from 'fs';
import { open, readfile, writefile, stat, unlink } from 'fs';
import {
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, DATA_DIR, RUN_DIR, VERSION
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, date_end, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
@@ -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;
@@ -34,11 +42,32 @@ const LOG_FLUSH = { '10min': 600, hourly: 3600 };
const RESYNC_EVERY = 600;
const CONFIG_FILE = '/etc/config/dawnline';
// One agent, procd's. A second copy would run forever beside it with the code
// it started with: its own events (pauses and resumes from stale states), its
// own counters and syncs. It takes no arguments: the commands are `dawnline`'s.
if (length(ARGV)) {
warn(`The agent takes no arguments (procd runs it). For commands use: dawnline ${join(' ', ARGV)}\n`);
exit(2);
}
ensure_dir(RUN_DIR);
// Held as long as the process lives; close-on-exec, so children don't keep it.
let instance = open(`${RUN_DIR}/agent.lock`, 'we');
if (!instance?.lock('xn')) {
warn(`The agent is already running (${RUN_DIR}/agent.lock is held). Use /etc/init.d/dawnline restart.\n`);
exit(1);
}
let usage = live.load_usage();
let last_states = null;
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
// swallow connects that happened in between.
let presence = read_json(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);
@@ -107,25 +136,30 @@ function record_rate(m) {
write_json(`${RUN_DIR}/rate_people.json`, people, 0o644);
}
let last_sync = 0;
// Per server, how the agent's last sync of its devices went (dawnline.awg.sync_peers).
let last_peers = {};
let conf_mtime = null;
let cert_mtime = null;
const REASON = {
paused: 'paused by admin', paused_all: 'everyone paused', expired: 'end date reached',
quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', active: 'active',
paused: 'paused by admin', expired: 'end date reached',
quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', server_off: 'server turned off',
active: 'active',
};
function check_people(m, states, events) {
let ts = time();
for (let id, p in m.people) {
let st = states[id], prev = last_states?.[id];
// The admin's own pauses are logged by rpcd when they happen; here only
// what changes on its own (end date, data limit, allowed hours).
let by_admin = (x) => x == 'paused' || x == 'paused_all';
// The admin's own pauses (and turning a server off or on) are logged by
// rpcd when they happen; here only what changes on its own (end date,
// data limit, allowed hours).
let by_admin = (x) => x == 'paused' || x == 'server_off';
if (prev != null && prev != st && !by_admin(prev) && !by_admin(st))
push(events, { type: st == 'active' ? 'resumed' : 'paused', person: id, detail: REASON[st] ?? st });
// "Remove their devices" when the end date passes.
if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices)) {
// "Remove their devices" when the end date passes: irreversible, so never
// on a clock that has not been set yet (a router before NTP is in 1970).
if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices) && localtime(ts).year >= 2025) {
store.transact((c, mm) => {
for (let d in mm.people[id]?.devices ?? [])
core.delete_device(c, mm, d);
@@ -136,32 +170,6 @@ function check_people(m, states, events) {
}
}
let last_home = 0;
/** Locate new client addresses for the admin map (a couple per minute). */
function check_geo(m) {
if (!m.settings.geo_enabled)
return;
let cache = geo.load();
let ips = [];
for (let id, rec in usage.devices)
for (let ip in keys(rec.ips ?? {}))
push(ips, ip);
let changed = geo.resolve(m.settings, cache, ips, 2);
if (time() - last_home > 3600) {
last_home = time();
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
changed = geo.resolve_home(m.settings, cache, wan) || changed;
}
if (changed)
geo.save(cache);
}
function place_of(ip) {
let pl = geo.place(geo.load(), ip);
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
}
/** Connections from home: the DHCP name of the address, as it is now. */
function named(e) {
let h = net.event_hosts(e, net.lan_names());
@@ -173,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++;
@@ -198,41 +288,201 @@ function save_presence(people) {
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
}
/* ---------- locations ---------- */
// A lookup run: this many addresses at most, within this many seconds; a run
// still going after GEO_KILL seconds (past every timeout) is given up.
const GEO_PER_RUN = 3;
const GEO_BUDGET = 12;
const GEO_KILL = 60;
let last_home = 0;
// Addresses the watcher saw connect or roam that wait for a run.
let geo_pending = {};
// The run in a child process (uloop.task) and when it started; null when none.
let geo_task = null, geo_since = 0;
/** Every client address still shown on the map (the cache never pushes these out). */
function geo_shown() {
let ips = [];
for (let id, rec in usage.devices)
for (let ip in keys(rec.ips ?? {}))
push(ips, ip);
return uniq(ips);
}
/*
* A run's results: into the cache (the agent is its only writer), onto the
* connections in the activity log that were logged before their place was
* known, and to open pages at once: the revision moves for the people seen
* from those addresses.
*/
function geo_done(found) {
let cache = geo.load();
if (type(found) != 'object' || !geo.merge(cache, found, geo_shown()))
return;
geo.save(cache);
let where = {};
for (let ip, r in found)
if (r)
where[ip] = geo.label(r);
if (!length(keys(where)))
return;
let m = watch_model(), people = {};
for (let id, rec in usage.devices)
for (let ip in keys(where))
if (rec.ips?.[ip] && m.devices[id])
people[m.devices[id].person] = true;
live.set_places(where, time() - 3600);
save_presence(keys(people));
}
/*
* Locate client addresses for the admin map in a child process: a lookup
* waits on the network for seconds, and neither the 1-second watcher nor the
* tick may wait with it. Addresses that just connected go first, at once
* (the watcher calls this on a connect); the tick adds anything still shown
* that is missing or stale (`more`). One run at a time, a few addresses each;
* what just connected and did not fit waits for the next run.
*/
function geo_lookup(m, more) {
if (!m.settings.geo_enabled) {
geo_pending = {};
return;
}
if (geo_task && !geo_task.finished()) {
if (time() - geo_since < GEO_KILL)
return;
geo_task.kill();
}
geo_task = null;
let todo = geo.stale(geo.load(), [ ...keys(geo_pending), ...(more ?? []) ]);
let want = slice(todo, 0, GEO_PER_RUN);
let rest = {};
for (let ip in slice(todo, GEO_PER_RUN))
if (geo_pending[ip])
rest[ip] = true;
geo_pending = rest;
if (!length(want))
return;
let provider = m.settings.geo_provider;
let t = null;
t = uloop.task(() => {
// The child shares the instance lock: it must not keep it past the agent (a restart would find it taken).
instance.close();
return geo.lookup_all(provider, want, GEO_PER_RUN, GEO_BUDGET);
}, (found) => {
if (geo_task == t)
geo_task = null;
geo_done(found);
if (length(keys(geo_pending)))
geo_lookup(watch_model());
});
geo_task = t;
geo_since = time();
}
/** The tick: shown addresses missing or stale get a run; the router's own place about hourly. */
function check_geo(m) {
geo_lookup(m, geo_shown());
if (!m.settings.geo_enabled || time() - last_home <= 3600)
return;
last_home = time();
let cache = geo.load();
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
if (geo.resolve_home(m.settings, cache, wan))
geo.save(cache);
}
function place_of(ip) {
return geo.label(geo.place(geo.load(), 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);
}
let on = last_hs[id] > 0 && now - last_hs[id] < live.ONLINE_WINDOW;
// Not in the tunnel (turned off, paused, out of time or data): offline now, and online
// again only with a new handshake, not the one remembered from before. Unless its
// tunnel was just set up again and the sync has not brought it back yet.
else if (!(grace[ifn] > now))
last_hs[id] = 0;
let on = last_hs[id] > 0 && now - last_hs[id] < (wm_windows[id] ?? live.ONLINE_WINDOW);
let was = last_online[id];
// 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)
@@ -243,25 +493,49 @@ 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;
// The status first, then what takes longer (a geo lookup may wait on the network).
save_presence(keys(people));
if (!length(events))
return;
live.collect(m, usage, d);
live.save_usage(usage, false);
if (m.settings.geo_enabled && length(ips)) {
let cache = geo.load();
if (geo.resolve(m.settings, cache, ips, length(ips)))
geo.save(cache);
}
// The event carries the place when the cache already knows it. A new
// address is looked up at once, in a child process (geo_lookup): its place
// goes onto this event and the revision moves again when it is known.
for (let e in events)
if (e.type == 'connect')
e.where = place_of(e.detail);
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
save_presence(keys(people));
if (m.settings.geo_enabled && length(ips)) {
for (let ip in ips)
geo_pending[ip] = true;
geo_lookup(m);
}
}
// What the service log was already told. On flash: the public address often
@@ -276,6 +550,33 @@ function note(k, v) {
write_json(NOTES, notes, 0o600);
}
/*
* End dates in the activity log: a heads-up once per end date when its
* warning window opens, and "keep access" passing it (which changes no
* state, so nothing else would say it). Not on a clock that is not set.
*/
function check_expiry(m, events) {
let ts = time();
if (localtime(ts).year < 2025)
return;
for (let id, p in m.people) {
if (!p.expires)
continue;
let end = date_end(p.expires);
if (end == null)
continue;
let left = end > ts ? int((end - ts) / 86400) + 1 : 0;
if (left > 0 && p.expire_warn > 0 && left <= p.expire_warn && notes[`warned:${id}`] != p.expires) {
note(`warned:${id}`, p.expires);
push(events, { type: 'expiring', person: id, detail: `${left} day${left == 1 ? '' : 's'}` });
}
if (left == 0 && p.expire_action == 'notify' && notes[`kept:${id}`] != p.expires) {
note(`kept:${id}`, p.expires);
push(events, { type: 'expired_kept', person: id, detail: p.expires });
}
}
}
/** "Jan 1 2027" from the certificate, or null. */
function cert_end(path) {
let m = match(sh_out(`openssl x509 -enddate -noout -in ${q(path)} 2>/dev/null`) ?? '', /notAfter=([A-Za-z]+) +([0-9]+) [0-9:]+ ([0-9]+)/);
@@ -288,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;
@@ -297,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);
}
}
@@ -319,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;
@@ -339,7 +644,10 @@ function nightly_backup() {
backup.backup_create('auto');
write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600);
}
catch (e) {}
catch (e) {
// Tried again tomorrow; meanwhile the admin should know (a full flash, mostly).
slog('dawnline', 'error', sprintf(L_('nightly backup failed: %s'), e.message), null, L_('Backup'));
}
}
}
@@ -370,8 +678,11 @@ 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), or
* every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
* file was written (by anyone: rpcd, the portal, the CLI, a restore), the
* access table is gone (a flushed ruleset: the firewall alone would let every
* device reach everything, so the sync unloads them until it is back), a
* running tunnel holds other devices than it should (check_peers), or every
* RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
*/
function sync_runtime(t) {
// uci commits replace the file: a new inode even within the same second.
@@ -379,14 +690,33 @@ function sync_runtime(t) {
let mt = st ? `${st.mtime}/${st.inode}` : null;
let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) ||
(conf_mtime != null && mt != conf_mtime);
if (changed || time() - last_sync > RESYNC_EVERY) {
apply.sync(t.m, usage);
if (changed || time() - last_sync > RESYNC_EVERY || (length(t.m.servers) && !apply.table_present())) {
last_peers = apply.sync(t.m, usage).peers ?? {};
last_sync = time();
}
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
@@ -405,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());
}
@@ -421,32 +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)
{ 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) },
];
@@ -462,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;
}
}
@@ -470,22 +804,29 @@ function step(i, s, fn) {
function tick() {
ensure_dir(RUN_DIR);
writefile(watchdog.BEAT, `${time()}`);
// A restore or import drops the live counters; start over from flash.
if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
// A restore or import put other counters on flash (dawnline.backup leaves
// a marker): start over from them, whatever the watcher wrote since.
if (stat(live.USAGE_RELOAD)) {
unlink(live.USAGE_RELOAD);
usage = live.load_usage(true);
}
else if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
usage = live.load_usage();
let t = { m: null, pol: null, reset: false, events: [] };
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)
if (persist) {
last_flush = time();
geo.flush();
}
});
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);
@@ -497,7 +838,10 @@ function tick() {
function shutdown() {
live.save_usage(usage, true);
live.persist_events();
geo.flush();
slog_trim(true);
// The live meter's file goes with it: a stopped agent's points are no speed now.
meter.stop();
// A clean stop: the next start is not a crash.
unlink(watchdog.BEAT);
}
@@ -514,18 +858,27 @@ if (was != VERSION) {
writefile(`${DATA_DIR}/version`, VERSION);
}
slog_restore();
if (was && was != VERSION)
slog('dawnline', 'up', `updated · ${was} → ${VERSION}`, null, 'Dawnline');
// postupdate put this (kept) version back because the new one did not come up.
let rolled = trim(readfile(`${RUN_DIR}/update-rolled-back`) ?? '');
unlink(`${RUN_DIR}/update-rolled-back`);
if (rolled)
slog('dawnline', 'error', sprintf(L_('update to %s failed its check - rolled back to %s'), rolled, VERSION),
L_('The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.'), 'Dawnline');
else if (was && was != VERSION)
slog('dawnline', 'up', sprintf(L_('updated · %s → %s'), was, VERSION), null, 'Dawnline');
else if (crashed)
slog('dawnline', 'repair', '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();
@@ -535,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);
});
@@ -1,9 +1,17 @@
#!/bin/sh
# Cron, every 5 minutes: the watchdog lives in the agent, so this looks after
# the agent itself and kills it when it runs but has stopped ticking (procd
# starts it again). Off with the watchdog (Health → Watchdog).
[ "$(uci -q get dawnline.settings.watchdog)" = 0 ] && exit 0
# the agent itself: ends any copy that isn't procd's, and kills procd's when it
# runs but has stopped ticking (procd starts it again; that part is off with
# the watchdog, Health → Watchdog).
pid="$(ubus call service list '{"name":"dawnline"}' 2>/dev/null | jsonfilter -q -e '@.dawnline.instances.agent.pid')"
# Only procd's agent: any other copy (started by hand, or left by an older version that let
# it start) runs stale code beside it, with its own events and syncs. Always ended.
for p in $(pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent'); do
[ "$p" = "$pid" ] || kill -9 "$p" 2>/dev/null
done
[ "$(uci -q get dawnline.settings.watchdog)" = 0 ] && exit 0
[ -n "$pid" ] && [ -r "/proc/$pid/stat" ] || exit 0
now="$(date +%s)"
@@ -0,0 +1,54 @@
#!/bin/sh
# Dawnline — after its own package was replaced: restart, check that the new
# version answers (the LuCI link and the agent), and put the kept previous
# version back when it does not. Started detached by the updater
# (usr/libexec/dawnline/updater) with the version being installed.
# postupdate <version>
# Plain shell on purpose: a release whose ucode does not compile cannot check
# or repair itself, and the admin cannot click Roll back in a page that this
# same backend serves.
RUN=/var/run/dawnline
KEEP=/etc/dawnline/keep/app
to="${1:-?}"
sleep 2
# LuCI reads a language's catalogs once per web server: a replaced translation
# needs a fresh one, before the new version answers and the page reloads.
ls /usr/lib/lua/luci/i18n/dawnline.*.lmo >/dev/null 2>&1 && /etc/init.d/uhttpd restart >/dev/null 2>&1
/etc/init.d/rpcd reload >/dev/null 2>&1
/etc/init.d/dawnline restart >/dev/null 2>&1
up() {
ubus list luci.dawnline >/dev/null 2>&1 || return 1
ubus -t 10 call luci.dawnline rev >/dev/null 2>&1 || return 1
pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent' >/dev/null 2>&1
}
i=0
while [ "$i" -lt 12 ]; do
sleep 5
i=$((i + 1))
up && exit 0
done
logger -t dawnline "update to $to failed its check: luci.dawnline or the agent is not up"
set --
for f in "$KEEP"/*.ipk "$KEEP"/*.apk; do
[ -f "$f" ] && set -- "$@" "$f"
done
if [ "$#" -eq 0 ]; then
logger -t dawnline "no previous version is kept: nothing to roll back to"
exit 1
fi
if command -v apk >/dev/null 2>&1; then
apk add --allow-untrusted "$@" >/dev/null 2>&1
else
opkg install --force-reinstall --force-downgrade "$@" >/dev/null 2>&1
fi
/etc/init.d/rpcd restart >/dev/null 2>&1
/etc/init.d/dawnline restart >/dev/null 2>&1
mkdir -p "$RUN"
# The restored agent reports it in the service log on its start.
echo "$to" > "$RUN/update-rolled-back"
logger -t dawnline "rolled back from $to to the kept version"
exit 0
@@ -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,
@@ -72,6 +97,8 @@ const ctx = {
pol: POL,
work: `/tmp/dawnline-update.${PID}`,
log, phase, run, save,
// An automatic run (nobody is watching: the previous version is always kept).
auto: () => job.auto,
versions: (from, to) => {
job.from = from;
job.to = to;
@@ -80,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() {
@@ -96,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)
@@ -104,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: '' };
}
}
@@ -130,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;
@@ -140,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) {
@@ -170,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);
@@ -226,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');
@@ -237,46 +285,41 @@ 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);
}
/** The restarts the job asked for, in one go, after its final state is saved. */
/**
* The restarts the job asked for, in one go, after its final state is saved.
* Dawnline's own package is restarted by postupdate, a shell that also checks
* the new version and rolls back to the kept one when it does not come up.
*/
function restarts() {
if (after.app) {
let to = replace(`${job.to ?? ''}`, /[^A-Za-z0-9.-]/g, '');
system(`/usr/libexec/dawnline/postupdate '${to}' </dev/null >/dev/null 2>&1 &`);
return;
}
let cmds = [];
if (after.app)
push(cmds, '/etc/init.d/rpcd reload');
else if (after.apply)
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.app || after.apply || after.uhttpd)
if (after.apply || after.uhttpd)
push(cmds, '/etc/init.d/dawnline restart');
if (length(cmds))
system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`);
}
/* ---------- main ---------- */
ensure_dir(RUN_DIR);
// One job at a time (LuCI refuses a second one; an automatic run just skips its turn).
let LOCK = null;
for (let i = 0; i < 10 && !LOCK; i++) {
LOCK = upd.try_lock();
if (!LOCK)
system('usleep 100000 2>/dev/null || sleep 1');
}
if (!LOCK)
exit(0);
fs.mkdir(ctx.work, 0o700);
save();
/** 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(`Unknown component ${w}`);
die(sprintf(_('Unknown component %s'), w));
job.result = run_checks(which);
let st = upd.auto_state();
note_found(job.result, st, false);
@@ -289,24 +332,41 @@ try {
else if (job.action == 'auto')
auto();
else
die('Usage: updater check [app|amneziawg|packages] | install <what> | auto');
die(USAGE);
job.state = 'done';
phase('Finished');
phase(_('Finished'));
}
catch (e) {
quiet = false;
job.state = 'failed';
job.error = e.message;
log(`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 ? 'automatic ' : ''}update failed`, e.message, WHO[name] ?? 'Dawnline');
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);
// One job at a time (LuCI refuses a second one; an automatic run just skips its turn).
let LOCK = null;
for (let i = 0; i < 10 && !LOCK; i++) {
LOCK = upd.try_lock();
if (!LOCK)
sleep(100);
}
if (!LOCK)
exit(0);
fs.mkdir(ctx.work, 0o700);
save();
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{--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.pill{display:inline-flex;align-items:center;height:22px;padding:0 9px;border-radius:999px;font-size:12px;font-weight:500;background:var(--soft);color:var(--muted)}.pill.ok{background:var(--ok-wash);color:var(--ok)}.pill.warn{background:var(--warn-wash);color:var(--warn)}.pill.bad{background:var(--bad-wash);color:var(--bad)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);mLine truncated
@@ -1,6 +0,0 @@
"use strict";(()=>{var it=Object.create;var He=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var ft=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var dt=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ct(t))!ut.call(e,u)&&u!==r&&He(e,u,{get:()=>t[u],enumerable:!(i=ot(t,u))||i.enumerable});return e};var ht=(e,t,r)=>(r=e!=null?it(lt(e)):{},dt(t||!e||!e.__esModule?He(r,"default",{value:e,enumerable:!0}):r,e));var je=ft((Ve,Ye)=>{"use strict";var qe=(function(){var e=function(M,A){var b=236,x=17,c=M,m=r[A],s=null,a=0,y=null,d=[],g={},T=function(l,f){a=c*4+17,s=(function(o){for(var h=new Array(o),v=0;v<o;v+=1){h[v]=new Array(o);for(var w=0;w<o;w+=1)h[v][w]=null}return h})(a),D(0,0),D(a-7,0),D(0,a-7),G(),I(),Q(l,f),c>=7&&z(l),y==null&&(y=at(c,m,d)),W(y,f)},D=function(l,f){for(var o=-1;o<=7;o+=1)if(!(l+o<=-1||a<=l+o))for(var h=-1;h<=7;h+=1)f+h<=-1||a<=f+h||(0<=o&&o<=6&&(h==0||h==6)||0<=h&&h<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=h&&h<=4?s[l+o][f+h]=!0:s[l+o][f+h]=!1)},P=function(){for(var l=0,f=0,o=0;o<8;o+=1){T(!0,o);var h=u.getLostPoint(g);(o==0||l>h)&&(l=h,f=o)}return f},I=function(){for(var l=8;l<a-8;l+=1)s[l][6]==null&&(s[l][6]=l%2==0);for(var f=8;f<a-8;f+=1)s[6][f]==null&&(s[6][f]=f%2==0)},G=function(){for(var l=u.getPatternPosition(c),f=0;f<l.length;f+=1)for(var o=0;o<l.length;o+=1){var h=l[f],v=l[o];if(s[h][v]==null)for(var w=-2;w<=2;w+=1)for(var C=-2;C<=2;C+=1)w==-2||w==2||C==-2||C==2||w==0&&C==0?s[h+w][v+C]=!0:s[h+w][v+C]=!1}},z=function(l){for(var f=u.getBCHTypeNumber(c),o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;s[Math.floor(o/3)][o%3+a-8-3]=h}for(var o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;s[o%3+a-8-3][Math.floor(o/3)]=h}},Q=function(l,f){for(var o=m<<3|f,h=u.getBCHTypeInfo(o),v=0;v<15;v+=1){var w=!l&&(h>>v&1)==1;v<6?s[v][8]=w:v<8?s[v+1][8]=w:s[a-15+v][8]=w}for(var v=0;v<15;v+=1){var w=!l&&(h>>v&1)==1;v<8?s[8][a-v-1]=w:v<9?s[8][15-v-1+1]=w:s[8][15-v-1]=w}s[a-8][8]=!l},W=function(l,f){for(var o=-1,h=a-1,v=7,w=0,C=u.getMaskFunction(f),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var N=0;N<2;N+=1)if(s[h][_-N]==null){var K=!1;w<l.length&&(K=(l[w]>>>v&1)==1);var L=C(h,_-N);L&&(K=!K),s[h][_-N]=K,v-=1,v==-1&&(w+=1,v=7)}if(h+=o,h<0||a<=h){h-=o,o=-o;break}}},ae=function(l,f){for(var o=0,h=0,v=0,w=new Array(f.length),C=new Array(f.length),_=0;_<f.length;_+=1){var N=f[_].dataCount,K=f[_].totalCount-N;h=Math.max(h,N),v=Math.max(v,K),w[_]=new Array(N);for(var L=0;L<w[_].length;L+=1)w[_][L]=255&l.getBuffer()[L+o];o+=N;var Y=u.getErrorCorrectPolynomial(K),j=k(w[_],Y.getLength()-1),Pe=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var L=0;L<C[_].length;L+=1){var Ne=L+Pe.getLength()-C[_].length;C[_][L]=Ne>=0?Pe.getAt(Ne):0}}for(var Re=0,L=0;L<f.length;L+=1)Re+=f[L].totalCount;for(var be=new Array(Re),he=0,L=0;L<h;L+=1)for(var _=0;_<f.length;_+=1)L<w[_].length&&(be[he]=w[_][L],he+=1);for(var L=0;L<v;L+=1)for(var _=0;_<f.length;_+=1)L<C[_].length&&(be[he]=C[_][L],he+=1);return be},at=function(l,f,o){for(var h=$.getRSBlocks(l,f),v=E(),w=0;w<o.length;w+=1){var C=o[w];v.put(C.getMode(),4),v.put(C.getLength(),u.getLengthInBits(C.getMode(),l)),C.write(v)}for(var _=0,w=0;w<h.length;w+=1)_+=h[w].dataCount;if(v.getLengthInBits()>_*8)throw"code length overflow. ("+v.getLengthInBits()+">"+_*8+")";for(v.getLengthInBits()+4<=_*8&&v.put(0,4);v.getLengthInBits()%8!=0;)v.putBit(!1);for(;!(v.getLengthInBits()>=_*8||(v.put(b,8),v.getLengthInBits()>=_*8));)v.put(x,8);return ae(v,h)};g.addData=function(l,f){f=f||"Byte";var o=null;switch(f){case"Numeric":o=B(l);break;case"Alphanumeric":o=q(l);break;case"Byte":o=J(l);break;case"Kanji":o=U(l);break;default:throw"mode:"+f}d.push(o),y=null},g.isDark=function(l,f){if(l<0||a<=l||f<0||a<=f)throw l+","+f;return s[l][f]},g.getModuleCount=function(){return a},g.make=function(){if(c<1){for(var l=1;l<40;l++){for(var f=$.getRSBlocks(l,m),o=E(),h=0;h<d.length;h++){var v=d[h];o.put(v.getMode(),4),o.put(v.getLength(),u.getLengthInBits(v.getMode(),l)),v.write(o)}for(var w=0,h=0;h<f.length;h++)w+=f[h].dataCount;if(o.getLengthInBits()<=w*8)break}c=l}T(!1,P())},g.createTableTag=function(l,f){l=l||2,f=typeof f=="undefined"?l*4:f;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+f+"px;",o+='">',o+="<tbody>";for(var h=0;h<g.getModuleCount();h+=1){o+="<tr>";for(var v=0;v<g.getModuleCount();v+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+l+"px;",o+=" height: "+l+"px;",o+=" background-color: ",o+=g.isDark(h,v)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(l,f,o,h){var v={};typeof arguments[0]=="object"&&(v=arguments[0],l=v.cellSize,f=v.margin,o=v.alt,h=v.title),l=l||2,f=typeof f=="undefined"?l*4:f,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
`}return o%2&&l>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(l,f){if(l=l||1,l<2)return st(f);l-=1,f=typeof f=="undefined"?l*2:f;var o=g.getModuleCount()*l+f*2,h=f,v=o-f,w,C,_,N,K=Array(l+1).join("██"),L=Array(l+1).join(" "),Y="",j="";for(w=0;w<o;w+=1){for(_=Math.floor((w-h)/l),j="",C=0;C<o;C+=1)N=1,h<=C&&C<v&&h<=w&&w<v&&g.isDark(_,Math.floor((C-h)/l))&&(N=0),j+=N?K:L;for(_=0;_<l;_+=1)Y+=j+`
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(l,f){f=f||2;for(var o=g.getModuleCount(),h=0;h<o;h++)for(var v=0;v<o;v++)l.fillStyle=g.isDark(h,v)?"black":"white",l.fillRect(h*f,v*f,f,f)},g};e.stringToBytesFuncs={default:function(M){for(var A=[],b=0;b<M.length;b+=1){var x=M.charCodeAt(b);A.push(x&255)}return A}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(M,A){var b=(function(){for(var c=H(M),m=function(){var I=c.read();if(I==-1)throw"eof";return I},s=0,a={};;){var y=c.read();if(y==-1)break;var d=m(),g=m(),T=m(),D=String.fromCharCode(y<<8|d),P=g<<8|T;a[D]=P,s+=1}if(s!=A)throw s+" != "+A;return a})(),x=63;return function(c){for(var m=[],s=0;s<c.length;s+=1){var a=c.charCodeAt(s);if(a<128)m.push(a);else{var y=b[c.charAt(s)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(x)}}return m}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},i={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},u=(function(){var M=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],A=1335,b=7973,x=21522,c={},m=function(s){for(var a=0;s!=0;)a+=1,s>>>=1;return a};return c.getBCHTypeInfo=function(s){for(var a=s<<10;m(a)-m(A)>=0;)a^=A<<m(a)-m(A);return(s<<10|a)^x},c.getBCHTypeNumber=function(s){for(var a=s<<12;m(a)-m(b)>=0;)a^=b<<m(a)-m(b);return s<<12|a},c.getPatternPosition=function(s){return M[s-1]},c.getMaskFunction=function(s){switch(s){case i.PATTERN000:return function(a,y){return(a+y)%2==0};case i.PATTERN001:return function(a,y){return a%2==0};case i.PATTERN010:return function(a,y){return y%3==0};case i.PATTERN011:return function(a,y){return(a+y)%3==0};case i.PATTERN100:return function(a,y){return(Math.floor(a/2)+Math.floor(y/3))%2==0};case i.PATTERN101:return function(a,y){return a*y%2+a*y%3==0};case i.PATTERN110:return function(a,y){return(a*y%2+a*y%3)%2==0};case i.PATTERN111:return function(a,y){return(a*y%3+(a+y)%2)%2==0};default:throw"bad maskPattern:"+s}},c.getErrorCorrectPolynomial=function(s){for(var a=k([1],0),y=0;y<s;y+=1)a=a.multiply(k([1,p.gexp(y)],0));return a},c.getLengthInBits=function(s,a){if(1<=a&&a<10)switch(s){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+s}else if(a<27)switch(s){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+s}else if(a<41)switch(s){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+s}else throw"type:"+a},c.getLostPoint=function(s){for(var a=s.getModuleCount(),y=0,d=0;d<a;d+=1)for(var g=0;g<a;g+=1){for(var T=0,D=s.isDark(d,g),P=-1;P<=1;P+=1)if(!(d+P<0||a<=d+P))for(var I=-1;I<=1;I+=1)g+I<0||a<=g+I||P==0&&I==0||D==s.isDark(d+P,g+I)&&(T+=1);T>5&&(y+=3+T-5)}for(var d=0;d<a-1;d+=1)for(var g=0;g<a-1;g+=1){var G=0;s.isDark(d,g)&&(G+=1),s.isDark(d+1,g)&&(G+=1),s.isDark(d,g+1)&&(G+=1),s.isDark(d+1,g+1)&&(G+=1),(G==0||G==4)&&(y+=3)}for(var d=0;d<a;d+=1)for(var g=0;g<a-6;g+=1)s.isDark(d,g)&&!s.isDark(d,g+1)&&s.isDark(d,g+2)&&s.isDark(d,g+3)&&s.isDark(d,g+4)&&!s.isDark(d,g+5)&&s.isDark(d,g+6)&&(y+=40);for(var g=0;g<a;g+=1)for(var d=0;d<a-6;d+=1)s.isDark(d,g)&&!s.isDark(d+1,g)&&s.isDark(d+2,g)&&s.isDark(d+3,g)&&s.isDark(d+4,g)&&!s.isDark(d+5,g)&&s.isDark(d+6,g)&&(y+=40);for(var z=0,g=0;g<a;g+=1)for(var d=0;d<a;d+=1)s.isDark(d,g)&&(z+=1);var Q=Math.abs(100*z/a/a-50)/5;return y+=Q*10,y},c})(),p=(function(){for(var M=new Array(256),A=new Array(256),b=0;b<8;b+=1)M[b]=1<<b;for(var b=8;b<256;b+=1)M[b]=M[b-4]^M[b-5]^M[b-6]^M[b-8];for(var b=0;b<255;b+=1)A[M[b]]=b;var x={};return x.glog=function(c){if(c<1)throw"glog("+c+")";return A[c]},x.gexp=function(c){for(;c<0;)c+=255;for(;c>=256;)c-=255;return M[c]},x})();function k(M,A){if(typeof M.length=="undefined")throw M.length+"/"+A;var b=(function(){for(var c=0;c<M.length&&M[c]==0;)c+=1;for(var m=new Array(M.length-c+A),s=0;s<M.length-c;s+=1)m[s]=M[s+c];return m})(),x={};return x.getAt=function(c){return b[c]},x.getLength=function(){return b.length},x.multiply=function(c){for(var m=new Array(x.getLength()+c.getLength()-1),s=0;s<x.getLength();s+=1)for(var a=0;a<c.getLength();a+=1)m[s+a]^=p.gexp(p.glog(x.getAt(s))+p.glog(c.getAt(a)));return k(m,0)},x.mod=function(c){if(x.getLen Line truncated
`),hostName:p,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},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(k),port:String(r.port),protocol_version:i.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:p};return r.dns[0]&&($.dns1=r.dns[0]),r.dns[1]&&($.dns2=r.dns[1]),$}function wt(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Mt(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),i=new Uint8Array(await new t.Response(r).arrayBuffer()),u=new Uint8Array(4+i.length);return new DataView(u.buffer).setUint32(0,e.length,!1),u.set(i,4),u}catch{return null}}async function Ae(e,t,r=!0){let i=new TextEncoder().encode(JSON.stringify(xt(e,t))),u=r?await Mt(i):null;return`vpn://${wt(u!=null?u:i)}`}var De=()=>{var e;return(e=S==null?void 0:S.today)!=null?e:pe(new Date)};function n(e,t={},...r){let i=document.createElement(e);for(let[p,k]of Object.entries(t))k==null||k===!1||(p.startsWith("on")&&typeof k=="function"?i.addEventListener(p.slice(2),k):p==="class"?i.className=String(k):k===!0?i.setAttribute(p,""):i.setAttribute(p,String(k)));let u=p=>{p==null||p===!1||(Array.isArray(p)?p.forEach(u):i.appendChild(typeof p=="string"?document.createTextNode(p):p))};return r.forEach(u),i}function O(e){let t=n("span",{class:"ic"});return t.innerHTML=Ge(e,"ic-svg"),t}var kt='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>',Ee=document.getElementById("app"),We,me=(We=Ee.dataset.base)!=null?We:"",At=Ee.dataset.title||"Dawnline",Ce=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,_t=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(me)?me.slice(1):"",Le=class extends Error{constructor(r,i){super(i);this.status=r}};async function ne(e,t){var u;let r=await fetch(`${me}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{}:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),i=null;try{i=await r.json()}catch{}if(!r.ok)throw new Le(r.status,(u=i==null?void 0:i.error)!=null?u:`Request failed (${r.status})`);return i}function te(e,t=!1){let r=n("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),300)},2600)}async function ce(e,t="Copied"){try{await navigator.clipboard.writeText(e)}catch{let r=n("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let i=document.execCommand("copy");if(r.remove(),!i)return te("Copying is blocked here. Select the text and copy it by hand.",!0)}te(t)}function Ze(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),i=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(i),i.click(),setTimeout(()=>{URL.revokeObjectURL(r),i.remove()},1e3)}var Z=null;function Xe(e,t){let r=i=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...t().map((u,p)=>n("div",{class:p?"muted":"tip-title"},u))),Z.style.display="",Z.style.left=`${i.clientX}px`,Z.style.top=`${i.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function Ct(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((i,u)=>{let p=n("i",{class:i?"":"zero"});p.style.height=`${Math.max(8,i/t*100)}%`;let k=e.length-1-u;Xe(p,()=>[k===0?"Today":k===1?"Yesterday":ve(Ie(De(),-k)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ie(i)]),r.appendChild(p)}),r}async function Be(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var oe=null,le=null;function ee(e=!1){if(!oe)return;let t=oe;if(oe=null,document.body.classList.remove("locked"),le==null||le(),le=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function fe(e,t,...r){let i=!!oe;ee(!0);let u=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},e),t?n("span",{class:"muted s"},t):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},O("x"))),n("div",{class:"sheet-body"},...r)),p=n("div",{class:"sheet",onclick:k=>{k.target===p&&ee()}},u);return document.body.appendChild(p),document.body.classList.add("locked"),i?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open")),o Line truncated
`).flatMap((p,k)=>k?[`
`,Qe(p,t)]:[Qe(p,t)])),u=n("button",{class:"btn small",onclick:p=>{p.preventDefault(),t=!t,u.replaceChildren(O(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),i()}},O("key"),n("span",{},"Show key"));return i(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>Ze(e.filename,e.conf)},O("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},O("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),u,n("button",{class:"btn small",onclick:p=>{p.preventDefault(),ce(e.conf,"Configuration copied")}},O("copy"),n("span",{},"Copy"))),r))}async function ue(e,t,r){let i=r!=null?r:await Se(e);if(!i)return;let u=await Ae(i,`${i.server} · ${i.name}`),p=Ce(),k={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:u},O("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=n("div",{class:"qr"});return H.innerHTML=Je(i.conf),n("div",{class:"pane center"},H,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},u),n("button",{class:"btn small",onclick:()=>ce(u,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Rt(i)},$=p?["app","qr","key","file"]:["qr","key","file"],E={app:"Open in app",qr:"QR code",key:"Key",file:"File"},B=n("div",{class:"tab-body"}),q=n("div",{class:"tabs",role:"tablist"}),J=H=>{q.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===H)),B.replaceChildren(k[H]())};for(let H of $)q.appendChild(n("button",{role:"tab","data-id":H,onclick:()=>J(H)},E[H]));J(t&&$.includes(t)?t:$[0]);let U=n("div",{class:"waiting"}),R=H=>{H!=null&&H.online?U.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${xe(H.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};R(e);let F=window.setInterval(async()=>{try{let H=await ne("state");S=H,R(H.person.devices.find(re=>re.id===e.id))}catch{}},5e3);fe(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",q,B,U),le=()=>{clearInterval(F),S&&de(S)}}function Ht(e){let t=n("input",{type:"text",value:e.name,maxlength:48,"aria-label":"Device name"}),r=n("button",{class:"btn primary block",type:"submit"},"Save");fe(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:i=>{i.preventDefault(),Be(r,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),de(S),te("Renamed")}catch(u){te(u.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function It(e,t){let r=t.here===e.id;fe(`New keys for ${e.name}?`,null,n("p",{class:"muted"},r?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:i=>Be(i.currentTarget,async()=>{try{let u=await ne(`devices/${e.id}`,{action:"rotate"});S=u.state,de(S),await ue(e,void 0,u.config)}catch(u){te(u.message,!0)}})},"New keys")))}function Ot(e){fe(`Remove ${e.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:t=>Be(t.currentTarget,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,nt=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function _e(){return nt||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Kt=[[/^SM-S93/,"Galaxy S25"],[/^SM-S92/,"Galaxy S24"],[/^SM-S91/,"Galaxy S23"],[/^SM-S90/,"Galaxy S22"],[/^SM-G99/,"Galaxy S21"],[/^SM-F9/,"Galaxy Z Fold"],[/^SM-F7/,"Galaxy Z Flip"],[/^SM-A5/,"Galaxy A5x"],[/^SM-A3/,"Galaxy A3x"],[/^SM-X/,"Galaxy Tab"] Line truncated
@@ -0,0 +1,22 @@
#!/usr/bin/ucode
// Dawnline personal portal as a CGI script: the request handling itself is
// dawnline.portal. www/cgi-bin/portal (a shell) runs it for requests shaped
// like a personal link and answers the rest itself.
'use strict';
import { stdin } from 'fs';
import { serve } from 'dawnline.portal';
let env = {};
for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE',
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_ACCEPT_ENCODING',
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
'HTTP_CF_CONNECTING_IP' ])
env[k] = getenv(k);
serve({
env,
headers: {},
read: (n) => stdin.read(n),
write: (s) => print(s),
});
@@ -1,21 +1,51 @@
#!/usr/bin/ucode
// Dawnline personal portal as a CGI script: the request handling itself is
// dawnline.portal.
'use strict';
#!/bin/sh
# Dawnline personal portal, the door: uhttpd runs this for every request.
# Anything that is not shaped like a personal link (/<word-code>[/…]) gets
# the portal's bare answer from here, in a shell that costs nothing, so a
# scanner or a flood on the root never starts ucode (compiling the portal's
# module graph is ~140 ms of CPU). Links go on to the portal itself
# (/usr/share/dawnline/portal/cgi.uc), which judges the code.
#
# The answer here is byte for byte the portal's own not_found(): keep both
# in step (dawnline.portal headers(), SECURITY_HEADERS, not_found()).
import { stdin } from 'fs';
import { serve } from 'dawnline.portal';
path="${REQUEST_URI%%\?*}"
w='[a-z][a-z][a-z][a-z][a-z][a-z]'
# The expansion is meant as a pattern (a word of six letters), not literally.
# shellcheck disable=SC2254
case "$path" in
/$w-$w-$w|/$w-$w-$w/*) exec /usr/bin/ucode /usr/share/dawnline/portal/cgi.uc ;;
esac
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',
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
'HTTP_CF_CONNECTING_IP' ])
env[k] = getenv(k);
# HSTS pins the whole name: only when the visitor is on the standard port.
hsts=
if [ "$HTTPS" = on ]; then
port="${HTTP_HOST##*:}"
case "$HTTP_HOST" in *:*) ;; *) port=443 ;; esac
case "$HTTP_HOST" in *\]) port=443 ;; esac
[ "$port" = 443 ] && hsts=1
fi
serve({
env,
headers: {},
read: (n) => stdin.read(n),
write: (s) => print(s),
});
# Files always get the 404: a missing asset must not turn into someone's website.
file=
case "$path" in
/luci-static|/luci-static/*|/cgi-bin|/cgi-bin/*|/ubus|/ubus/*) file=1 ;;
*) case "${path##*/}" in *.*) file=1 ;; esac ;;
esac
redirect=
[ -n "$file" ] || redirect="$(uci -q get dawnline.settings.portal_redirect)"
if [ -n "$redirect" ]; then
printf 'Status: 302 Found\r\n'
printf 'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\nCache-Control: no-store\r\n'
printf 'Location: %s\r\nContent-Type: text/plain\r\n' "$redirect"
[ -n "$hsts" ] && printf 'Strict-Transport-Security: max-age=31536000\r\n'
printf '\r\nMoved\n'
else
printf 'Status: 404 Not Found\r\n'
printf 'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\nCache-Control: no-store\r\n'
printf 'Content-Type: text/plain\r\n'
[ -n "$hsts" ] && printf 'Strict-Transport-Security: max-age=31536000\r\n'
printf '\r\nNot found\n'
fi
exit 0
@@ -6,6 +6,7 @@
"luci.dawnline": [
"rev",
"status",
"meter",
"setup_defaults",
"health",
"service_log",
@@ -18,6 +19,8 @@
"settings_get",
"portal_info",
"interfaces",
"server_ports",
"endpoint_probe",
"events"
]
}
@@ -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: 'their server is turned off',
paused: 'they are paused',
paused_all: 'everyone is 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,40 +178,57 @@ 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) {
if (home_access(p))
push(steps, step(true, `${t.ip} is this router`, 'Home access includes the router.'));
else if (t.port == 53)
push(steps, step(true, `${t.ip} is this router: DNS is open to everyone`, ''));
else
return stop(steps, step(false, `${t.ip} is this router`, `${p.name} has ${ACCESS_TEXT[p.access]}: only DNS on the router.`));
let portal = m.settings.portal_enabled && (t.port == m.settings.portal_port || (core.portal_http(m) && t.port == core.portal_http_port(m)));
if (t.port == 53)
push(steps, step(true, sprintf(_('%s is this router: DNS is open to everyone'), t.ip), ''));
else if (portal)
push(steps, step(true, sprintf(_('%s is this router: the personal portal is open to everyone'), t.ip), ''));
else if (!home_access(p))
return stop(steps, step(false, sprintf(_('%s is this router'), t.ip), sprintf(p.access == 'lan'
? _('%s has Home only: only DNS and the portal on the router.')
: _('%s has Internet only: only DNS and the portal on the router.'), p.name)));
else {
// Like any home address: only on the networks the person reaches.
let h = core.person_home(srv, p, snap);
if (!h.all && !in_nets(t.ip, h.nets))
return stop(steps, step(false, sprintf(_("%s is this router on a network %s doesn't reach"), t.ip, p.name), reaches(p.name, h.devs)));
push(steps, step(true, sprintf(_('%s is this router'), t.ip),
h.all ? _('Home access includes the router.') : sprintf(_('On one of the networks %s reaches.'), p.name)));
}
push(steps, via(t.ip));
return steps;
}
@@ -167,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) {
@@ -184,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;
}
@@ -214,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). */
@@ -35,19 +36,17 @@ function log(who, msg, level, detail) {
/* ---------- hostnames ---------- */
function host_label(s) {
let l = replace(lc(s), /[^a-z0-9]+/g, '-');
l = replace(l, /^-+|-+$/g, '');
return substr(l, 0, 40) || 'device';
}
export function sync_hosts(m) {
let lines = [];
if (m.settings.hostnames)
for (let id, d in m.devices) {
let p = m.people[d.person];
if (p && ip2int(d.address) != null)
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`);
for (let pid, p in m.people) {
// One label per device, unique within the person (the UI shows the same).
let labels = core.device_labels(m, p);
for (let id in p.devices) {
let d = m.devices[id];
if (ip2int(d.address) != null)
push(lines, `${d.address} ${labels[id]}.${p.id}.${m.settings.domain}`);
}
}
let ls = loop.status();
if (ls.active)
@@ -82,37 +81,44 @@ export function access_sets(m, usage, states) {
return nft.access_sets(m, usage, states);
};
/** Log an access-table failure once per distinct error; true when the table is in place. */
function nft_result(err) {
/**
* Log an access-table failure once per distinct error (with what it means
* for the devices: none loaded while the table is missing, the previous rules
* kept when an older one survived the failed rebuild); the error, or null.
*/
function nft_result(err, present) {
let was = readfile(NFT_ERR);
if (err == null) {
if (was != null)
unlink(NFT_ERR);
return true;
return null;
}
if (was != err) {
log('Access rules', "couldn't load — devices aren't 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);
}
return false;
return err;
}
/**
* The table in place: rebuilt with `full`, otherwise members only, rebuilt
* when that fails (no table yet at boot, or an older shape) — an error only
* when the rebuild fails too.
* when that fails (no table yet at boot, or an older shape). Null, or the
* error when the rebuild fails too.
*/
function load_table(m, sets, full) {
let err = full ? nft.rebuild(m, sets) : nft.update(sets);
if (err != null && !full)
err = nft.rebuild(m, sets);
return nft_result(err);
return nft_result(err, err != null && nft.present());
}
/** Full table rebuild (structure changes: servers, LAN subnets). */
/** Full table rebuild (structure changes: servers, LAN subnets); true when it loaded. */
export function rebuild_nft(m, sets) {
return nft_result(nft.rebuild(m, sets));
let err = nft.rebuild(m, sets);
return nft_result(err, err != null && nft.present()) == null;
};
/** Atomically replace set contents only. */
@@ -131,32 +137,58 @@ export function firewall_drift(m) {
/* ---------- runtime sync ---------- */
/**
* What an admin should hear when a sync did not fully take: the access table
* failed, or a server did not accept its devices (sentences in the caller's
* language, with what nft or awg said). Null when all went in.
*/
function sync_warning(m, table, peers) {
let out = [];
if (table != null)
push(out, nft.present()
? sprintf(_("Access rules couldn't be updated (%s): the previous rules stay, so this change isn't in effect yet."), table)
: sprintf(_("Access rules couldn't load (%s): no device is loaded into the tunnels until they do."), table));
for (let id, r in peers)
if (r != 'ok' && r != 'down')
push(out, sprintf(_("Couldn't load devices into %s: %s."), m.servers[id]?.name ?? id, r));
return length(out) ? join(' ', [ ...out, _('Open Diagnostics → Health.') ]) : null;
}
/*
* With the lock held: access sets first, and devices into the tunnels only
* once the table that limits them is in place.
* With the lock held: access sets first, then devices into the tunnels.
* Fail closed: without the table the firewall would let every loaded device
* reach everything, so while it is missing no device is loaded at all. An
* older table that survived a failed rebuild keeps limiting them with the
* sets it has, and the devices still follow people's states (a revoked one
* leaves).
*/
function locked_sync(m, usage, full) {
let states = states_for(m, usage);
let sets = nft.access_sets(m, usage, states);
let peers = {};
if (load_table(m, sets, full))
peers = awg.sync_peers(m, states);
let table = load_table(m, sets, full);
let peers = awg.sync_peers(m, table == null || nft.present() ? states : {});
sync_hosts(m);
ensure_dir(RUN_DIR);
write_json(`${RUN_DIR}/states.json`, states, 0o644);
return { peers, states };
return { peers, states, table, warning: sync_warning(m, table, peers) };
}
/**
* Runtime sync: devices into the tunnels (AmneziaWG peers), access sets,
* hostnames. Cheap; safe to call often. The model is always read again under
* the lock (`m` is accepted for older callers and not used); `usage` is the
* caller's (the agent holds the live counters).
* caller's (the agent holds the live counters). The result carries `warning`
* (a sentence for the admin) when the sync did not fully take.
*/
export function sync(m, usage) {
return with_lock('apply', () => locked_sync(core.load(), usage ?? core.load_usage()));
};
/** Is the access table loaded (the agent's tick re-syncs when it is not). */
export function table_present() {
return nft.present();
};
/**
* Everything on the router that Dawnline's state is derived from: WAN and
* LAN, the home networks and zones of each server, the netns address and the
@@ -209,10 +241,10 @@ export function apply(opts) {
let s = locked_sync(m, usage, true);
ensure_dir(RUN_DIR);
write_file(NET_SIG, net_signature(m), 0o644);
return { network, firewall, lp, peers: s.peers };
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 };
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). */
File diff suppressed because it is too large. Load diff
@@ -1,9 +1,14 @@
// 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';
export const SOURCES = {
@@ -28,7 +33,69 @@ export function firmware() {
let arch = rel.arch ?? match(readfile('/etc/openwrt_release') ?? '', /DISTRIB_ARCH='([^']*)'/)?.[1];
if (!rel.version || length(target) != 2 || !arch)
return null;
return { tag: `v${rel.version}`, postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, ext: pkg.ext() };
return { tag: `v${rel.version}`, postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, ext: pkg.ext(),
snapshot: match(rel.version, /SNAPSHOT/) != null };
};
/** What was installed, for whom: /etc/dawnline/awg.json (survives a sysupgrade with the data). */
export const RECORD = `${DATA_DIR}/awg.json`;
/** This boot (a new one loads the module on disk), or null when the kernel does not say. */
export function boot_id() {
return trim(readfile('/proc/sys/kernel/random/boot_id') ?? '') || null;
};
/**
* The size in memory of the loaded kernel module, or null when none is
* loaded. sysfs has no version for it, but builds differ in size: a module
* reloaded by hand ends a wait for a reboot (pending()).
*/
export function module_core() {
let n = int(trim(readfile('/sys/module/amneziawg/coresize') ?? ''));
return n > 0 ? n : null;
};
/**
* Remember which build was installed on which kernel. After a firmware
* upgrade the module is gone (it was built for that kernel): Health can then
* say so and offer the build for the new one (dawnline.health). `run` comes
* from an install: prev_gen and prev_core, the module that ran before it
* (module_now()), and reloaded, false while that one stays loaded until the
* next boot. null for a module Dawnline did not install (adopt()).
*/
export function record(source, tag, packages, run) {
ensure_dir(DATA_DIR, 0o700);
write_json(RECORD, {
osrelease: trim(readfile('/proc/sys/kernel/osrelease') ?? ''),
source, tag, packages, installed: time(), boot: boot_id(),
prev_gen: run?.prev_gen ?? null, prev_core: run?.prev_core ?? null, reloaded: run?.reloaded ?? null,
}, 0o600);
};
/**
* A record for a module Dawnline did not install (install.sh, by hand, or
* before Dawnline kept records), so kernel_changed() notices the next
* firmware upgrade: the kernel it is for, source null, `installed` the time
* Dawnline first saw it. Only when there is no record and the module is
* loaded or on disk for the running kernel. The agent calls it when it starts.
*/
export function adopt() {
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
if (stat(RECORD) || (!stat('/sys/module/amneziawg') && (rel == '' || !stat(`/lib/modules/${rel}/amneziawg.ko`))))
return;
record(null, null, null, null);
};
/**
* The firmware the recorded AmneziaWG build was for, when it is not this one
* (and the module is gone): { was, now, tag, source }, else null.
*/
export function kernel_changed() {
let r = read_json(RECORD, null);
let now = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
if (!r?.osrelease || r.osrelease == now)
return null;
return { was: r.osrelease, now, tag: r.tag, source: r.source };
};
/** The file name of a package in a build. */
@@ -41,9 +108,57 @@ export function for_tag(fw, tag) {
return { ...fw, tag, postfix: replace(fw.postfix, fw.tag, tag) };
};
/** AmneziaWG generation of a tools version: 3.x packages carry 3.1, older ones (1.0.x) 2.0. */
/**
* AmneziaWG generation of a package version: 3.x packages carry 3.1; 1.0.x
* ones are 2.0 (S3/S4, I1-I5, header ranges) from July 2025 on, and the
* first generation before that. A kernel module's version carries the kernel
* release in front (6.12.94.3.1.20260906): the AmneziaWG part is at the end.
*/
export function gen(version) {
return version == null ? null : match(version, /^3\./) ? '3.1' : '2.0';
if (version == null)
return null;
let v = match(`${version}`, /([0-9]+\.[0-9]+\.[0-9]{8})(-r?[0-9]+)?$/)?.[1] ?? `${version}`;
if (match(v, /^3\./))
return '3.1';
if (match(v, /^1\.0\.2024/) || match(v, /^1\.0\.20250[1-6]/))
return '1.0';
return '2.0';
};
/**
* An installed update that waits for a reboot: the install could not swap
* the kernel module (the old one stayed loaded), this is still the boot it
* ran in, and the module loaded is still the one from before it (core:
* module_core() now). Pure: rec is the record or null.
*/
export function pending(rec, boot, core) {
return rec?.reloaded === false && rec.boot != null && rec.boot == boot && core != null && rec.prev_core == core;
};
/**
* The AmneziaWG generation of the kernel module that runs: the one from
* before the install while it waits for a reboot (pending(); null when that
* module had no package), else the installed package's version (gen()).
* Pure, with the record, this boot and module_core() passed in.
*/
export function running_gen(rec, boot, core, version) {
return pending(rec, boot, core) ? rec.prev_gen : gen(version);
};
/**
* The kernel module loaded now, taken before an install changes packages:
* { core, gen, pending }. core is null when none is loaded; gen is what it
* runs (running_gen(), from `version`, the kmod-amneziawg package installed
* now); pending, an earlier update that still waits for a reboot.
*/
export function module_now(version) {
let rec = read_json(RECORD, null), boot = boot_id(), core = module_core();
return { core, gen: core == null ? null : running_gen(rec, boot, core, version), pending: pending(rec, boot, core) };
};
/** The installed AmneziaWG update waits for a reboot (pending(), for Health and Components). */
export function waits_for_reboot() {
return pending(read_json(RECORD, null), boot_id(), module_core());
};
/** The installed AmneziaWG packages: { name: version | null }. */
@@ -1,55 +1,70 @@
// 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 } from 'fs';
import { readfile, stat, unlink, lsdir, rename } from 'fs';
import { cursor } from 'uci';
import {
q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
import * as health from 'dawnline.health';
import { _ } from 'dawnline.i18n';
const BACKUP_DIR = `${DATA_DIR}/backups`;
const KEEP_BACKUPS = 10;
/**
* How many backups of each kind stay (the newest): the nightly ones must not
* push out what the admin made by hand or what a removal left behind.
*/
const KEEP = { manual: 10, auto: 7, 'pre-delete': 5, 'pre-remove': 3, 'pre-update': 3, 'pre-restore': 3, 'pre-import': 3 };
const NAME = /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/;
/** What a backup holds (paths inside the archive, relative to /). */
const FILES = [ 'etc/config/dawnline', 'etc/dawnline/usage.json', 'etc/dawnline/events.json' ];
/**
* Kinds that hold the config alone (about 20 KB): the history can be a
* megabyte or more, and these are made often and never to bring history
* back. Manual, pre-restore and pre-import backups protect the data that is
* about to be replaced, so they take everything.
*/
const CONFIG_ONLY = [ 'auto', 'pre-delete', 'pre-remove', 'pre-update' ];
/** The unpacked size a backup may have (the upload itself is limited to 4 MB). */
const MAX_UNPACKED = 16 * 1024 * 1024;
/* ---------- checking a configuration before it is used ---------- */
/**
* What is wrong with the servers of a configuration about to replace the
* current one (cursor `c` holds it): each must have a valid, unique interface
* name that is not one of the router's own interfaces, a free subnet and a
* unique port. [] when it can be used.
* What is wrong with a configuration about to replace the current one
* (cursor `c` holds it): each server must have a valid, unique interface
* name that is not one of the router's own interfaces, a free subnet, a
* unique port and disguise values AmneziaWG takes (awg.obf_unsafe), and the
* people and devices must be consistent (core.model_errors). [] when it can
* be used.
*/
export function config_errors(c) {
let m = core.load(c);
let errs = [];
let errs = core.model_errors(m);
let nc = cursor();
nc.load('network');
let foreign = health.foreign_subnets();
let internal = values(net.INTERNAL);
let ifnames = {}, ports = {}, subnets = [];
for (let id, srv in m.servers) {
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);
@@ -63,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). */
@@ -92,39 +107,51 @@ export function backup_list() {
};
/**
* Make a backup now; returns its name. The oldest beyond KEEP_BACKUPS are
* removed, except `keep` (the backup being restored, which must survive the
* backup made just before restoring it).
* Make a backup now; returns its name. Written whole or not at all (a half
* archive from a full flash never shows up as a backup). Of each kind the
* oldest beyond KEEP are removed, except `keep` (the backup being restored,
* which must survive the backup made just before restoring it).
*/
export function backup_create(reason, keep) {
let kind = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? reason : 'manual';
let config_only = index(CONFIG_ONLY, kind) >= 0;
// Flush live counters first so the backup has current usage.
if (!config_only) {
let u = read_json(`${RUN_DIR}/usage.json`, null);
if (u)
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
live.persist_events();
}
ensure_dir(BACKUP_DIR, 0o700);
let t = localtime();
let tag = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? `-${reason}` : '';
let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, tag);
let files = join(' ', map(filter(FILES, (f) => file_exists(`/${f}`)), q));
let r = sh(`tar -czf ${q(BACKUP_DIR + '/' + name)} -C / ${files}`);
if (r.code != 0)
die(`Backup failed: ${trim(r.out)}`);
let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, kind == 'manual' ? '' : `-${kind}`);
let want = config_only ? [ FILES[0] ] : FILES;
let files = join(' ', map(filter(want, (f) => file_exists(`/${f}`)), q));
// Not a NAME until it is complete.
let tmp = `${BACKUP_DIR}/.${name}.tmp`;
let r = sh(`tar -czf ${q(tmp)} -C / ${files}`);
if (r.code != 0 || !rename(tmp, `${BACKUP_DIR}/${name}`)) {
unlink(tmp);
let why = trim(r.out);
die(why ? sprintf(_('Backup failed: %s'), why) : _('Backup failed: the archive could not be written (is the flash full?)'));
}
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
let all = backup_list();
let old = filter(all, (b) => b.name != keep && b.name != name);
let room = KEEP_BACKUPS - 1 - (length(old) < length(all) - 1 ? 1 : 0);
for (let i = room; i < length(old); i++)
unlink(`${BACKUP_DIR}/${old[i].name}`);
let by_kind = {};
for (let b in backup_list())
if (b.name != keep && b.name != name)
push(by_kind[b.reason] ??= [], b);
for (let k, list in by_kind)
for (let i = KEEP[k] ?? 3; i < length(list); i++)
unlink(`${BACKUP_DIR}/${list[i].name}`);
return name;
};
function backup_path(name) {
if (!match(name ?? '', NAME))
die('Invalid backup name.');
die(_('Invalid backup name.'));
let p = `${BACKUP_DIR}/${name}`;
if (!file_exists(p))
die('Backup not found.');
die(_('Backup not found.'));
return p;
}
@@ -135,34 +162,44 @@ 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.'));
}
/** Put the files unpacked in `dir` in place, under the config lock. */
/**
* Put the files unpacked in `dir` in place, under the config lock. The
* config goes first: when it cannot be written nothing else is touched, and
* a data file that fails afterwards is reported, not ignored.
*/
function install_files(dir) {
ensure_dir(DATA_DIR, 0o700);
let l = lock('config');
try {
for (let f in FILES) {
let data = readfile(`${dir}/${f}`);
if (data != null)
write_file(`/${f}`, data, 0o600);
if (data != null && !write_file(`/${f}`, data, 0o600))
die(sprintf(_("Couldn't write %s. Is the flash full?"), `/${f}`));
}
}
catch (e) {
unlock(l);
die(e.message);
}
unlock(l);
system('chmod 600 /etc/config/dawnline');
@@ -175,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);
@@ -185,9 +222,11 @@ export function backup_restore(name, path) {
die(e.message);
}
system(`rm -rf ${q(dir)}`);
// Live counters must follow the restored file.
// Live counters must follow the restored file: the agent reloads them from
// flash on its next tick (its watcher may write the old ones again before).
unlink(`${RUN_DIR}/usage.json`);
unlink(`${RUN_DIR}/events.json`);
write_file(live.USAGE_RELOAD, `${time()}`, 0o600);
return apply.apply();
};
@@ -203,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);
@@ -238,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
@@ -279,7 +318,9 @@ export function import_json(data) {
system(`rm -rf ${q(dir)}`);
backup_create('pre-import');
let l = lock('config');
write_file('/etc/config/dawnline', text, 0o600);
let ok = write_file('/etc/config/dawnline', text, 0o600);
unlock(l);
if (!ok)
die(sprintf(_("Couldn't write %s. Is the flash full?"), '/etc/config/dawnline'));
return apply.apply();
};
@@ -4,10 +4,12 @@
import { cursor } from 'uci';
import {
valid_name, valid_key, valid_host, valid_date, slugify, 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';
export const CONFIG = 'dawnline';
@@ -20,6 +22,8 @@ export const CONFIG = 'dawnline';
export const BLOCKED = `${RUN_DIR}/netifd-blocked.json`;
export const ACCESS = [ 'lan', 'internet', 'both' ];
export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ];
/** Kinds that mostly live on mobile networks: their configurations carry a smaller MTU. */
export const MOBILE_KINDS = [ 'phone', 'tablet' ];
/** Devices of different people reaching each other: never, everyone with home access, or within a circle. */
export const MESH = [ 'off', 'all', 'circles' ];
/** Circle colours (index into the admin palette). */
@@ -66,29 +70,30 @@ export function open_cursor() {
export function load(c) {
c ??= open_cursor();
let s = c.get_all(CONFIG, 'settings') ?? {};
// Types, defaults and ranges of the settings live in dawnline.schema (one
// place): what is read here is what settings_update would have accepted.
let g = (k) => schema.get(s, k);
let m = {
settings: {
portal_enabled: bool(s.portal_enabled, false),
portal_port: toint(s.portal_port, 8443),
portal_host: s.portal_host ?? '',
portal_enabled: g('portal_enabled'),
portal_port: g('portal_port'),
portal_host: g('portal_host'),
// More addresses for the same links (the main one is portal_host).
portal_alt: filter(type(s.portal_alt) == 'array' ? s.portal_alt : s.portal_alt ? [ s.portal_alt ] : [], (x) => x != ''),
portal_cert: s.portal_cert ?? '',
portal_key: s.portal_key ?? '',
portal_title: s.portal_title ?? 'Dawnline',
portal_alt: g('portal_alt'),
portal_cert: g('portal_cert'),
portal_key: g('portal_key'),
// Where unknown portal links go instead of a bare 404 (empty = 404).
portal_redirect: s.portal_redirect ?? '',
paused_all: bool(s.paused_all, false),
default_device_limit: toint(s.default_device_limit, 3),
geo_enabled: bool(s.geo_enabled, true),
geo_provider: s.geo_provider == 'ipapi.co' ? 'ipapi.co' : 'ipwho.is',
hostnames: bool(s.hostnames, true),
domain: s.domain ?? 'lan',
log_connections: bool(s.log_connections, true),
portal_redirect: g('portal_redirect'),
default_device_limit: g('default_device_limit'),
geo_enabled: g('geo_enabled'),
geo_provider: g('geo_provider'),
hostnames: g('hostnames'),
domain: g('domain'),
log_connections: g('log_connections'),
// Repair tunnels and services on its own (the agent, every minute).
watchdog: bool(s.watchdog, true),
watchdog: g('watchdog'),
// Second DNS for "home names" devices, used by the device when the tunnel is down.
home_dns_fallback: s.home_dns_fallback == 'none' ? '' : (s.home_dns_fallback ?? '1.1.1.1'),
home_dns_fallback: g('home_dns_fallback'),
// Settings → Updates (automatic checks and updates of the components).
updates: updates_policy(s),
// Raw retention values; dawnline.live policy() interprets them.
@@ -115,7 +120,8 @@ export function load(c) {
port: toint(r.port, 51820),
subnet: r.subnet ?? '',
endpoint: r.endpoint ?? '',
mtu: toint(r.mtu, 1380),
// 0 = automatic (tunnel_mtu, device_mtu).
mtu: toint(r.mtu, 0),
dns: list(r.dns),
keepalive: toint(r.keepalive, 25),
private_key: r.private_key ?? '',
@@ -156,6 +162,8 @@ export function load(c) {
access: index(ACCESS, r.access) >= 0 ? r.access : 'internet',
device_limit: toint(r.device_limit, m.settings.default_device_limit),
code: r.code ?? '',
// When the personal link was last made (0 for links from before this was kept).
code_set: toint(r.code_set, 0),
expires: r.expires ?? '',
quota_gb: num(r.quota_gb, 0),
quota_period: r.quota_period == 'total' ? 'total' : 'month',
@@ -191,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])
@@ -234,23 +249,23 @@ function within_hours(h, ts) {
return h[0] < h[1] ? (cur >= h[0] && cur < h[1]) : (cur >= h[0] || cur < h[1]);
}
/** Bytes used in the person's quota period. */
export function person_usage(p, usage) {
/** Bytes used in the person's quota period (the month of `ts`, default now). */
export function person_usage(p, usage, ts) {
let u = usage?.people?.[p.id];
if (!u)
return 0;
if (p.quota_period == 'total')
return (u.total?.[0] ?? 0) + (u.total?.[1] ?? 0);
let mm = u.months?.[month_key()];
let mm = u.months?.[month_key(ts)];
return mm ? mm[0] + mm[1] : 0;
};
/** Quota in bytes for the current period (base + this month's bonus), 0 = unlimited. */
export function person_quota(p) {
/** Quota in bytes for the period of `ts` (default now): base + that month's bonus, 0 = unlimited. */
export function person_quota(p, ts) {
if (!(p.quota_gb > 0))
return 0;
let gb = p.quota_gb;
if (p.bonus_gb > 0 && p.bonus_month == month_key())
if (p.bonus_gb > 0 && p.bonus_month == month_key(ts))
gb += p.bonus_gb;
return gb * 1073741824;
};
@@ -262,24 +277,16 @@ export function person_expired(p, ts) {
return end != null && (ts ?? time()) > end;
};
/**
* Effective state of a person: 'active', or why they are off:
* 'paused' (admin), 'paused_all', 'expired', 'quota', 'hours', 'no_server'.
*/
export function person_state(m, p, usage, ts) {
/** The person's state whatever their server is doing (paused, expired, …, or 'active'). */
export function own_state(m, p, usage, ts) {
ts ??= time();
let srv = m.servers[p.server];
if (!srv || !srv.enabled)
return 'no_server';
if (p.paused)
return 'paused';
if (m.settings.paused_all)
return 'paused_all';
// "notify" keeps access after the end date (shown in Overview and People).
if (person_expired(p, ts) && p.expire_action != 'notify')
return 'expired';
let quota = person_quota(p);
if (quota > 0 && person_usage(p, usage) >= quota)
let quota = person_quota(p, ts);
if (quota > 0 && person_usage(p, usage, ts) >= quota)
return 'quota';
let h = parse_hours(p.hours);
if (h && !within_hours(h, ts))
@@ -287,6 +294,20 @@ export function person_state(m, p, usage, ts) {
return 'active';
};
/**
* Effective state of a person: 'active', or why they are off:
* 'paused' (admin), 'expired', 'quota', 'hours', 'no_server',
* 'server_off' (their server is turned off: about the server, not the person).
*/
export function person_state(m, p, usage, ts) {
let srv = m.servers[p.server];
if (!srv)
return 'no_server';
if (!srv.enabled)
return 'server_off';
return own_state(m, p, usage, ts);
};
export function load_usage() {
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} });
};
@@ -344,6 +365,49 @@ export function alloc_address(m, srv) {
/* ---------- what clients get ---------- */
/*
* Automatic MTU. A path is assumed to carry 1460 bytes (1500 less PPPoE,
* 464XLAT or DS-Lite), the tunnel's own headers take 80 over IPv6, and
* AmneziaWG's S4 adds its bytes to every data packet (its padding and random
* trailers stay within the largest packet already seen, so they cost
* nothing). Phones and tablets get 1280, the IPv6 minimum: mobile paths vary.
*/
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 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 || '';
};
@@ -447,35 +511,35 @@ export function new_code() {
export function create_person(c, m, a) {
if (!valid_name(a.name))
fail('Enter a name (up to 48 characters).');
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);
@@ -483,6 +547,7 @@ export function create_person(c, m, a) {
c.set(CONFIG, slug, 'access', access);
c.set(CONFIG, slug, 'device_limit', `${limit}`);
c.set(CONFIG, slug, 'code', new_code());
c.set(CONFIG, slug, 'code_set', `${time()}`);
c.set(CONFIG, slug, 'created', `${time()}`);
if (a.expires)
c.set(CONFIG, slug, 'expires', a.expires);
@@ -500,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('Enter a name (up to 48 characters).');
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)
@@ -553,21 +619,21 @@ 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)
set('note', substr(trim(a.note), 0, 500));
set('note', ucut(trim(a.note), 500));
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
@@ -576,11 +642,29 @@ 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
// needs its configuration again); circles and home networks are the old
// server's and go.
if (a.server != null && a.server != '' && a.server != p.server) {
if (!m.servers[a.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(sprintf(_('No free address left on %s.'), m.servers[a.server].name));
m.devices[did].address = addr;
c.set(CONFIG, did, 'address', addr);
}
c.delete(CONFIG, id, 'circle');
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
@@ -594,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);
@@ -636,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;
@@ -646,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)
@@ -672,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)
@@ -684,48 +816,185 @@ 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);
};
const PRIVATE_NETS = map([ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
/** The parsed subnet lies inside one of the private ranges. */
export function private_cidr(c) {
for (let p in PRIVATE_NETS)
if (c.net >= p.net && c.net + c.size <= p.net + p.size)
return true;
return false;
};
/** Validate a server definition (as loaded) against the rest of the router. */
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;
};
/** Someone else already forwards this TCP port from outside (a port forward we must not take over). */
export function wan_port_taken(port) {
/**
* What is wrong inside a model as a whole, beyond each server: devices with
* 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, 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) {
if (p.server != '' && !m.servers[p.server])
push(errs, sprintf(_('Person %s: server %s does not exist.'), p.name, p.server));
if (p.circle != '' && !m.circles[p.circle])
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, sprintf(_('Person %s: home service %s does not exist.'), p.name, sid));
if (p.code != '') {
if (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];
if (!p) {
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))
say(_('Device %s of %s: the public key is not a key.'));
if (d.private_key != '' && !valid_key(d.private_key))
say(_('Device %s of %s: the private key is not a key.'));
if (d.preshared_key != '' && !valid_key(d.preshared_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) {
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))
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)
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}`;
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, sprintf(_('Circle %s: server %s does not exist.'), ci.name, ci.server));
return errs;
};
/**
* Give every device on a server an address in `subnet` (the server's new
* tunnel network), lowest first: used by server_update when the network
* changes. Each device then needs its configuration again (the address is
* in it). Fails when the subnet cannot hold them.
*/
export function renumber_server(c, m, srv, subnet) {
srv.subnet = subnet;
for (let pid, p in m.people)
if (p.server == srv.id)
for (let did in p.devices)
m.devices[did].address = '';
for (let pid, p in m.people)
if (p.server == srv.id)
for (let did in p.devices) {
let addr = alloc_address(m, srv);
if (!addr)
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);
}
c.set(CONFIG, srv.id, 'subnet', subnet);
};
/**
* The DNS labels of a person's devices, { device id: label }, unique within
* the person: two devices whose names give one label ("iPhone" and
* "iPhone!", or two Cyrillic names) get -2, -3 by age. Hostnames in
* /tmp/hosts (dawnline.apply) and the ones the UI shows (dawnline.view) both
* come from here, so what is shown resolves.
*/
export function device_labels(m, p) {
let out = {}, used = {};
let devs = sort(map(p.devices, (id) => m.devices[id]), (a, b) => (a.created - b.created) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
for (let d in devs) {
let base = host_label(d.name), l = base;
for (let n = 2; used[l]; n++)
l = `${substr(base, 0, 37)}-${n}`;
used[l] = true;
out[d.id] = l;
}
return out;
};
/**
* Port forwards from `zone` for `proto` that aren't Dawnline's: [{ from, to, name }].
* A forwarded port never reaches the router itself, so nothing here can listen on it.
*/
export function wan_forwards(zone, proto) {
let c = cursor();
c.load('firewall');
let taken = false;
let out = [];
c.foreach('firewall', 'redirect', (r) => {
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT')
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', /[ ,]+/);
if (index(protos, proto) < 0 && index(protos, 'all') < 0 && index(protos, 'any') < 0)
return;
for (let p in split(`${r.src_dport ?? ''}`, /[ ,]+/)) {
let m = match(p, /^(\d+)([-:](\d+))?$/);
if (m && +m[1] <= port && port <= +(m[3] || m[1]))
taken = true;
if (m)
push(out, { from: +m[1], to: +(m[3] || m[1]), name: r.name ?? r['.name'] });
}
});
return taken;
return out;
};
/** Every address the links use, the main one first. */
@@ -767,7 +1036,9 @@ export function portal_link(m, p, host) {
return `http://${host}${hp == 80 ? '' : `:${hp}`}/${p.code}`;
}
let pp = portal_public_port(m);
return `https://${host}${pp == 443 ? '' : `:${pp}`}/${p.code}`;
// An IPv6 address needs its brackets in a URL.
let h = index(host, ':') >= 0 && !match(host, /^\[/) ? `[${host}]` : host;
return `https://${h}${pp == 443 ? '' : `:${pp}`}/${p.code}`;
};
/** The main link (QR, invite card, Copy link). */
@@ -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,33 +33,44 @@ 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) }));
apply.sync();
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind,
{ by, keys: awg.new_keys(opts.public_key || null), lan_bypass: opts.lan_bypass === true }));
let s = apply.sync();
let m = core.load();
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
awg.mark_issued(m, id);
return { id, config: awg.client_config(m, m.devices[id]) };
return { id, config: awg.client_config(m, m.devices[id]), warning: s.warning };
};
/**
* 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) => {
@@ -89,15 +112,35 @@ export function rotate(id, opts) {
});
// The device a portal page came through would lose its tunnel before the
// answer gets out: load the new key a moment after answering.
let s = null;
if (opts.defer)
sh_bg('sleep 3; /usr/bin/dawnline sync');
else
apply.sync();
s = apply.sync();
let m = core.load();
let d = m.devices[id];
live.add_event({ type: 'device_keys', person: d.person, device: id, detail: d.name, by });
awg.mark_issued(m, id);
return awg.client_config(m, d);
let cfg = awg.client_config(m, d);
if (s?.warning)
cfg.warning = s.warning;
return cfg;
}
/**
* Set a device up from scratch (a new phone, the app reinstalled, settings
* the admin changed; the portal's Reconnect and the admin's New keys): new
* keys, so the configuration it holds stops working with the sync, and it
* counts as not set up until it connects with the new one. The usage keeps
* the old keys' last handshake: awg.handshake_since hides it. Returns the new
* configuration (with `warning` when the sync did not fully take).
*/
export function reconnect(id, opts) {
opts ??= {};
let cfg = rotate(id, opts);
// A deferred sync (the page came through this device) lets the old keys live a few seconds more.
awg.mark_reconnect(core.load(), id, time() + (opts.defer ? 5 : 0));
return cfg;
};
/** Remove a device. Returns the runtime sync. */
@@ -5,11 +5,12 @@
// named dawnline_* are ever changed.
import { readfile, unlink } from 'fs';
import { q, sh, sh_out, uniq, uci_put, uci_section, ack_config, write_file, RUN_DIR } from 'dawnline.util';
import { q, sh, sh_out, uniq, in_nets, uci_put, uci_section, ack_config, write_file, RUN_DIR } from 'dawnline.util';
import { cursor } from 'uci';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as nft from 'dawnline.nft';
import * as loop from 'dawnline.loop';
const LOOP_ZONE = 'dl_loop';
/*
@@ -42,12 +43,33 @@ export function sync(m, dry) {
let snap = net.snapshot(true);
let portal_zone = null, want_loop = false;
// Where tunnel DNS is sent (dawnline.nft): into the netns for home names
// while any server runs "like a home device", and to the LAN's DNS for
// everyone else. A server that does not forward to those zones on its own
// gets a rule for port 53 alone.
let any_loop = length(filter(values(m.servers), (s) => s.lan_like && length(core.tunnels(s)))) > 0;
let lan_dns = loop.lan_dns();
let lan_dns_zone = null;
if (lan_dns)
for (let dev, d in snap.devices)
if (d.zone && in_nets(lan_dns, d.nets ?? []))
lan_dns_zone ??= d.zone;
for (let id, srv in m.servers) {
if (!length(core.tunnels(srv)))
continue;
let z = `dawnline_${id}`;
let sn = net.server_net(srv, snap);
portal_zone ??= sn.wan.zone;
if (!srv.lan_like && any_loop)
sec(`${z}_loopdns`, 'rule', {
name: `Dawnline-${srv.ifname}-names`, src: srv.ifname, dest: LOOP_ZONE,
proto: 'tcp udp', dest_port: 53, target: 'ACCEPT',
});
if (lan_dns_zone && lan_dns_zone != srv.ifname && index(sn.zones, lan_dns_zone) < 0)
sec(`${z}_landns`, 'rule', {
name: `Dawnline-${srv.ifname}-dns`, src: srv.ifname, dest: lan_dns_zone, dest_ip: lan_dns,
proto: 'tcp udp', dest_port: 53, target: 'ACCEPT',
});
sec(`${z}_zone`, 'zone', {
// Forward within the zone (device to device) is decided by the inet dawnline table.
name: srv.ifname, network: [ srv.ifname ],
@@ -104,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) {
@@ -148,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);
@@ -162,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] };
@@ -1,14 +1,21 @@
// Dawnline — city-level locations for the admin map.
//
// Client addresses are looked up once with a third-party service (ipwho.is,
// ipapi.co as fallback) and cached in DATA_DIR/geo.json. Only the agent
// performs lookups, a few per minute at most; the UI reads the cache.
// ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on
// flash (DATA_DIR/geo.json) by flush() about hourly, like the usage
// counters. Only the agent performs lookups, in a child process (the network
// may take seconds; neither its watcher nor its tick waits for them) and
// merges them into the cache itself; the UI reads the cache.
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR } from 'dawnline.util';
import { stat } from 'fs';
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util';
const CACHE = `${DATA_DIR}/geo.json`;
const CACHE = `${RUN_DIR}/geo.json`;
const SAVED = `${DATA_DIR}/geo.json`;
const TTL = 30 * 86400;
const RETRY = 86400;
// Entries kept at least; addresses still shown are never pushed out (merge).
const CAP = 500;
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
const PRIVATE4 = map([ [ '0.0.0.0', 8 ], [ '10.0.0.0', 8 ], [ '100.64.0.0', 10 ], [ '127.0.0.0', 8 ], [ '169.254.0.0', 16 ],
@@ -30,16 +37,30 @@ export function is_public(ip) {
};
export function load() {
return read_json(CACHE, null) ?? { ips: {}, home: null };
return read_json(CACHE, null) ?? read_json(SAVED, null) ?? { ips: {}, home: null };
};
/** The live copy (tmpfs); flush() puts it on flash. */
export function save(cache) {
ensure_dir(DATA_DIR, 0o700);
ensure_dir(RUN_DIR);
write_json(CACHE, cache, 0o600);
};
/** Copy the live cache to flash when it is newer (the agent, about hourly and on a clean stop). */
export function flush() {
let live = stat(CACHE);
if (!live || live.mtime <= (stat(SAVED)?.mtime ?? 0))
return false;
let c = read_json(CACHE, null);
if (!c)
return false;
ensure_dir(DATA_DIR, 0o700);
write_json(SAVED, c, 0o600);
return true;
};
function fetch_json(url) {
let out = sh_out(`uclient-fetch -q -T 8 -O - ${q(url)}`);
let out = sh_out(`uclient-fetch -q -T 5 -O - ${q(url)}`);
if (!out)
return null;
try {
@@ -79,36 +100,69 @@ export function lookup(provider, ip) {
};
/**
* Resolve up to `max` addresses that are missing or stale. Returns true when
* the cache changed (the caller saves it).
* The public addresses of `ips` the cache does not know or knows from too
* long ago (a failed lookup is retried after a day), once each and in order.
* Returns an empty array when there is nothing to look up.
*/
export function resolve(settings, cache, ips, max) {
let now = time(), changed = false, done = 0;
export function stale(cache, ips, ts) {
let now = ts ?? time(), out = [], seen = {};
for (let ip in ips) {
if (done >= max)
break;
if (!is_public(ip))
if (seen[ip] || !is_public(ip))
continue;
seen[ip] = true;
let c = cache.ips[ip];
if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL)))
continue;
let r = lookup(settings.geo_provider, ip);
push(out, ip);
}
return out;
};
/**
* Look up at most `max` of `ips`, within `budget` seconds (each lookup may
* wait on the network). Returns { ip: place, or false when the services had
* nothing } for the ones tried. Network only, no cache: the agent runs it in
* a child process and merges the result itself.
*/
export function lookup_all(provider, ips, max, budget) {
let started = time(), out = {}, done = 0;
for (let ip in ips) {
if (done >= max || (budget != null && time() - started >= budget))
break;
let r = lookup(provider, ip);
done++;
changed = true;
if (r) {
if (r)
delete r.ip;
r.ts = now;
cache.ips[ip] = r;
out[ip] = r ?? false;
}
else
cache.ips[ip] = { fail: now };
return out;
};
/**
* Put lookup_all() results into the cache. Returns true when the cache
* changed (the caller saves it). `shown` is what is still on the map: the
* cache is kept bounded by dropping other entries only, oldest first, so a
* lookup is never repeated for an address that is still on the map.
*/
export function merge(cache, found, shown, ts) {
let now = ts ?? time(), changed = false;
for (let ip, r in found) {
if (!is_public(ip))
continue;
cache.ips[ip] = r ? { ...r, ts: now } : { fail: now };
changed = true;
}
// Keep the cache bounded: drop the oldest entries beyond 500.
let keep = {};
for (let ip in shown)
keep[ip] = true;
let all = keys(cache.ips);
if (length(all) > 500) {
all = sort(all, (a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
for (let i = 0; i < length(all) - 500; i++)
delete cache.ips[all[i]];
if (length(all) > CAP) {
let other = sort(filter(all, (ip) => !keep[ip]),
(a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
for (let i = 0; i < length(all) - CAP && i < length(other); i++) {
delete cache.ips[other[i]];
changed = true;
}
}
return changed;
};
@@ -130,6 +184,13 @@ export function place(cache, ip) {
return (c && !c.fail) ? c : null;
};
/** "City · ISP" for the activity log; null for no place. */
export function label(pl) {
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
};
export function clear() {
save({ ips: {}, home: null });
ensure_dir(DATA_DIR, 0o700);
write_json(SAVED, { ips: {}, home: null }, 0o600);
};
@@ -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;
}
@@ -78,14 +79,17 @@ function cached(key, ttl, fn) {
/* ---------- releases ---------- */
function slim(x) {
let digests = {};
for (let a in x.assets ?? [])
let digests = {}, ids = {};
for (let a in x.assets ?? []) {
if (match(a.digest ?? '', /^sha256:[0-9a-f]{64}$/))
digests[a.name] = substr(a.digest, 7);
if (type(a.id) == 'int' && a.id > 0)
ids[a.name] = a.id;
}
return {
tag: x.tag_name, name: x.name ?? x.tag_name, published: x.published_at ?? null,
prerelease: !!x.prerelease, url: x.html_url ?? null, body: substr(x.body ?? '', 0, 12000),
assets: map(x.assets ?? [], (a) => a.name), digests,
assets: map(x.assets ?? [], (a) => a.name), digests, ids,
};
}
@@ -193,6 +197,25 @@ export function sha256(path) {
return match(run(`sha256sum ${q(path)}`).out, /^([0-9a-f]{64})/)?.[1];
};
/** A release file's URL on github.com in parts: { repo, tag, name }, or null for any other URL. */
export function release_file(url) {
let m = match(url ?? '', /^https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\/releases\/download\/([^\/?#]+)\/([^\/?#]+)$/);
return m ? { repo: m[1], tag: m[2], name: m[3] } : null;
};
/** The same file through the API (api.github.com), when its release is known; else null. */
function asset_api_url(url) {
let f = release_file(url);
if (!f)
return null;
let id = null;
try {
id = release(f.repo, f.tag)?.ids?.[f.name];
}
catch (e) {}
return id ? `https://api.github.com/repos/${f.repo}/releases/assets/${id}` : null;
}
/**
* Download to a file. o: { sha256, mirrors, log }. Direct first; mirrors
* only when the sha256 is known (from the API) and mirrors are allowed. A
@@ -202,25 +225,33 @@ export function sha256(path) {
export function download(url, dest, o) {
o ??= {};
let want = o.sha256 ? lc(o.sha256) : null;
let tries = [ url ];
let curl = have_curl();
let tries = [];
// Without curl a release file comes through the API first: github.com's redirect to it carries a
// Content-Security-Policy header that can outgrow uclient-fetch's 4 KB line buffer, and it stalls there.
let api = curl ? null : asset_api_url(url);
if (api)
push(tries, { u: api, accept: 'application/octet-stream' });
push(tries, { u: url });
let direct = length(tries);
if (want && o.mirrors && match(url, /^https:\/\/(github\.com|raw\.githubusercontent\.com)\//))
for (let m in MIRRORS)
push(tries, m + url);
for (let i, u in tries) {
let host = replace(u, /^https:\/\/([^\/]+)\/.*$/, '$1');
if (i > 0)
o.log?.(`Trying mirror ${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)}`);
push(tries, { u: m + url, mirror: true });
for (let i, t in tries) {
let host = replace(t.u, /^https:\/\/([^\/]+)\/.*$/, '$1');
if (t.mirror)
o.log?.(sprintf(_('Trying mirror %s'), host));
let r = curl
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 1 -o ${q(dest)} ${q(t.u)}`)
: run(`uclient-fetch -q -T 30 ${t.accept ? `--header=${q('Accept: ' + t.accept)} ` : ''}-O ${q(dest)} ${q(t.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`);
return t.u;
o.log?.(sprintf(_("Warning: %s sent a file that does not match GitHub's sha256, discarded"), host));
}
system(`rm -f ${q(dest)}`);
if (i == 0 && length(tries) > 1)
o.log?.('GitHub did not answer, trying mirrors');
if (i == direct - 1 && length(tries) > direct)
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';
@@ -11,6 +13,7 @@ import * as fw from 'dawnline.fw';
import * as loop from 'dawnline.loop';
import * as net from 'dawnline.net';
import * as awg from 'dawnline.awg';
import * as builds from 'dawnline.awg_builds';
import * as lookup from 'dawnline.lookup';
import * as pc from 'dawnline.portalcert';
@@ -42,12 +45,59 @@ export function needs() {
};
};
export function udp_listening(port) {
let hex = sprintf(':%04X ', port);
// " 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' ])
if (index(readfile(f) ?? '', hex) >= 0)
return true;
return false;
for (let line in split(readfile(f) ?? '', '\n')) {
let m = match(line, UDP_UNCONNECTED);
if (m)
out[hex(m[1])] = true;
}
return map(keys(out), (k) => +k);
};
// netstat's columns and the port of "0.0.0.0:53" / ":::53". Module constants,
// compiled once, not for each socket.
const BLANKS = /[ \t]+/, PORT_SUFFIX = /:([0-9]+)$/;
/**
* Programs on 'tcp' or 'udp' ports, our portal left out: { port: "dnsmasq" }.
* Kernel sockets (a tunnel's) have no name.
*/
function port_programs(proto) {
let out = {};
for (let line in split(sh_out(`netstat -ln${proto == 'tcp' ? 't' : 'u'}p 2>/dev/null`) ?? '', '\n')) {
let f = split(trim(line), BLANKS);
if (f[0] != proto && f[0] != `${proto}6`)
continue;
let m = match(f[3] ?? '', PORT_SUFFIX);
let owner = split(f[length(f) - 1], '/');
if (!m || !owner[1] || out[m[1]])
continue;
// Our own portal runs as a dedicated uhttpd instance.
if (index(readfile(`/proc/${+owner[0]}/cmdline`) ?? '', '/usr/share/dawnline/portal') >= 0)
continue;
out[m[1]] = owner[1];
}
return out;
}
export function udp_port_programs() {
return port_programs('udp');
};
export function tcp_port_programs() {
return port_programs('tcp');
};
export function udp_listening(port) {
return index(udp_bound(), +port) >= 0;
};
export function tcp_listening(port) {
@@ -116,6 +166,11 @@ function other_subnets(srv_id) {
};
/** Subnets in use on the router except the given server's (null: all of them). */
/** The router's IPv4 networks, Dawnline's tunnels included: [{ iface, cidr }]. */
export function networks() {
return other_subnets(null);
};
export function used_subnets(except_srv) {
return map(other_subnets(except_srv), (x) => x.cidr);
};
@@ -129,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 };
}
/**
@@ -177,54 +201,307 @@ 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);
/** 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) {
if (!host)
return check(id, title, 'error', 'No public address: devices will not know where to connect.');
let ips = lookup.resolve(host);
let wan = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
/** What kind of IPv4 the WAN has: public, cgnat (100.64/10), private (behind another router), or none. */
export function wan_kind(wan) {
let wc = wan ? ip2int(wan) : null;
let cgnat = wc != null && length(filter(PRIVATE, (c) => in_cidr(wc, c))) > 0;
if (!length(ips))
return check(id, title, 'error', `${host} does not resolve.`);
if (cgnat)
return check(id, title, 'warn', `WAN address ${wan} is private: forward ${proto_note} on the upstream router, or devices cannot connect.`);
if (length(filter(ips, (a) => cloudflare_ip(a))))
return check(id, title, 'error', `${host} → ${join(', ', ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.`);
if (wan && index(ips, wan) < 0)
return check(id, title, 'warn', `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`);
return check(id, title, 'ok', `${host} → ${join(', ', ips)}`);
if (wc == null)
return 'none';
if (in_cidr(wc, PRIVATE[0]))
return 'cgnat';
return length(filter(PRIVATE, (c) => in_cidr(wc, c))) ? 'private' : 'public';
};
const HEX = '0123456789abcdef';
// An IPv6 address as its 32 hex digits, so two spellings of one address
// compare equal (2001:DB8::1, 2001:db8:0::1, as typed or as a tool prints
// it); null when it is none. No regex: the router's addresses and a name's
// AAAA records go through it on every look.
function ip6_full(s) {
if (type(s) != 'string')
return null;
let halves = split(lc(s), '::');
if (length(halves) > 2)
return null;
let head = halves[0] != '' ? split(halves[0], ':') : [];
let tail = length(halves) == 2 && halves[1] != '' ? split(halves[1], ':') : [];
let gap = 8 - length(head) - length(tail);
if (length(halves) == 2 ? gap < 1 : gap != 0)
return null;
let groups = [ ...head ];
for (let i = 0; i < gap; i++)
push(groups, '0');
push(groups, ...tail);
let out = '';
for (let g in groups) {
if (length(g) < 1 || length(g) > 4 || ltrim(g, HEX) != '')
return null;
out += substr(`0000${g}`, length(g));
}
return out;
}
const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).";
/**
* The router's public IPv6 addresses in `ip -6 -j addr show scope global`
* output (`links`), on any interface: a DDNS client may publish the LAN's
* address from the delegated prefix, which reaches the router too. Unique
* local addresses (fc00::/7: OpenWrt gives the LAN one even without IPv6
* from the ISP) and failed duplicates do not count: nothing reaches them from
* outside. [] when there is none.
*/
export function own_ipv6(links) {
let out = [];
for (let l in (type(links) == 'array' ? links : []))
for (let a in l?.addr_info ?? []) {
let k = ip6_full(a?.local);
if (k && a.family == 'inet6' && !a.dadfailed && substr(k, 0, 2) != 'fc' && substr(k, 0, 2) != 'fd')
push(out, a.local);
}
return out;
};
// The router's public IPv6 addresses (own_ipv6), or null when `ip` could not tell.
function router_ipv6() {
let out = sh_out('ip -6 -j addr show scope global');
if (out == null)
return null;
try {
let links = json(out || '[]');
return type(links) == 'array' ? own_ipv6(links) : null;
}
catch (e) {
// No JSON (an `ip` without -j): unknown, so the AAAA records get no verdict.
return null;
}
}
// What the facts are made from, read on the router.
function endpoint_reads(srv, host) {
let ips = host ? lookup.resolve(host) : [];
// The router's IPv6 only when the name has some to compare with.
return {
ips, wan: srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan'),
router6: length(filter(ips, (a) => ip2int(a) == null)) ? router_ipv6() : null,
};
}
/**
* What a public address points at, for Health and the "as you type" check on
* the server page: { host, ips, ips4, ips6, wan, kind (wan_kind), cloudflare,
* here (an IPv4 of it is this router's WAN), v6_only, router6 (the router's
* public IPv6 addresses, own_ipv6; null when unknown, or not read because the
* name has no IPv6), foreign6 (its IPv6 addresses that are none of those, all
* of them when the router has none; null while router6 is), here6 (it has
* IPv6 addresses and each is one of the router's) }. `reads` (a test's)
* stands for what is read on the router: { ips, wan, router6 }.
*/
export function endpoint_facts(srv, host, reads) {
let r = reads ?? endpoint_reads(srv, host);
let ips = r.ips ?? [], wan = r.wan ?? null;
let ips4 = filter(ips, (a) => ip2int(a) != null), ips6 = filter(ips, (a) => ip2int(a) == null);
let own = r.router6 != null ? map(r.router6, ip6_full) : null;
let foreign6 = own != null ? filter(ips6, (a) => index(own, ip6_full(a)) < 0) : null;
return {
host, ips, ips4, ips6, wan, kind: wan_kind(wan),
cloudflare: length(filter(ips, (a) => cloudflare_ip(a))) > 0,
here: wan != null && index(ips4, wan) >= 0,
v6_only: !length(ips4) && length(ips6) > 0,
router6: r.router6 ?? null, foreign6,
here6: foreign6 != null && length(ips6) > 0 && !length(foreign6),
};
};
/*
* The name's IPv6 addresses that do not reach this router from outside, in
* words, or null (each is a public one of the router, or those are unknown).
* A name with IPv4 too: devices that prefer IPv6 take these and fail, the
* others connect.
*/
function aaaa_words(f) {
let bad = f.foreign6 ?? [], n = length(bad);
if (!n)
return null;
if (!length(f.router6))
return sprintf(N_(n, '%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router.',
'%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router.'),
f.host, join(', ', bad));
return sprintf(N_(n, '%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
'%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records.'),
f.host, join(', ', bad));
}
// An IPv6-only name none of whose addresses is a public one of the router: no device connects. Null otherwise.
function v6_only_unreached(f) {
let n = length(f.foreign6 ?? []);
if (!n || n < length(f.ips6))
return null;
if (!length(f.router6))
return sprintf(_('%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router.'),
f.host, join(', ', f.ips6));
return sprintf(N_(n, '%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS.',
'%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS.'),
f.host, join(', ', f.ips6));
}
/**
* The facts in words, in the language of the call: { status: ok|warn|error, text }
* (text a whole sentence). `proto_note` names what must get through ("UDP 4500").
*/
export function endpoint_words(f, proto_note) {
if (!f.host)
return { status: 'error', text: _('No public address: devices will not know where to connect.') };
if (!length(f.ips))
return { status: 'error', text: sprintf(_('%s does not resolve.'), f.host) };
if (f.cloudflare)
return { status: 'error', text: sprintf(_("%s → %s (Cloudflare). %s reaches the router only if this name is DNS-only there, or use the router's IP."),
f.host, join(', ', f.ips), proto_note) };
let v6 = aaaa_words(f);
if (f.v6_only) {
let none = v6_only_unreached(f);
if (none != null || v6 != null)
return { status: 'warn', text: none ?? v6 };
return { status: f.kind == 'public' ? 'warn' : 'ok', text: f.kind == 'public'
? sprintf(_("%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."), f.host, join(', ', f.ips6), f.wan)
: sprintf(_('%s → %s: IPv6 only, so only devices with IPv6 connect.'), f.host, join(', ', f.ips6)) };
}
let v4 = null;
if (f.kind == 'cgnat' || f.kind == 'private')
v4 = f.kind == 'cgnat'
? sprintf(_('The WAN address %s is CGNAT (shared by the ISP): %s cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.'), f.wan, proto_note)
: sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note);
else if (f.wan && !f.here)
v4 = sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan);
// Two separate facts, each a sentence of its own: the IPv4 one first.
if (v4 != null || v6 != null)
return { status: 'warn', text: join(' ', filter([ v4, v6 ], (x) => x != null)) };
// Without the router's WAN address only the facts: names and addresses, no words.
return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, join(', ', [ f.wan, ...(f.here6 ? f.ips6 : []) ]))
: `${f.host} → ${join(', ', f.ips)}` };
};
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
function endpoint_check(id, title, problem, srv, host, proto_note) {
let w = endpoint_words(endpoint_facts(srv, host), proto_note);
return check(id, title, w.status, w.text, null, problem);
}
// "1000: from all fwmark 0x1 lookup 100". A module constant, compiled once, not for each rule.
const MARK_RULE = /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/;
/**
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
* Dawnline's (pref < 5205) whose table has a default route of its own sends
* marked tunnel traffic straight out, past "like a home device". Reported,
* since those marks belong to that package. [] when none.
*/
function policy_routing() {
let out = [];
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
let mm = match(line, MARK_RULE);
if (!mm || +mm[1] >= 5205)
continue;
let routes = sh_out(`ip -4 route show table ${q(mm[4])} 2>/dev/null`) ?? '';
let def = match(routes, /(^|\n)default [^\n]*/)?.[0] ?? '';
if (def == '' || match(def, /local default/) || index(def, `dev ${net.INTERNAL.transit}`) >= 0)
continue;
push(out, `pref ${mm[1]} fwmark 0x${mm[2]} → table ${mm[4]}`);
}
return out;
}
function no_proto() {
return _("netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).");
}
/** Free space on the overlay in KB (null when unknown). */
function overlay_free_kb() {
let out = sh('df -Pk /overlay 2>/dev/null || df -Pk / 2>/dev/null').out;
let m = match(out ?? '', /\n\S+\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s/);
return m ? +m[1] : null;
}
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
function awg_check() {
let st = awg.state();
let title = 'AmneziaWG installed';
if (length(st.missing ?? []))
return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg',
'AmneziaWG isn’t installed');
let st = awg.load();
let title = _('AmneziaWG installed');
let missing = st.missing ?? [];
if (length(missing)) {
// The module was built for the kernel of the firmware it was installed on.
let kc = builds.kernel_changed();
if (kc && index(missing, 'kmod-amneziawg') >= 0)
return check('awg', title, 'error',
sprintf(_('The firmware changed (kernel %s → %s): the AmneziaWG build installed for it is gone. Install the build for this firmware.'), kc.was, kc.now),
'install:awg', _('AmneziaWG needs a build for the new firmware'));
return check('awg', title, 'error', sprintf(N_(length(missing), '%s is missing.', '%s are missing.'), join(', ', missing)), 'install:awg',
_('AmneziaWG isn’t installed'));
}
if (!st.loaded) {
// load() tried it: the second modprobe only repeats why.
let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out);
return check('awg', title, 'error',
`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. */
@@ -233,34 +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) {
let expected = 0;
let states = apply.states_for(m, core.load_usage());
for (let did, d in m.devices) {
let p = m.people[d.person];
if (p?.server == id && !d.disabled && states[d.person] == 'active')
expected++;
}
let actual = 0;
for (let k, p in dmp.peers)
if (p.ifname == srv.ifname)
actual++;
push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, expected == actual ? 'ok' : 'warn',
`${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync'));
push(out, check(`up_${id}`, running, up ? 'ok' : 'error',
up ? sprintf(_('%s is up, listening on UDP %d.'), srv.ifname, srv.port) :
!st ? sprintf(_('%s does not exist.'), srv.ifname) :
length(codes) ? sprintf(_('%s is down: %s.'), srv.ifname, join(', ', codes)) : sprintf(_('%s is down.'), srv.ifname),
up ? null : (st ? 'ifup:' + srv.ifname : 'apply'), down));
// The devices the sync loads, by the same choice the agent compares with every minute.
if (up && dmp.reads[srv.ifname] == 'error')
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, 'warn',
_('The tunnel could not be read, so its devices could not be checked.'), null,
_('The devices in AmneziaWG could not be checked') + label));
else if (up) {
let devs = awg.tunnel_devices(m, id, apply.states_for(m, core.load_usage()));
let diff = awg.peer_diff(devs, dmp, srv.ifname);
let expected = length(devs), missing = diff.missing, extra = diff.extra, actual = diff.loaded;
let same = !missing && !extra;
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, same ? 'ok' : 'warn',
same ? sprintf(N_(actual, '%d device is loaded in the tunnel.', '%d devices are loaded in the tunnel.'), actual) :
extra ? sprintf(N_(expected, '%d of %d device missing, %d loaded that should not be.', '%d of %d devices missing, %d loaded that should not be.'),
missing, expected, extra)
: sprintf(N_(expected, '%d of %d device missing.', '%d of %d devices missing.'), missing, expected),
same ? null : 'sync', _('Not every device is loaded into AmneziaWG') + label));
}
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
push(out, check(`fw_${id}`, `AmneziaWG firewall${label}`, rule && zone ? 'ok' : 'error',
rule && zone ? `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();
@@ -270,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)) {
@@ -278,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;
}
@@ -287,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).
*/
@@ -344,22 +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 ? 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: access is not enforced.',
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) ? sprintf(_("Policy routing on the router (%s) sends marked traffic straight out, past the home-device path: tunnel traffic it matches skips your LAN's proxies and filters."), join('; ', pr))
: _('No other policy routing ahead of the tunnel rules.'),
null, _('Other policy routing bypasses the home-device path')));
}
// A device the sync has to leave out (a merged import, a hand-edited config).
// Its sentences (core.model_errors), how many more, then what it means.
let data = core.model_errors(m);
push(out, check('data', _('People and devices consistent'), length(data) ? 'error' : 'ok',
length(data) ? join(' ', filter([ join(' ', slice(data, 0, 4)), length(data) > 4 ? sprintf(_('(%d more)'), length(data) - 4) : null,
_('Such devices are left out of the tunnels: fix or remove them.') ], (x) => x))
: _('Every device has a key and an address of its own inside its server.'),
null, _('People and devices are inconsistent')));
let fwc = cursor();
fwc.load('firewall');
@@ -367,30 +691,39 @@ 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));
}
}
if (length(filter(values(m.servers), (x) => x.private_key))) {
// While every server is off the resolver only idles on loopback: nothing to check.
if (length(filter(values(m.servers), (x) => x.enabled && x.private_key))) {
let rt = loop.resolver_target();
let ok = stat(loop.RESOLVER.conf) != null && loop.resolver_running();
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`)
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply'));
let conf = stat(loop.RESOLVER.conf);
let running = conf != null && loop.resolver_running();
// A new config (a server turned on, the home link up) restarts it: give it a few seconds.
let restarting = !running && conf != null && time() - conf.mtime < 10;
let ok = running || restarting;
push(out, check('resolver', _('DNS for Home-only devices'), ok ? 'ok' : 'warn',
restarting ? _('Restarting with the new settings.') :
ok ? (rt.mode == 'ns' ? sprintf(_('Plain resolver running next to the LAN (%s).'), rt.address) : sprintf(_('Plain resolver on port %d.'), rt.port))
: _('The resolver is not running; Home-only devices cannot resolve names.'),
ok ? null : 'apply', _('DNS for Home-only devices isn’t working')));
}
if (m.settings.portal_enabled)
@@ -414,8 +747,12 @@ export function fix(id) {
}
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
if (m) {
// Only Dawnline's own tunnels: never another interface of the router.
let mine = filter(values(core.load().servers), (s) => s.ifname == m[1] && s.private_key);
if (!length(mine))
die(sprintf(_("%s is not one of Dawnline's tunnels."), m[1]));
system(`ifup ${q(m[1])}`);
return { ok: true };
}
die('Unknown fix.');
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,14 +11,17 @@ 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;
const KEEP_DAYS = 62;
const KEEP_MONTHS = 24;
const KEEP_EVENTS = 2000;
/** A restore put other counters on flash: the agent reloads from there (dawnline.backup writes it). */
export const USAGE_RELOAD = `${RUN_DIR}/usage.reload`;
/* ---------- retention policy ---------- */
@@ -29,8 +32,10 @@ export const CATEGORY = {
device_added: 'people', device_removed: 'people', devices_removed: 'people',
device_changed: 'people', device_keys: 'people', link_changed: 'people',
person_added: 'people', person_removed: 'people', person_changed: 'people',
paused: 'people', resumed: 'people', paused_all: 'people', resumed_all: 'people',
paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people',
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
// A device's link (dawnline.link): failing in a named way, and working again.
device_failing: 'problems', device_recovered: 'problems',
};
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
@@ -38,9 +43,6 @@ export function category_of(type) {
return CATEGORY[type] ?? 'problems';
};
function int_or(v, d) {
return (v == null || v == '' || match(`${v}`, /[^0-9]/)) ? d : +v;
}
/**
* Log and history retention from /etc/config/dawnline (read fresh, the
@@ -62,13 +64,14 @@ export function policy(s) {
else if (type(cats) != 'array')
cats = split(cats, /[ ,]+/);
cats = uniq(filter(map(cats, (x) => x == 'devices' ? 'people' : x), (x) => index(CATEGORIES, x) >= 0));
// Defaults and ranges come from dawnline.schema, like every other setting.
return {
keep_days: int_or(s.log_keep_days, 30),
max: min(max(int_or(s.log_max, KEEP_EVENTS), 100), 20000),
keep_days: schema.get(s, 'log_keep_days'),
max: schema.get(s, 'log_max'),
categories: cats,
persist: index([ '10min', 'hourly', 'off' ], s.log_persist) >= 0 ? s.log_persist : 'hourly',
usage_days: min(max(int_or(s.usage_keep_days, KEEP_DAYS), 7), 1830),
usage_months: min(max(int_or(s.usage_keep_months, KEEP_MONTHS), 1), 120),
persist: schema.get(s, 'log_persist'),
usage_days: schema.get(s, 'usage_keep_days'),
usage_months: schema.get(s, 'usage_keep_months'),
};
};
@@ -97,21 +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) {
let d = awg.dump();
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;
};
@@ -120,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;
};
@@ -134,8 +210,13 @@ function empty_usage() {
return { devices: {}, people: {}, updated: 0, flushed: 0 };
}
export function load_usage() {
let u = read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
/**
* The usage counters: the live copy in RUN_DIR, else what flash holds. With
* `from_flash` only flash counts (a restore put new counters there, and the
* watcher may have written the old live ones again since).
*/
export function load_usage(from_flash) {
let u = (from_flash ? null : read_json(`${RUN_DIR}/usage.json`, null)) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
// Per-app counters of earlier test builds are not kept.
delete u.clients;
return u;
@@ -208,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 ];
@@ -256,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,
@@ -363,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)
@@ -372,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;
@@ -389,6 +475,35 @@ export function add_event_merged(e, window) {
unlock(l);
};
/**
* Places for connections logged before their address was located (the
* lookup finishes after the event): connect events since `since` from an
* address in `where` ({ ip: "City · ISP" }) that have no place yet get it.
* Returns true when `ev` changed.
*/
export function fill_places(ev, where, since) {
let changed = false;
for (let i = length(ev) - 1; i >= 0 && ev[i].ts >= since; i--) {
let e = ev[i];
if (e.type == 'connect' && !e.where && where[e.detail]) {
e.where = where[e.detail];
changed = true;
}
}
return changed;
};
/** fill_places() on the live log, written only when something changed. */
export function set_places(where, since) {
let l = lock('events');
let ev = load_events();
if (fill_places(ev, where, since)) {
ensure_dir(RUN_DIR);
write_json(`${RUN_DIR}/events.json`, ev, 0o600);
}
unlock(l);
};
/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */
export function persist_events(pol) {
pol ??= policy();
@@ -397,6 +512,10 @@ export function persist_events(pol) {
unlink(`${DATA_DIR}/events.json`);
return;
}
// Only when something was logged since the last copy: flash is written rarely.
let live_st = stat(`${RUN_DIR}/events.json`);
if (!live_st || live_st.mtime <= (stat(`${DATA_DIR}/events.json`)?.mtime ?? 0))
return;
let ev = read_json(`${RUN_DIR}/events.json`, null);
if (ev != null) {
ensure_dir(DATA_DIR, 0o700);
@@ -4,7 +4,7 @@
// time, so a slow DNS server must not hold up the whole admin UI.
import { readfile } from 'fs';
import { q, sh, ensure_dir, read_json, write_json, ip2int, rand_hex, RUN_DIR } from 'dawnline.util';
import { q, sh, ensure_dir, read_json, write_json, ip2int, is_ip6, rand_hex, RUN_DIR } from 'dawnline.util';
import * as live from 'dawnline.live';
import * as net from 'dawnline.net';
@@ -23,9 +23,10 @@ function valid_name(h) {
}
/**
* IPv4 addresses of each name: { host: [ ip, … ] } (empty when it does not
* resolve). IP addresses map to themselves. Every uncached name is asked of
* every server at once; the first server (in SERVERS order) that answers wins.
* Addresses of each name, IPv4 and IPv6: { host: [ ip, … ] } (empty when it
* does not resolve). IP addresses map to themselves. Every uncached name is
* asked of every server at once, A and AAAA; the first server (in SERVERS
* order) that answers wins.
*/
export function resolve_all(hosts) {
let out = {}, now = time(), todo = [];
@@ -33,7 +34,7 @@ export function resolve_all(hosts) {
for (let h in hosts) {
if (h == null || out[h] != null)
continue;
if (ip2int(h) != null) {
if (ip2int(h) != null || is_ip6(h)) {
out[h] = [ h ];
continue;
}
@@ -55,13 +56,16 @@ export function resolve_all(hosts) {
let cmds = [];
for (let i = 0; i < length(todo); i++)
for (let j = 0; j < length(SERVERS); j++)
push(cmds, `( timeout ${TIMEOUT} nslookup ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j} ) &`);
for (let t in [ 'a', 'aaaa' ])
// nslookup's own timeout: some firmware builds BusyBox without `timeout`.
push(cmds, `( nslookup -type=${t} -timeout=${TIMEOUT} -retry=1 ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j}.${t} ) &`);
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
for (let i = 0; i < length(todo); i++) {
let ips = [];
for (let j = 0; j < length(SERVERS) && !length(ips); j++) {
let r = readfile(`${dir}/${i}.${j}`) ?? '';
ips = filter(split(trim(r), '\n'), (x) => ip2int(x) != null);
for (let j = 0; j < length(SERVERS) && !length(ips); j++)
for (let t in [ 'a', 'aaaa' ]) {
let r = readfile(`${dir}/${i}.${j}.${t}`) ?? '';
push(ips, ...filter(split(trim(r), '\n'), (x) => ip2int(x) != null || is_ip6(x)));
}
out[todo[i]] = ips;
cache[todo[i]] = { ts: now, ips };
@@ -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,38 +118,63 @@ 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) {
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);
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 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;
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;
}
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]}`);
/** 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;
}
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'));
}
/*
@@ -57,8 +58,57 @@ export function uhttpd() {
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
};
/** The portal names itself after the server now (the breadcrumb, the tab): its own title setting is gone. */
function portal_title() {
let c = cursor();
c.load('dawnline');
if (c.get('dawnline', 'settings', 'portal_title') != null)
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_title'));
}
/*
* Steps that cannot tell from the config whether they ran are recorded in
* `settings.migrated` (a list), so they run exactly once.
*/
function migrated(c, name) {
let done = c.get('dawnline', 'settings', 'migrated') ?? [];
return index(type(done) == 'array' ? done : [ done ], name) >= 0;
}
function mark_migrated(w, name) {
let done = w.get('dawnline', 'settings', 'migrated') ?? [];
w.set('dawnline', 'settings', 'migrated', [ ...(type(done) == 'array' ? done : [ done ]), name ]);
}
/*
* 1380 was every server's stored MTU before it became automatic (by device
* type and disguise). Once only: an admin may choose 1380 again on purpose.
*/
function auto_mtu() {
let c = cursor();
c.load('dawnline');
if (migrated(c, 'auto_mtu'))
return;
let any = false;
c.foreach('dawnline', 'server', (s) => {
if (s.mtu == '1380')
any = true;
});
store.transact((w, m) => {
w.foreach('dawnline', 'server', (s) => {
if (s.mtu == '1380')
w.delete('dawnline', s['.name'], 'mtu');
});
mark_migrated(w, 'auto_mtu');
});
if (any)
slog('dawnline', 'info', L_('MTU is now automatic'), null, L_('Servers'));
}
/** All of them, in order. */
export function run() {
word_codes();
uhttpd();
auto_mtu();
portal_title();
};
@@ -9,8 +9,8 @@
// lan_device extra interfaces that count as the home network (list)
//
// Home access is enforced by destination: the networks routed out of the
// chosen interfaces form the nft `lan_nets` set, and the tunnel's firewall
// zone gets a forwarding to each of their zones.
// chosen interfaces form the server's nft `home_<id>` set, and the tunnel's
// firewall zone gets a forwarding to each of their zones.
import { readfile, readlink, lsdir, stat } from 'fs';
import { cursor } from 'uci';
@@ -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,32 +70,42 @@ 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 ? null : length(awg.obf_unsafe(srv.obf)) ? { code: 'disguise_invalid' } : awg.obf_unsupported(srv.obf);
if (why) {
block(srv, why, awg.blocked_fix(why));
continue;
}
delete srv.blocked;
want[ifn] = true;
if (!tools)
continue;
// Per server: with several, each changed one has to be brought up again.
let mine = uci_section(c, 'network', ifn, 'interface');
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);
@@ -114,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)
@@ -123,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;
};
@@ -5,12 +5,13 @@
// changes often (update, one atomic transaction).
import { unlink } from 'fs';
import { sh, ensure_dir, write_file, rand_hex, ip2int, RUN_DIR } from 'dawnline.util';
import { sh, ensure_dir, write_file, rand_hex, ip2int, uniq, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
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];
@@ -74,17 +78,43 @@ export function access_sets(m, usage, states) {
return sets;
};
// Duplicate members (two devices with one address) would make the whole load fail.
function set_elems(arr) {
arr = uniq(arr);
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
}
function table(m, sets) {
let ifs = [], lan = [], tun = [];
let dns_addr = loop.client_dns();
/** The portal's TCP ports people may reach through the tunnel (never SSH, DNS or LuCI, whatever is stored). */
function portal_ports(m) {
if (!m.settings.portal_enabled)
return [];
let ok = (p) => p >= 1 && p <= 65535 && index([ 22, 53, 80, 443 ], p) < 0;
let ports = filter([ m.settings.portal_port ], ok);
if (core.portal_http(m) && ok(core.portal_http_port(m)))
push(ports, core.portal_http_port(m));
return ports;
}
/**
* What the table is made from besides the model, read from the router: the
* netns's DNS address (loop.client_dns), where the Home-only resolver runs
* (loop.resolver_target), the LAN's DNS and the network snapshot.
*/
function router_ctx() {
return { dns_addr: loop.client_dns(), resolver: loop.resolver_target(), lan_dns: loop.lan_dns(), snap: net.snapshot() };
}
function table(m, sets, ctx) {
ctx ??= router_ctx();
let ifs = [], tun = [];
let dns_addr = ctx.dns_addr;
if (!ip4(dns_addr))
dns_addr = null;
let rt = 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 = {};
for (let id, srv in m.servers) {
// Only valid interface names reach here (core.tunnels): they are written into the rules as strings.
let tns = core.tunnels(srv);
@@ -93,13 +123,13 @@ function table(m, sets) {
push(tun, t.subnet);
}
if (length(tns))
push(lan, ...net.server_net(srv, snap).nets);
homes[id] = net.collapse(net.server_net(srv, snap).nets);
}
lan = net.collapse(lan);
tun = net.collapse(tun);
let t = [];
push(t, 'table inet dawnline {');
push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`);
for (let id, nets in homes)
push(t, ` set home_${id} { type ipv4_addr; flags interval; auto-merge; ${set_elems(nets)} }`);
// Tunnel subnets are never "home", even inside a wider route to the LAN.
push(t, ` set tun_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(tun)} }`);
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
@@ -118,15 +148,30 @@ function table(m, sets) {
push(t, ' }');
push(t, ' chain guard {');
push(t, ' meta nfproto ipv6 drop');
push(t, ' ct state established,related accept');
push(t, ' icmp type echo-request fib daddr type local accept');
// Every packet is judged by the rules below, not only the first of a
// connection: a change of access cuts open connections too, instead of
// letting a session or a long UDP flow run on for days. Only what has no
// rule of its own passes on its connection: errors and the like, answers
// to the admin's port forwards, and the router's own pings.
push(t, ' ct state related accept');
push(t, ' ct status dnat accept');
push(t, ' icmp type { echo-request, echo-reply } fib daddr type local accept');
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
push(t, ' fib daddr type local ip saddr @lan_ok accept');
let pp = portal_ports(m);
if (length(pp))
// Their own portal, also with the VPN on (the address may be this router's).
push(t, ` fib daddr type local tcp dport { ${join(', ', pp)} } accept`);
// The router itself is part of home: for everyone with all of it, and for
// people limited to some networks only on the addresses in those.
push(t, ' fib daddr type local ip saddr @lan_all accept');
push(t, ' fib daddr type local ip saddr . ip daddr @lan_part accept');
push(t, ' fib daddr type local counter drop');
if (dns_addr)
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
push(t, ' ip daddr @lan_nets ip daddr != @tun_nets ip saddr @lan_all accept');
for (let id, nets in homes)
for (let tn in core.tunnels(m.servers[id]))
push(t, ` iifname "${tn.ifname}" ip daddr @home_${id} ip daddr != @tun_nets ip saddr @lan_all accept`);
push(t, ' ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept');
// Devices with home access are part of home: they reach each other, where the
// server allows it (everyone, or within circles). Within one server: the
@@ -155,13 +200,15 @@ function table(m, sets) {
push(t, ' chain to_device {');
push(t, ' meta nfproto ipv6 drop');
push(t, ' ct status dnat accept');
push(t, ' ip saddr @lan_nets ip saddr != @tun_nets ip daddr @lan_all accept');
for (let id, nets in homes)
for (let tn in core.tunnels(m.servers[id]))
push(t, ` oifname "${tn.ifname}" ip saddr @home_${id} ip saddr != @tun_nets ip daddr @lan_all accept`);
push(t, ' ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept');
push(t, ' counter reject with icmpx admin-prohibited');
push(t, ' }');
// Devices ask the tunnel address; send each query where it belongs.
let to_resolver = rt.mode == 'ns' && ip4(rt.address) ? `dnat ip to ${rt.address}:53` : `redirect to :${+rt.port}`;
let lan_dns = loop.lan_dns();
let lan_dns = ctx.lan_dns;
if (!ip4(lan_dns))
lan_dns = null;
push(t, ' chain dns {');
@@ -195,6 +242,15 @@ 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.
* `ctx` (a test's) stands for what is read from the router: { dns_addr,
* resolver, lan_dns, snap } (router_ctx).
*/
export function render(m, sets, ctx) {
return table(m, sets, ctx);
};
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
export function rebuild(m, sets) {
return load('table inet dawnline\ndelete table inet dawnline\n' + table(m, sets));
@@ -208,9 +264,10 @@ export function rebuild(m, sets) {
export function update(sets) {
let s = '';
for (let name in SETS) {
let members = uniq(sets[name]);
s += `flush set inet dawnline ${name}\n`;
if (length(sets[name]))
s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`;
if (length(members))
s += `add element inet dawnline ${name} { ${join(', ', members)} }\n`;
}
return load(s);
};
@@ -2,8 +2,9 @@
// OpenWrt 24.10, apk on 25.12. Commands that change packages take a log(line)
// callback, which gets their output line by line.
import { access, popen } from 'fs';
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;
};
/**
@@ -79,20 +95,89 @@ export function refresh(log) {
return logged(is_apk() ? 'apk update' : 'opkg update', log).code == 0;
};
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
/** Free space on the overlay in KB (null when unknown). */
function overlay_free_kb() {
let out = run('df -Pk /overlay 2>/dev/null || df -Pk / 2>/dev/null').out;
let m = match(out, /\n\S+\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s/);
return m ? +m[1] : null;
}
/**
* Room for `files` (or `need_kb` from the feeds): the package manager
* unpacks before it removes, so a full flash leaves half an install behind.
* Dies with the numbers.
*/
function preflight(files, need_kb, log) {
let free = overlay_free_kb();
if (free == null)
return;
let need = need_kb ?? 512;
for (let f in files ?? [])
need += int(((stat(f)?.size ?? 0) * 3) / 1024);
if (free < need)
die(sprintf(_('Not enough free space on the router: %d MB free, about %d MB needed. Remove old backups or packages first'),
int(free / 1024), int(need / 1024) + 1));
log?.(' ' + sprintf(_('%d MB free on the overlay'), int(free / 1024)));
}
/** Dawnline's own package: a file of it tells whether apk really reinstalled it. */
const SELF = 'luci-app-dawnline', SELF_MARKER = '/usr/share/ucode/dawnline/util.uc';
/**
* The packages an apk install did not leave at their file's version: apk
* takes a given file as it is (an older version too, a rollback) but leaves
* an installed version alone, whatever the file. Pure: want [{ name,
* version, file }] from the files (file_info()), have { name: installed
* version }. [] when every package took.
*/
export function mismatched(want, have) {
return filter(want, (w) => w.name == null || w.version == null || have?.[w.name] != w.version);
};
/**
* Package files (from a release): true when every one is installed. force
* also reinstalls the same version or goes back to an older one (opkg; apk
* takes a file as it is: Dawnline's own package is checked by a file of it,
* any other by its installed version).
*/
export function install_files(files, force, log) {
preflight(files, 0, log);
let args = join(' ', map(files, q));
return logged(is_apk()
? `apk add --allow-untrusted ${args}`
: `opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
if (!is_apk())
return logged(`opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
let want = map(files, (f) => ({ ...file_info(f), file: f }));
let own = length(filter(want, (w) => w.name == SELF)) > 0;
// Dawnline's own reinstall that changed nothing is a failure, not a silent "done".
let before = own && force ? stat(SELF_MARKER)?.mtime : null;
if (logged(`apk add --allow-untrusted ${args}`, log).code != 0)
return false;
if (own) {
if (force && before != null && stat(SELF_MARKER)?.mtime == before) {
log?.(' ' + _('apk did not reinstall the version that is already installed'));
die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router"));
}
return true;
}
// Any other package took when it is at its file's version (the same
// version again counts: apk keeps the installed one).
let have = {};
for (let w in want)
if (w.name != null)
have[w.name] = version(w.name);
let bad = mismatched(want, have);
for (let w in bad)
log?.(' ' + sprintf(_('apk did not install %s %s (installed: %s)'), w.name ?? w.file, w.version ?? '?', have[w.name] ?? '-'));
return !length(bad);
};
/** Packages by name from the feeds. */
export function add(names, log) {
preflight(null, 2048, log);
return logged(is_apk() ? `apk add ${join(' ', map(names, q))}` : `opkg install ${join(' ', map(names, q))}`, log).code == 0;
};
export function upgrade(names, log) {
preflight(null, 2048, log);
return logged(is_apk() ? `apk upgrade ${join(' ', map(names, q))}` : `opkg upgrade ${join(' ', map(names, q))}`, log).code == 0;
};
@@ -105,7 +190,9 @@ export function upgradable() {
let up = {};
if (is_apk()) {
for (let line in split(run('apk version -l "<"').out, '\n')) {
let m = match(line, /^(\S+?)-([0-9][^ ]*)\s+<\s+(\S+)/);
// "name-version-rN < newer": the version is what follows the last dash
// before the release suffix (a name may hold digits, a version no dash).
let m = match(line, /^(\S+)-([^- ]+-r[0-9]+)\s+<\s+(\S+)/);
if (m)
up[m[1]] = m[3];
}
@@ -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? }
//
@@ -19,8 +19,18 @@
// other sites' logs. The portal can only manage the person's own devices
// within their limits, and not those the admin turned off (dawnline.devices).
//
// Changes through a link are limited too (a link is not a terminal: a few
// dozen every quarter hour), and the configurations themselves (keys, the
// disguise) only go over HTTPS: a plain-HTTP link (an IP address in Settings)
// shows the page, but gets them from its HTTPS twin.
//
// Messages go out in the page's language (Accept-Language: the portal's
// fetch sends the visitor's choice) when a Dawnline translation for it is
// installed; else in English, and the page translates the ones it knows.
//
// handle() serves one request: `io` = { env, headers, read(n), write(s) }; the
// CGI script (www/cgi-bin/portal) is its wrapper.
// CGI script (cgi.uc) is its wrapper, behind the shell door www/cgi-bin/portal
// that answers anything not shaped like a link (its not_found() twin).
import { stat, readfile } from 'fs';
import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util';
@@ -30,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).
@@ -41,6 +53,8 @@ const SHARED_LIMIT = FAIL_LIMIT * 25;
const SHARED_KEY = 'cloudflare';
// Clients remembered at most (the oldest go first).
const RATE_MAX = 2000;
// Changes one link may make within FAIL_WINDOW (each one writes flash and syncs the tunnels).
const ACTION_LIMIT = 40;
const BODY_MAX = 8192;
// The early end of a request (a response was written).
const DONE = '__dawnline_done__';
@@ -52,7 +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', '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]);
@@ -110,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));
@@ -123,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.'));
}
}
@@ -210,28 +239,50 @@ function rate_fail(r) {
live.add_event({ type: 'portal_blocked', detail: k == SHARED_KEY ? 'all Cloudflare visitors' : k });
}
/** One more change through this link; refused beyond ACTION_LIMIT per window. */
function rate_action(r) {
let key = `act:${r.person.id}`;
let l = lock('portal-rate');
let st = rate_state();
let v = st[key] ?? { first: time(), count: 0 };
v.count++;
st[key] = v;
ensure_dir(RUN_DIR);
write_json(RATE, st, 0o600);
unlock(l);
if (v.count > ACTION_LIMIT)
fail(r, '429 Too Many Requests', _('Too many changes in a short time. Try again in a few minutes.'));
}
/* ---------- pages ---------- */
/** What the page is called (the tab, the first crumb): the person's server, or Dawnline. */
function place(r) {
return r.person ? r.m.servers[r.person.server]?.name || 'Dawnline' : 'Dawnline';
}
/** The app shell; it reads the code from its own URL and sends it along. */
function shell(r) {
// The build's time joins the version so every update busts the hour-long asset cache.
// 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 = r.title;
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>
@@ -242,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();
}
@@ -263,30 +319,94 @@ function reload(r) {
not_found(r);
}
/**
* The person's state for the page: a stop by the admin (pause, end of access)
* wins over their server being off, so they learn that their access is stopped.
*/
function person_state(m, p, usage) {
let st = core.person_state(m, p, usage);
if (st == 'server_off') {
let own = core.own_state(m, p, usage);
if (index(LOCKED, own) >= 0)
return own;
}
return st;
}
/** Why the person can't change anything right now, or null. */
function locked(r) {
return locked_reason(person_state(r.m, r.person, core.load_usage()));
}
/** Refuses a change (or a config) while the person is stopped. */
function need_open(r) {
let why = locked(r);
if (why)
fail(r, '403 Forbidden', why);
}
/** The same link over HTTPS (for a plain-HTTP visitor), or null when this is it. */
function https_url(r) {
if (r.https)
return null;
let host = r.host;
let h = match(host, /^\[/) ? match(host, /^(\[[^\]]*\])/)?.[1] : split(host, ':')[0];
let port = r.m.settings.portal_port;
return `https://${h}${port == 443 ? '' : `:${port}`}${r.base}`;
}
/**
* Keys and the disguise never travel in the clear: over plain HTTP a
* configuration is refused, and the answer names the HTTPS link to use.
*/
function need_https(r) {
let u = https_url(r);
if (u)
send_json(r, '403 Forbidden', { error: _('Open this link over HTTPS to get the connection settings.'), https_url: u });
}
/** The router's offset from UTC in minutes: the admin sets hours in its time, the page shows the visitor's. */
function tz_offset() {
let t = time();
return int((timegm(localtime(t)) - t) / 60);
}
/** Everything the page shows. */
function state(r) {
let m = r.m, person = r.person;
let usage = core.load_usage();
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]);
let srv = m.servers[person.server];
// The device this page was opened from, when it came through the tunnel.
let here = null;
for (let id, d in m.devices)
if (d.person == person.id && d.address == r.peer)
here = id;
// The device this page was opened from, through the tunnel or beside it.
let here = view.device_here(v.devices, r.peer);
return {
title: r.title,
person: v,
here,
server: {
name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh,
// AmneziaWG with the disguise off is plain WireGuard (any WireGuard app).
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
// Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets.
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
// The home networks a device with LAN Bypass still sends into the tunnel (home and internet access):
// its own local network on the same addresses is out of reach (Add a device says so).
home: srv && person.access == 'both' ? core.person_home(srv, person).nets : [],
},
can_add: length(person.devices) < person.device_limit,
locked: index(LOCKED, v.state) >= 0,
// Over plain HTTP: where the configurations are (keys only travel encrypted).
https_url: https_url(r),
kinds: core.KINDS,
// The router's day: access ends and usage days follow its clock, not the browser's.
today: today(),
// Its clock too: "last connected 3 min ago" is measured against it, not the phone's.
now: time(),
// And its time zone: hours are set in the router's time, shown in the visitor's.
tz_offset: tz_offset(),
version: VERSION,
};
}
@@ -295,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;
}
@@ -304,16 +424,22 @@ function api_state(r) {
}
function api_add(r) {
need_open(r);
need_https(r);
let b = body(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
fail(r, '503 Service Unavailable', not_ready());
rate_action(r);
// lan_bypass: JSON true keeps the device's own local network out of the tunnel; anything else is off.
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key, lan_bypass: b.lan_bypass === true }));
reload(r);
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
}
function api_config(r, id) {
let d = own_device(r, id);
need_open(r);
need_https(r);
awg.mark_issued(r.m, d.id);
send_json(r, '200 OK', awg.client_config(r.m, d));
}
@@ -324,10 +450,12 @@ const ACTIONS = {
guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id }));
return {};
},
rotate: (r, d, b) => {
// Set up from scratch: new keys and the new configuration, which the set-up sheet takes in.
reconnect: (r, d, b) => {
need_https(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
let config = guard(r, () => devices.rotate(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
fail(r, '503 Service Unavailable', not_ready());
let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
return { config };
},
'delete': (r, d, b) => {
@@ -338,10 +466,12 @@ const ACTIONS = {
function api_device(r, id) {
let d = own_device(r, id);
need_open(r);
let b = body(r);
let act = ACTIONS[b.action];
if (!act)
fail(r, '400 Bad Request', 'Unknown action.');
fail(r, '400 Bad Request', _('Unknown action.'));
rate_action(r);
let res = act(r, d, b);
reload(r);
send_json(r, '200 OK', { ok: true, ...res, state: state(r) });
@@ -388,15 +518,15 @@ export function handle(io) {
let host = header('host') ?? '';
let m = core.load();
let r = {
io, env, m, path, https,
io, env, m, path, https, host,
method: env.REQUEST_METHOD ?? 'GET',
peer: env.REMOTE_ADDR ?? '',
buckets: buckets(env),
title: m.settings.portal_title || 'Dawnline',
// The port in the visitor's address bar ([v6]:port, name:port, or the default).
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
person: null,
base: '',
gzip: match(lc(header('accept-encoding') ?? ''), /(^|[ ,])gzip([ ;,]|$)/) != null,
};
let segs = filter(split(path, '/'), (s) => s != '');
@@ -415,11 +545,12 @@ export function handle(io) {
if (p.code == code)
r.person = p;
// A wrong code or a blocked client: indistinguishable from a path that does
// not exist. Only well-formed guesses count towards the limit.
if (rate_blocked(r))
not_found(r);
// A wrong code is indistinguishable from a path that does not exist. Only
// well-formed guesses count towards the limit, and a client over it is just
// no longer counted: a valid link always opens, so guesses from a shared
// address (every Cloudflare visitor) cannot lock its owner out.
if (r.person == null) {
if (!rate_blocked(r))
rate_fail(r);
not_found(r);
}
@@ -439,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`;
@@ -54,8 +54,10 @@ export function running() {
*/
export function sync(m, target, lan) {
ensure_dir('/var/etc');
// Servers that are on: with none, the resolver idles on loopback.
let ifs = [];
for (let id, s in m.servers)
if (s.enabled)
for (let t in core.tunnels(s))
push(ifs, t.ifname);
let lines = [
@@ -76,7 +78,7 @@ export function sync(m, target, lan) {
push(lines, `server=${a}@${target.address}`);
}
else {
// No tunnel yet: loopback only (without any interface= line dnsmasq would answer everywhere).
// No tunnel on: loopback only (without any interface= line dnsmasq would answer everywhere).
push(lines, 'bind-dynamic', ...(length(ifs) ? map(ifs, (i) => `interface=${i}`) : [ 'listen-address=127.0.0.1' ]), `resolv-file=${RESOLV}`);
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
if ((readfile(RESOLV) ?? '') != resolv) {
@@ -5,6 +5,8 @@ import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as health from 'dawnline.health';
import * as schema from 'dawnline.schema';
import { uniq } from 'dawnline.util';
import { _ } from 'dawnline.i18n';
/**
* An rpcd handler from fn(args): an object result is passed on, anything else
@@ -33,16 +35,27 @@ export function clamp_days(v) {
return n >= 1 ? (n > 400 ? 400 : int(n)) : 30;
};
export const METHODS = [ 'off', 'standard', 'strong', 'max' ];
export const METHODS = [ 'off', 'balanced', 'max' ];
/** The disguise a new server gets: the strongest this router can run. */
export function default_method() {
let c = awg.caps();
return c.v3 ? 'max' : c.v2 ? 'balanced' : 'off';
};
/** A disguise method the installed AmneziaWG can run. */
export function check_method(name) {
if (index(METHODS, name) < 0)
die('Unknown disguise method.');
if (name == 'max' && !awg.caps().v3)
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.'));
return name;
};
@@ -52,18 +65,49 @@ export function check_method(name) {
* addresses use plain HTTP, the next port too — both get a WAN ACCEPT rule.
* Neither may be 22, 53, 80 or 443, beyond 65535, or taken by another program.
*/
/** TCP port forwards from the servers' WAN zones: [{ from, to, name }]. */
function tcp_forwards(m) {
let out = [];
for (let z in uniq([ 'wan', ...map(values(m.servers), (s) => s.wan_zone) ]))
push(out, ...core.wan_forwards(z, 'tcp'));
return out;
}
/**
* TCP ports the portal can't take, and who holds them: [{ from, to, who }].
* The router's own (22, 53, 80, 443), other programs and port forwards from WAN.
* `who` is shown in the admin's language ("Used by %s.").
*/
export function tcp_taken(m) {
let out = [];
let held = {};
let hold = (p, who) => {
if (!held[p]) {
held[p] = true;
push(out, { from: p, to: p, who });
}
};
for (let p in schema.RESERVED_PORTS)
hold(p, _('the router itself'));
for (let p, name in health.tcp_port_programs())
hold(+p, sprintf(_('%s on this router'), name));
for (let f in tcp_forwards(m))
push(out, { from: f.from, to: f.to, who: sprintf(_('port forward “%s”'), f.name) });
return out;
};
export function check_portal(m, was) {
let s = m.settings;
if (!s.portal_enabled)
return;
let port = s.portal_port;
if (!schema.valid_port(port) || index(schema.RESERVED_PORTS, port) >= 0)
die('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).');
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.
@@ -78,6 +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(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 } 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 (name == '' || length(name) > 48)
die('Enter a service name.');
if (!valid_name(name))
die(_('Service: Enter a name: up to 48 characters, without < > " or \\.'));
let address = str(a.address);
if (!schema.ipv4(address))
die('Address must be an IPv4 address.');
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);
@@ -54,14 +55,14 @@ function service_set(a) {
c.delete(core.CONFIG, id, 'port');
return id;
});
apply.sync();
return { id };
let s = apply.sync();
return { id, warning: s.warning };
}
function service_delete(a) {
store.transact((c, m) => {
if (!m.services[a.id])
die('Unknown service.');
die(_('Unknown service.'));
c.delete(core.CONFIG, a.id);
for (let pid, p in m.people)
if (index(p.services, a.id) >= 0) {
@@ -72,8 +73,8 @@ function service_delete(a) {
c.delete(core.CONFIG, pid, 'service');
}
});
apply.sync();
return { ok: true };
let s = apply.sync();
return { ok: true, warning: s.warning };
}
/* ---------- circles ---------- */
@@ -81,18 +82,18 @@ function service_delete(a) {
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
function circle_set(a) {
let name = str(a.name);
if (name == '' || length(name) > 32)
die('Enter a circle name (up to 32 characters).');
if (!valid_name(name) || ulength(name) > 32)
die(_('Enter a circle name: up to 32 characters, without < > " or \\.'));
let res = store.transact((c, m) => {
let ci = a.id ? m.circles[a.id] : null;
if (a.id && !ci)
die('Unknown circle.');
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');
@@ -112,25 +113,25 @@ function circle_set(a) {
}
return { id, edit: !!ci, server: m.servers[server].name };
});
apply.sync();
let s = apply.sync();
admin_log('awg', res.edit ? 'changed' : 'added', 'circle', name, res.server);
return { id: res.id, circles: values(core.load().circles) };
return { id: res.id, circles: values(core.load().circles), warning: s.warning };
}
function circle_delete(a) {
let res = store.transact((c, m) => {
let ci = m.circles[a.id];
if (!ci)
die('Unknown circle.');
die(_('Unknown circle.'));
c.delete(core.CONFIG, a.id);
for (let pid, p in m.people)
if (p.circle == a.id)
c.delete(core.CONFIG, pid, 'circle');
return { name: ci.name, server: m.servers[ci.server]?.name };
});
apply.sync();
let s = apply.sync();
admin_log('awg', 'removed', 'circle', res.name, res.server);
return { circles: values(core.load().circles) };
return { circles: values(core.load().circles), warning: s.warning };
}
/* ---------- devices at home ---------- */
@@ -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,9 +9,10 @@ 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' ];
'bonus_gb', 'hours', 'note', 'dns_mode', 'server' ];
/* ---------- people ---------- */
@@ -39,25 +40,31 @@ function person_update(a) {
fields.circle = a.circle;
if (type(a.home_nets) == 'array')
fields.home_nets = a.home_nets;
let m0 = null;
let before = store.transact((c, m) => {
let p = m.people[a.id];
m0 = m;
core.update_person(c, m, a.id, fields);
return p;
});
let changes = join(', ', filter(keys(fields), (k) => k != 'note'));
// "moved to Test" says more than "server".
let changes = join(', ', map(filter(keys(fields), (k) => k != 'note'),
(k) => k == 'server' && m0?.servers[fields.server] ? `moved to ${m0.servers[fields.server].name}` : k));
if (changes)
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
// Access changes affect the nft sets and client AllowedIPs.
apply.sync();
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 };
// 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
@@ -67,16 +74,34 @@ function person_pause(a) {
return apply.sync();
}
/** A new personal link: the old one stops working at once (every portal request carries the code). */
/**
* A new personal link: the old one stops working at once (every portal
* request carries the code). What the old link already handed out stays
* unless asked: `remove` lists the person's devices to take away with it.
*/
function person_regen(a) {
store.transact((c, m) => {
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 = [];
for (let id in (type(a.remove) == 'array' ? a.remove : []))
if (m.devices[id]?.person == a.id) {
push(gone, m.devices[id]);
core.delete_device(c, m, id);
}
return gone;
});
live.add_event({ type: 'link_changed', person: a.id, by: 'admin' });
let s = null;
if (length(gone)) {
for (let d in gone)
live.add_event({ type: 'device_removed', person: a.id, device: d.id, detail: d.name, dname: d.name, dkind: d.kind, by: 'admin' });
s = apply.sync();
}
let m = core.load();
return { link: core.portal_url(m, m.people[a.id]) };
return { link: core.portal_url(m, m.people[a.id]), removed: length(gone), warning: s?.warning };
}
/** The personal code and links (Copy link, QR, invite): admins only, unlike status. */
@@ -84,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) };
}
@@ -103,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)
@@ -111,33 +136,32 @@ function person_usage(a) {
return { person: live.series([ usage.people?.[a.id] ], days), devices: devs };
}
function pause_all(a) {
store.transact((c, m) => {
c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, 'settings', 'paused_all', a.paused ? '1' : '0');
});
live.add_event({ type: a.paused ? 'paused_all' : 'resumed_all', by: 'admin' });
return apply.sync();
}
/* ---------- devices ---------- */
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.');
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 = {
@@ -147,18 +171,18 @@ export const methods = {
},
person_update: {
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [] },
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [], server: '' },
call: wrap(person_update),
},
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
person_regen: { args: { id: '' }, call: wrap(person_regen) },
person_regen: { args: { id: '', remove: [] }, call: wrap(person_regen) },
person_links: { args: { id: '' }, call: wrap(person_links) },
person_delete: { args: { id: '' }, call: wrap(person_delete) },
person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) },
pause_all: { args: { paused: false }, call: wrap(pause_all) },
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, 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';
@@ -14,7 +14,8 @@ import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health';
import * as backup from 'dawnline.backup';
import * as devices from 'dawnline.devices';
import { wrap, str, check_method, check_portal } from 'dawnline.rpc.common';
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' ];
@@ -23,27 +24,64 @@ const MESH_WORDS = { off: 'devices kept apart', all: 'devices reach each other',
/* ---------- free names, ports and subnets ---------- */
function free_port(m) {
let used = {};
/**
* UDP ports a server can't listen on, and who holds them: [{ from, to, who }].
* Other servers, tunnel interfaces, programs on the router and port forwards
* from its WAN zone. `srv` is the server being edited: its own port isn't counted.
* `who` is shown in the admin's language ("Used by %s.").
*/
function udp_taken(m, srv, wan_zone) {
let out = [];
let held = {};
let hold = (p, who) => {
if (p > 0 && !held[p]) {
held[p] = true;
push(out, { from: p, to: p, who });
}
};
for (let id, o in m.servers)
if (id != srv?.id)
hold(o.port, sprintf(_('server “%s”'), o.name));
let nc = cursor();
nc.load('network');
nc.foreach('network', 'interface', (s) => {
if (s.listen_port)
used[+s.listen_port] = true;
if (s.listen_port && s['.name'] != srv?.ifname)
hold(+s.listen_port, sprintf(_('interface %s'), s['.name']));
});
for (let id, srv in m.servers)
used[srv.port] = true;
let progs = health.udp_port_programs();
for (let p in health.udp_bound())
if (p != srv?.port)
hold(p, progs[`${p}`] ? sprintf(_('%s on this router'), progs[`${p}`]) : _('another program on this router'));
for (let f in core.wan_forwards(wan_zone, 'udp'))
push(out, { from: f.from, to: f.to, who: sprintf(_('port forward “%s”'), f.name) });
return out;
}
function check_udp_port(port, taken) {
for (let t in taken)
if (t.from <= port && port <= t.to)
die(sprintf(_('UDP %d is used by %s. Choose another port.'), port, t.who));
}
/** The usual AmneziaWG port when free, otherwise a random high one. */
const DEFAULT_PORT = 4500;
function free_port(taken) {
let used = (p) => length(filter(taken, (t) => t.from <= p && p <= t.to)) > 0;
if (!used(DEFAULT_PORT))
return DEFAULT_PORT;
for (let i = 0; i < 50; i++) {
let p = rand_int(40000, 60000);
if (!used[p])
if (!used(p))
return p;
}
return 51830;
}
function free_subnet(taken) {
for (let i = 0; i < 200; i++) {
let cand = parse_cidr(sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)));
for (let i = 0; i < 300; i++) {
// 10.x first; past 200 tries (a 10/8 LAN) the 172.16-31 range.
let cand = parse_cidr(i < 200 ? sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)) : sprintf('172.%d.%d.0/24', rand_int(16, 31), rand_int(0, 250)));
let bad = false;
for (let t in taken) {
let tc = parse_cidr(t);
@@ -58,9 +96,14 @@ function free_subnet(taken) {
return '10.77.0.0/24';
}
function free_portal_port(cur) {
for (let p in uniq([ cur || 8443, 8443, 9443, 10443, 7443, 4443 ]))
if (!length(health.tcp_port_owners(p)) && !length(health.tcp_port_owners(p + 1)))
/**
* A portal port free together with the next one (plain HTTP for IP links):
* `first` (the server's UDP number, TCP is another port) before the usual ones.
*/
function free_portal_port(first, cur, taken) {
let used = (p) => length(filter(taken, (t) => t.from <= p && p <= t.to)) > 0;
for (let p in uniq([ first, cur || 8443, 8443, 9443, 10443, 7443, 4443 ]))
if (!used(p) && !used(p + 1))
return p;
return 9443;
}
@@ -97,70 +140,118 @@ function free_server_id(m) {
return `server${n}`;
}
/** Subnets a new server must not overlap: the router's networks and the other servers. */
function taken_subnets(m) {
let taken = health.used_subnets(null);
/** Networks a new server must not overlap, by name: the router's and the other servers'. */
function taken_networks(m) {
let out = [];
let seen = {};
let add = (name, cidr) => {
let c = parse_cidr(cidr);
if (c && !seen[cidr_str(c)]) {
seen[cidr_str(c)] = true;
push(out, { name, cidr: cidr_str(c) });
}
};
for (let n in health.networks())
add(n.iface, n.cidr);
for (let id, s in m.servers)
push(taken, s.subnet);
return taken;
add(s.name, s.subnet);
return out;
}
/* ---------- setup ---------- */
function setup_defaults(a) {
let m = core.load();
let taken = taken_subnets(m);
let networks = taken_networks(m);
let zones = [];
let fc = cursor();
fc.load('firewall');
fc.foreach('firewall', 'zone', (z) => push(zones, z.name));
let host = m.settings.portal_host;
let snap = net.snapshot(true);
let wan_ip = snap.wan ? split(snap.devices[snap.wan]?.addrs?.[0] ?? '', '/')[0] : '';
let kind = health.wan_kind(wan_ip || null);
let host = m.settings.portal_host, from = host ? 'portal' : '';
if (!host) {
// Prefer a DDNS name, then an ACME certificate's, then the WAN address.
// Prefer a DDNS name, then an ACME certificate's, then the WAN address —
// but never a private or CGNAT one: nobody on the internet reaches it.
let dc = cursor();
if (dc.load('ddns'))
dc.foreach('ddns', 'service', (s) => {
if (!host && s.lookup_host && s.enabled == '1')
if (!host && s.lookup_host && s.enabled == '1') {
host = s.lookup_host;
});
if (!host)
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
if (!host)
host = live.iface_status('wan')?.['ipv4-address']?.[0]?.address ?? '';
from = 'ddns';
}
});
if (!host) {
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
from = host ? 'cert' : '';
}
if (!host && kind == 'public') {
host = wan_ip;
from = 'wan';
}
}
// The zones the WAN and LAN devices are in, whatever they are called.
let wan_zone = snap.devices[snap.wan]?.zone ?? (index(zones, 'wan') >= 0 ? 'wan' : zones[1]);
let lan_zone = snap.devices[snap.lan]?.zone ?? (index(zones, 'lan') >= 0 ? 'lan' : zones[0]);
let udp = udp_taken(m, null, wan_zone);
let tcp = tcp_taken(m);
let port = free_port(udp);
return {
id: free_server_id(m),
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: free_port(m),
subnet: free_subnet(taken),
port,
subnet: free_subnet(map(networks, (n) => n.cidr)),
endpoint: host,
mtu: 1380,
// Where the address came from (ddns, cert, wan, portal) and what the WAN is (public, private, cgnat, none).
endpoint_from: from,
wan_kind: kind,
wan_ip: wan_ip || null,
// Automatic.
mtu: 0,
zones,
lan_zone: index(zones, 'lan') >= 0 ? 'lan' : zones[0],
wan_zone: index(zones, 'wan') >= 0 ? 'wan' : zones[1],
portal_port: free_portal_port(m.settings.portal_port),
lan_zone,
wan_zone,
// A portal already on keeps its port; a new one takes the server's number when it can.
portal_port: m.settings.portal_enabled ? m.settings.portal_port : free_portal_port(port, m.settings.portal_port, tcp),
awg: awg.caps(),
awg_state: awg.state(),
taken,
awg_state: awg.load(),
networks,
udp_taken: udp,
tcp_taken: tcp,
};
}
/**
* Where a public address points, as the admin types it (debounced in the
* UI): the same facts Health uses, in words. `id` names the server whose WAN
* to compare with (a new one: the default WAN).
*/
function endpoint_probe(a) {
let host = str(a.host);
if (host != '' && !valid_host(host))
die(_('Public address must be a hostname or IP address.'));
let m = core.load();
let srv = m.servers[str(a.id)] ?? null;
let f = health.endpoint_facts(srv, host);
let w = health.endpoint_words(f, `UDP ${srv?.port ?? +a.port || 4500}`);
return { ...f, status: w.status, text: w.text };
}
/** AmneziaWG can run a server: installed, and its kernel module loads. */
function need_awg_loaded() {
devices.need_awg();
if (awg.state().loaded)
return;
system('modprobe amneziawg >/dev/null 2>&1');
if (!awg.state().loaded)
die("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components.");
if (!awg.load().loaded)
die(_("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components."));
}
/** An MTU as typed: '' (the default) or 1280-1500. */
/** 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;
}
@@ -172,29 +263,32 @@ 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.`);
let port = free_port(m);
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);
}
for (let sid, o in m.servers)
if (o.port == port)
die(`UDP ${port} is used by ${o.name}.`);
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu) || '1380';
let preset = str(a.preset) || 'standard';
check_udp_port(port, udp);
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu);
let preset = str(a.preset) || default_method();
let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) };
let pc = parse_cidr(srv.subnet);
if (pc)
srv.subnet = cidr_str(pc);
// Public addresses inside the tunnel would hide the real hosts behind them.
// New servers only: a restored backup keeps what it had.
if (pc && !core.private_cidr(pc))
die(_('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.'));
let taken = [ ...router_subnets ];
for (let sid, o in m.servers)
push(taken, o.subnet);
@@ -206,12 +300,15 @@ function server_create(a) {
let set = (k, v) => c.set(core.CONFIG, id, k, v);
c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, id, 'server');
if (!valid_name(str(a.name) || 'Home'))
die(_('Server: Enter a name: up to 48 characters, without < > " or \\.'));
set('name', str(a.name) || 'Home');
set('ifname', ifname);
set('port', `${port}`);
set('subnet', srv.subnet);
if (srv.endpoint)
set('endpoint', srv.endpoint);
if (mtu)
set('mtu', mtu);
set('keepalive', '25');
let kp = awg.server_keys();
@@ -228,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)}`);
}
}
@@ -249,8 +347,11 @@ function server_create(a) {
system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable');
let made = core.load().servers[id];
admin_log('dawnline', 'created', 'server', made?.name ?? id, made ? `UDP ${made.port}` : null);
sh_bg('/etc/init.d/dawnline restart');
return { id, applied: r };
// netifd reads its protocol handlers when it starts: AmneziaWG installed
// after that (by hand, or by an older installer) needs a network restart.
let network_restart = !awg.state().handler;
sh_bg(network_restart ? '/etc/init.d/network restart; /etc/init.d/dawnline restart' : '/etc/init.d/dawnline restart');
return { id, applied: r, network_restart, warning: r.warning };
}
/* ---------- interfaces ---------- */
@@ -297,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));
}
@@ -309,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 : [])) {
@@ -323,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);
@@ -388,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;
}
@@ -400,32 +501,32 @@ 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 (str(v.name) == '')
die('Name cannot be empty.');
if (!valid_name(str(v.name)))
die(_('Server: Enter a name: up to 48 characters, without < > " or \\.'));
set('name', str(v.name));
}
// Empty = the portal's address (core.endpoint_host), as at creation.
if (v.endpoint != null) {
if (str(v.endpoint) == '' || !valid_host(str(v.endpoint)))
die('Public address must be a hostname or IP address.');
if (str(v.endpoint) != '' && !valid_host(str(v.endpoint)))
die(_('Public address must be a hostname or IP address.'));
set('endpoint', str(v.endpoint));
}
if (v.port != null) {
if (!schema.valid_port(v.port))
die('UDP port must be 1-65535.');
die(_('UDP port must be 1-65535.'));
let n = +str(v.port);
for (let id, o in m.servers)
if (id != srv.id && o.port == n)
die(`UDP ${n} is used by ${o.name}.`);
if (n != srv.port)
check_udp_port(n, udp_taken(m, srv, srv.wan_zone));
set('port', `${n}`);
}
if (v.enabled != null)
set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0');
if (v.mesh != null) {
if (index(core.MESH, v.mesh) < 0)
die('Unknown choice for devices reaching each other.');
die(_('Unknown choice for devices reaching each other.'));
set('mesh', v.mesh);
set('device_mesh', null);
}
@@ -433,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) {
@@ -443,15 +544,28 @@ function server_update(a) {
else
c.delete(core.CONFIG, srv.id, 'dns');
}
// A new tunnel network: private, free, and every device renumbered into it.
if (v.subnet != null && str(v.subnet) != '' && str(v.subnet) != srv.subnet) {
let pc = parse_cidr(str(v.subnet));
if (!pc)
die(_('Subnet must look like 10.77.0.0/24.'));
if (!core.private_cidr(pc))
die(_('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.'));
let taken = map(filter(taken_networks(m), (n) => n.cidr != srv.subnet && n.name != srv.name), (n) => n.cidr);
for (let t in taken)
if (cidr_overlaps(pc, parse_cidr(t)))
die(sprintf(_('Subnet overlaps %s.'), t));
core.renumber_server(c, m, srv, cidr_str(pc));
}
return srv;
});
// For the log: what changed, in words. Turning on or off is its own line.
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS' };
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS', subnet: 'tunnel network' };
let what = [];
for (let k, label in labels) {
if (v[k] == null)
continue;
let was = k == 'dns' ? join(' ', srv.dns ?? []) : `${srv[k] ?? ''}`;
let was = k == 'dns' ? join(' ', srv.dns ?? []) : k == 'mtu' && !srv.mtu ? '' : `${srv[k] ?? ''}`;
let now = k == 'dns' ? join(' ', dns_list(v.dns)) : str(v[k]);
if (trim(was) != trim(now))
push(what, label);
@@ -468,13 +582,28 @@ function server_update(a) {
return r;
}
/** What the ports of an existing server must avoid (the AmneziaWG card checks as you type). */
function server_ports(a) {
let m = core.load();
let srv = m.servers[a.id];
if (!srv)
die(_('Unknown server.'));
// `networks`: what a new tunnel network must not overlap (everything but this server's own).
return { udp_taken: udp_taken(m, srv, srv.wan_zone), tcp_taken: tcp_taken(m),
networks: filter(taken_networks(m), (n) => n.cidr != srv.subnet) };
}
function server_obfuscation(a) {
let preset = str(a.preset) || 'standard';
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)
@@ -490,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) {
@@ -520,6 +649,8 @@ export const methods = {
lan_like: true, portal_enabled: false, portal_port: 0 },
call: wrap(server_create),
},
server_ports: { args: { id: '' }, call: wrap(server_ports) },
endpoint_probe: { args: { host: '', id: '', port: 0 }, call: wrap(endpoint_probe) },
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
@@ -11,7 +11,8 @@ import * as store from 'dawnline.store';
import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health';
import * as pc from 'dawnline.portalcert';
import { wrap, check_portal } from 'dawnline.rpc.common';
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' ];
@@ -65,7 +66,7 @@ function settings_get(a) {
services: values(m.services),
cert: cert ? { path: cert.cert, self_signed: cert.self_signed,
expires: sh_out(`openssl x509 -enddate -noout -in ${q(cert.cert)} 2>/dev/null | cut -d= -f2`) } : null,
port_owners: m.settings.portal_enabled ? [] : health.tcp_port_owners(m.settings.portal_port),
tcp_taken: tcp_taken(m),
portal_public_port: core.portal_public_port(m),
geo_cached: length(keys(geo.load().ips)),
logs: logs_info(m),
@@ -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');
@@ -115,10 +116,11 @@ function settings_update(a) {
check_portal(core.load(c), m);
return { restart, was: m.settings };
});
let s = null;
if (res.restart)
system('/etc/init.d/dawnline reload >/dev/null 2>&1');
else
apply.sync();
s = apply.sync();
// The changes worth a line: the portal and the watchdog (other settings are housekeeping).
let now = core.load().settings, was = res.was;
if (now.portal_enabled != was.portal_enabled)
@@ -140,7 +142,10 @@ function settings_update(a) {
}
if (now.watchdog != was.watchdog)
admin_log('dawnline', now.watchdog ? 'turned on' : 'turned off', null, 'the watchdog', now.watchdog ? null : 'problems are only logged, nothing is repaired');
return settings_get({});
let out = settings_get({});
if (s?.warning)
out.warning = s.warning;
return out;
}
export const methods = {
@@ -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';
@@ -10,7 +12,30 @@ import * as geo from 'dawnline.geo';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg';
import { wrap, clamp_days } from 'dawnline.rpc.common';
import * as lookup from 'dawnline.lookup';
import * as health from 'dawnline.health';
import * as meter from 'dawnline.meter';
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
/** The router's public IPv4 (null when none or private). */
function wan_public(m) {
let w = lookup.router_wan(m);
return w && health.wan_kind(w) == 'public' ? w : null;
}
/** The router's own public addresses: a device at home that reaches the server through the WAN address (NAT loopback) is not "outside". */
function own_addresses(m) {
let own = {};
for (let id, srv in m.servers) {
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
if (a)
own[a] = true;
}
let wan = lookup.wan_ipv4('wan');
if (wan)
own[wan] = true;
return own;
}
/** Router location plus one point per (device, recent client address). */
function geo_view(m, usage, dmp) {
@@ -19,14 +44,25 @@ function geo_view(m, usage, dmp) {
let cache = geo.load();
let points = [];
let now = time();
// The router's own public addresses: a device at home that reaches the server through the
// WAN address (NAT loopback) shows up from there. Home is not a place people connect from.
let own = {};
for (let id, srv in m.servers) {
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
if (a)
own[a] = true;
}
let wan = lookup.wan_ipv4('wan');
if (wan)
own[wan] = true;
for (let id, d in m.devices) {
let rec = usage.devices?.[id];
let peer = dmp.peers[d.public_key];
let cur = live.endpoint_ip(peer?.endpoint);
let online = live.online(dmp, id, peer);
for (let ip, ts in rec?.ips ?? {}) {
// Local (LAN / CGNAT) client addresses are not shown on the map.
let pl = geo.is_public(ip) ? geo.place(cache, ip) : null;
// Local (LAN / CGNAT) client addresses and the router's own are not shown on the map.
let pl = geo.is_public(ip) && !own[ip] ? geo.place(cache, ip) : null;
if (!pl)
continue;
push(points, {
@@ -72,16 +108,29 @@ function server_view(m, srv, usage, dmp, rates, days) {
online++;
}
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
// The newest handshake from a public address that is not the router's own:
// proof that the port is reachable from the internet.
let own = own_addresses(m);
let reached = 0;
for (let id, d in m.devices)
if (m.people[d.person]?.server == srv.id)
for (let ip, ts in usage.devices?.[id]?.ips ?? {})
if (geo.is_public(ip) && !own[ip] && ts > reached)
reached = ts;
return {
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet,
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet, reached,
endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled,
lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
// What devices get now, by kind (mtu 0 = automatic).
mtus: { computer: core.device_mtu(srv, { kind: 'computer' }), phone: core.device_mtu(srv, { kind: 'phone' }) },
address: core.server_address(srv), up: !!st.up, uptime: st.uptime ?? 0,
// Why the tunnel cannot run (its interface name belongs to another network section), or null.
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).
@@ -91,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();
@@ -142,7 +192,7 @@ function status(a) {
settings: {
portal_enabled: s.portal_enabled, portal_port: s.portal_port, portal_host: s.portal_host,
portal_public_port: core.portal_public_port(m),
paused_all: s.paused_all, default_device_limit: s.default_device_limit, domain: s.domain,
default_device_limit: s.default_device_limit, domain: s.domain,
hostnames: s.hostnames, geo_enabled: s.geo_enabled, home_dns_fallback: s.home_dns_fallback,
},
servers,
@@ -155,12 +205,18 @@ function status(a) {
like_home: loop.status(),
awg: awg.caps(),
awg_state: awg.state(),
// The router's public IPv4 (null when none or private): a server whose public address is an old one is told so.
wan: wan_public(m),
};
}
/** The newest `limit` events; `person` keeps one person's only, `since` only those after a time. */
function events_list(a) {
// Tunnel down/up events of older versions: the service log tells it better (names, reasons).
let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up');
let person = str(a.person), since = +a.since || 0;
let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up' &&
(!person || e.person == person) && (!since || (e.ts ?? 0) > since));
let n = +a.limit || 300;
return { events: with_hosts(slice(ev, length(ev) > n ? length(ev) - n : 0)), total: length(ev), policy: live.policy() };
}
@@ -171,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);
@@ -202,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');
@@ -225,14 +281,28 @@ function usage_clear(a) {
}
/** The live revision (dawnline.live.PRESENCE): pages refresh when it moves; 0 without the agent. */
/** The live revision, and the version answering (a page notices an update under it). */
function rev() {
return { rev: +(live.presence()?.rev ?? 0) };
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 }, call: wrap(events_list) },
events: { args: { limit: 300, person: '', since: 0 }, call: wrap(events_list) },
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
usage_clear: { args: { scope: '', id: '' }, call: wrap(usage_clear) },
geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) },
@@ -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,8 +79,8 @@ function status(a) {
function releases(a) {
let page = +(a.page ?? 1);
if (page != int(page) || page < 1 || page > 50)
die('Unknown page.');
return { releases: map(gh.releases(REPO, page), (x) => ({ ...x, body: null, digests: null })), page };
die(_('Unknown page.'));
return { releases: map(gh.releases(REPO, page), (x) => ({ ...x, body: null, digests: null, ids: null })), page };
}
/** Release notes for What's new: Dawnline by tag, or an AmneziaWG build's release. */
@@ -80,20 +88,20 @@ 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}.`);
return { ...r, digests: null, repo: rp };
die(sprintf(_('No release %s in %s.'), tag, rp));
return { ...r, digests: null, ids: null, repo: rp };
}
/** What changed between the installed Dawnline and a release (points for the Components tab). */
function changes(a) {
let to = a.to ?? '', from = a.from ?? '';
if (!match(to, TAG) || (from != '' && !match(from, TAG)))
die('Unknown release.');
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/, '') ] : []))
@@ -103,29 +111,34 @@ function changes(a) {
}
/**
* Start an update job. Returns the new job once its worker has written it,
* else null (the caller follows updates_status); never an older job.
* Start an update job. Returns the new job once its worker has written it
* (a quick check may be over by then), else null (the caller follows
* updates_status); never an older job. Waits two seconds at most: LuCI gives
* up on a call after twenty.
*/
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 t0 = time(), prev = read_json(upd.JOB_FILE, null)?.id;
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)
if (j && j.id != prev && j.started >= t0)
return { started: true, job: j };
system('usleep 100000 2>/dev/null || sleep 1');
// ucode's own sleep: OpenWrt's BusyBox has no usleep.
sleep(100);
}
return { started: true, job: null };
}
@@ -6,8 +6,9 @@
// config_get_bool does, so the service and the code never disagree.
import { stat } from 'fs';
import { ip2int, valid_host } from 'dawnline.util';
import { ip2int, valid_host, ulength } from 'dawnline.util';
import { INTERVALS, TARGETS } from 'dawnline.updates';
import { _ } from 'dawnline.i18n';
/* ---------- addresses ---------- */
@@ -107,39 +108,38 @@ export function to_int(v, dflt, lo, hi) {
/* ---------- the settings section ---------- */
/*
* type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | text | targets
* 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 and text length; 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_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,
msg: 'Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).' },
portal_title: { type: 'text', dflt: 'Dawnline', max: 64, msg: 'Portal title: up to 64 characters on one line.' },
portal_redirect: { type: 'url', dflt: '', msg: 'Redirect must be a full http:// or https:// address.' },
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.' },
geo_enabled: { type: 'bool', dflt: true },
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ], msg: 'Unknown location service.' },
domain: { type: 'domain', dflt: 'lan' },
// Off until the admin turns it on: lookups send people's addresses to a third party.
geo_enabled: { type: 'bool', dflt: false },
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ] },
log_connections: { type: 'bool', dflt: true },
watchdog: { type: 'bool', dflt: true },
log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999, 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,13 +182,17 @@ 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 : []))
if (type(x) == 'string' && valid_host(trim(x)) && index(lst, trim(x)) < 0)
for (let x in (type(val) == 'array' ? val : [])) {
// A typo must not vanish on Save: refused, like the main address.
if (type(x) != 'string' || (trim(x) != '' && !valid_host(trim(x))))
bad(key);
if (trim(x) != '' && index(lst, trim(x)) < 0)
push(lst, trim(x));
}
return length(lst) ? lst : null;
}
if (t == 'targets') {
@@ -186,44 +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);
}
else if (t == 'text') {
if (length(val) > spec.max || match(val, /[[:cntrl:]]/))
bad(spec, key);
bad(key);
}
return val;
};
@@ -5,13 +5,22 @@
import { lock, unlock } from 'dawnline.util';
import * as core from 'dawnline.core';
import { _ } from 'dawnline.i18n';
/** Section names that are never ids of people, devices, servers, services or circles. */
export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
/** Commit the dawnline config and keep it readable by root only. */
/**
* Commit the dawnline config and keep it readable by root only. A commit
* that did not reach flash (full or read-only overlay) is an error: the
* caller's change never happened, and nothing downstream may act on it.
*/
export function commit(c) {
c.commit(core.CONFIG);
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,18 +19,18 @@ 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 };
};
/**
* The sha256 a release publishes for a file: GitHub's own (API), else the
* release's sha256sums.txt fetched straight from github.com (never a mirror).
* release's sha256sums.txt fetched straight from GitHub (never a mirror).
*/
function want_sha(ctx, tag, asset, dir) {
let want = gh.asset_sha256(REPO, tag, asset);
@@ -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,22 +178,25 @@ export function install(ctx, arg) {
}
out.to = replace(tag, /^v/, '');
ctx.versions(VERSION, out.to);
let f = fetch(ctx, tag, ctx.work);
// The version being replaced, for Roll back (downloaded again: opkg keeps no package files).
if (ctx.pol.keep && out.to != VERSION && upd.kept('app')?.version != VERSION) {
ctx.phase(`Keeping Dawnline ${VERSION} for rollback`);
let files = fetch(ctx, tag, ctx.work);
// The version being replaced, for Roll back (downloaded again: opkg keeps
// no package files). Always for an automatic run: nobody is there to
// recover a router whose new version does not come up (postupdate rolls
// back to it on its own).
if ((ctx.pol.keep || ctx.auto?.()) && out.to != VERSION && upd.kept('app')?.version != VERSION) {
ctx.phase(sprintf(_('Keeping Dawnline %s for rollback'), VERSION));
try {
system(`mkdir -p '${ctx.work}/keep'`);
upd.keep('app', VERSION, [ fetch(ctx, tag_of(VERSION), `${ctx.work}/keep`) ]);
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,13 +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') };
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;
@@ -85,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');
@@ -109,32 +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}'`);
}
sh('rmmod amneziawg');
if (stat('/sys/module/amneziawg'))
ctx.run('rmmod amneziawg');
let swapped = !stat('/sys/module/amneziawg');
if (swapped) {
ctx.run('modprobe amneziawg');
if (!stat('/sys/module/amneziawg'))
die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)"));
}
for (let i in ifaces)
sh(`ifup '${i}'`);
return swapped;
}
/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */
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. */
@@ -154,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';
@@ -181,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]);
@@ -210,22 +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);
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;
Loaded 100 of 350 files, more files were not shown because too many files have changed in this diff. Show more