Dawnline 0.20.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 / Backend (Go: vet, tests, a real ubusd and uhttpd) (push) Blocked by required conditions
CI / Package files (push) Blocked by required conditions

- **Backend rewritten in Go.** One daemon, `dawnlined`, replaces the whole ucode backend: the rpcd plugin, the agent, the CLI and the updater. The package no longer depends on ucode.
- **Per-architecture builds.** The release carries the backend for arm64, ARMv7, mips, mipsle and amd64; the router fetches its own after the package is installed and checks its sha256. Dawnline does not run on other architectures (older ARM, 32-bit x86, RISC-V).
- **Faster on the router.** A firewall sync takes 0.06 s instead of 0.9 s; a full apply takes about 300 ms. The portal is served by the daemon itself, without a CGI process per request.
- **Live pages.** The admin and the portal follow a live stream from the router instead of re-fetching the whole state every 30 seconds.
- **Admin redesigned in the portal's style.** Three sections (Overview · Log · Settings); a server is a page of its own with People, Places and Settings; a device opens as a dialog over its person.
- **Changes wait for «Apply».** Every setting, and a person's access, is staged in one dock before it reaches the router.
- **Configuration rollout.** After a change that makes devices fetch their configuration again, the admin shows how many have fetched it and who has not. Every setting shows beforehand (⟳N) how many devices it will touch.
- **Waiting for a decision.** Overview and People put first the people who need one (access ended, limit reached, a device that does not connect), each with its one action a tap away.
- **Bulk actions on people.** «Select» (or a long press on a card) picks several people to extend by a month, pause or resume at once.
- **Undo.** An action done from a card or a request is undone from its toast.
- **Update dialogs redesigned.** An update is one view from its question to its result; Dawnline's own update runs in it like every other, and the page reloads itself once the new version answers. Other versions are a list, each with its notes and Install on a page of its own.
- **Site to site: networks behind a router.** A router connected as a device can have networks behind it (up to eight, /16 to /30): the server routes them and applies the router's access to them. A network that shares addresses with a tunnel, the router's own networks or another site is refused by name.
- **Routers from the portal.** People can add a router and name its networks on their own page; the admin accepts or declines with a reason, or lets them through without asking.
- **Check access and Health know the networks behind routers.**
- **Usage limits reworked.** A monthly limit no longer follows the calendar. A person's month starts with their first traffic and ends a month later; the next one starts only when they connect again, so time away uses up none of it. Before, everyone's limit reset on the 1st.
- Extra data lasts until that person's month ends; «Reset usage» starts the month anew.
- A limit is for a month or for the whole term; the admin and the portal show when it resets.
- Charts that said «this month» show the last 30 days.
- After the update nobody loses what was counted: the month that was running becomes the person's first and ends on the 1st.
- **Access by time of day removed.** The Hours limit is gone from the admin, the portal and the backend; saved hours are dropped.
- **Expiry simplified.** An end date always stops access, with a heads-up three days before; the per-person choice is gone.
- **No false disconnects from sleeping phones.** A phone or a tablet stays online through ten minutes of silence.
- **Mobile Safari fixes.** Pressing a control no longer sends the page to its top; tab tracks that do not fit scroll; switches animate after a press.
This commit is contained in:
Aemeath committed 2026-11-13 09:43:50 +03:00
1 parent f8130e39a8
commit ac90575b0b
788 files changed
+139244 -41720

No files matched your search

+146
View File
@@ -0,0 +1,146 @@
// The networks behind people's routers (site to site): a router that connects as a device may have a
// network of its own behind it, which the tunnel then carries both ways. The settings keep them on the
// device (`list behind_net`); what may be one and which of them are in effect is decided here, for the
// methods that take them and for everything that is made from them. Pure.
package model
import "github.com/tickcount/luci-app-dawnline/backend/ipnet"
const (
// BehindMost is how many networks one router may have behind it.
BehindMost = 8
// BehindWidest is the shortest prefix one may have: a site's own network, never a whole private range.
BehindWidest = 16
)
// Only private ranges stand behind a router: a public one would take that part of the internet away from
// everyone who reaches the network.
var behindRanges = []string{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"}
// BehindNet reads a network as one may stand behind a router: "a.b.c.d/len" inside a private range, from
// /16 to /30. It is told from its first address ("192.168.2.7/24" is 192.168.2.0/24). why is "" for one
// that will do, else what is wrong with it: "form" (no network written out), "wide" (wider than /16) or
// "public" (outside the private ranges).
func BehindNet(s string) (n ipnet.Net, why string) {
n, ok := ipnet.Subnet(s)
if !ok {
return ipnet.Net{}, "form"
}
if n.Prefix < BehindWidest {
return ipnet.Net{}, "wide"
}
for _, r := range behindRanges {
if in, _ := ipnet.Any(r); in.Holds(n.Base) {
return n, ""
}
}
return ipnet.Net{}, "public"
}
// Clash is what a network behind a device runs into: Net is the other network, which is a server's own
// subnet (Server), one of the router's own networks (neither), or behind another device (Device).
type Clash struct {
Net string
Server, Device string
}
// BehindClash is what a network behind a device shares addresses with, or nil: a tunnel's subnet, one of
// the router's own networks (own: nil when they are not known) or a network behind another device. Two
// ends of a tunnel with the same addresses reach neither.
func (m *Model) BehindClash(n ipnet.Net, device string, own []string) *Clash {
for _, id := range m.serverIDs {
if s, ok := ipnet.Subnet(m.Servers[id].Subnet); ok && s.Overlaps(n) {
return &Clash{Net: s.String(), Server: id}
}
}
for _, o := range own {
if x, ok := ipnet.Any(o); ok && x.Prefix >= 1 && x.Overlaps(n) {
return &Clash{Net: x.String()}
}
}
for _, id := range m.deviceIDs {
if id == device {
continue
}
for _, o := range m.Devices[id].Behind {
if x, why := BehindNet(o); why == "" && x.Overlaps(n) {
return &Clash{Net: x.String(), Device: id}
}
}
}
return nil
}
// BehindOf is the networks behind each router that are in effect, by the device's id: what the tunnels'
// peers, the routes, the access rules and other devices' configurations are made from. Only a router has
// any. A line that is no such network, one over BehindMost, and one that shares addresses with a tunnel,
// with the router's own networks (own: nil when they are not known) or with a network already counted (an
// earlier device's in the settings' order, or an earlier one of its own) is left out: a bad line in the
// file never takes a route away from the router or from another site. What is asked for and not answered
// is in effect nowhere.
func (m *Model) BehindOf(own []string) map[string][]string {
out := map[string][]string{}
var counted []ipnet.Net
for _, id := range m.deviceIDs {
d := m.Devices[id]
// a router that waits for the admin's answer is no device of the tunnel yet
if d.Kind != "router" || d.Waiting {
continue
}
for _, s := range d.Behind {
n, why := BehindNet(s)
if why != "" || len(out[id]) >= BehindMost {
continue
}
taken := false
for _, c := range counted {
taken = taken || c.Overlaps(n)
}
if c := m.BehindClash(n, id, own); taken || (c != nil && c.Device == "") {
continue
}
counted = append(counted, n)
out[id] = append(out[id], n.String())
}
}
return out
}
// HomeAccess tells whether a person is part of home: all of it or the networks picked for them, and the
// devices the server lets reach each other. Not someone held to a few home services.
func (p *Person) HomeAccess() bool {
return p.Access == "both" || (p.Access == "lan" && len(p.Services) == 0)
}
// MeshGroup is whom a person's devices reach directly where the server keeps devices within circles: the
// person's circle on that server, else the person's own devices.
func (m *Model) MeshGroup(p *Person) string {
if c := m.Circles[p.Circle]; c != nil && c.Server == p.Server {
return "c:" + c.ID
}
return "p:" + p.ID
}
// BehindReach is the networks behind other routers that a person's device reaches through the tunnel, in
// the settings' order: those of the devices it reaches itself (everyone's on the server, or its circle's,
// where their owners are part of home too). behind is the networks in effect (BehindOf); device is the
// device's id, "" for a configuration that is nobody's yet.
func (m *Model) BehindReach(p *Person, device string, behind map[string][]string) []string {
srv := m.Servers[p.Server]
if srv == nil || srv.Mesh == "off" || !p.HomeAccess() {
return nil
}
var out []string
for _, id := range m.deviceIDs {
q := m.People[m.Devices[id].Person]
if id == device || len(behind[id]) == 0 || q == nil || q.Server != p.Server || !q.HomeAccess() {
continue
}
if srv.Mesh == "circles" && m.MeshGroup(p) != m.MeshGroup(q) {
continue
}
out = append(out, behind[id]...)
}
return out
}
+261
View File
@@ -0,0 +1,261 @@
package model
import (
"reflect"
"testing"
"github.com/tickcount/luci-app-dawnline/backend/ipnet"
"github.com/tickcount/luci-app-dawnline/backend/uci"
)
func TestWhatMayStandBehindARouter(t *testing.T) {
for _, c := range []struct{ in, net, why string }{
{"192.168.2.0/24", "192.168.2.0/24", ""},
{"192.168.2.7/24", "192.168.2.0/24", ""},
{"10.5.0.0/16", "10.5.0.0/16", ""},
{"172.31.255.0/30", "172.31.255.0/30", ""},
{"192.168.2.0", "", "form"},
{"192.168.2.0/31", "", "form"},
{"192.168.2.0/24 ", "", "form"},
{"home", "", "form"},
{"", "", "form"},
{"10.0.0.0/8", "", "wide"},
{"10.4.0.0/15", "", "wide"},
{"8.8.8.0/24", "", "public"},
{"172.32.0.0/24", "", "public"},
{"100.64.0.0/24", "", "public"},
{"169.254.1.0/24", "", "public"},
} {
n, why := BehindNet(c.in)
if why != c.why || (why == "" && n.String() != c.net) {
t.Errorf("%q: %s %q, want %s %q", c.in, n, why, c.net, c.why)
}
}
}
// A household for the networks behind routers: two servers, one that keeps devices within circles.
const sites = `
config server 'home'
option subnet '10.77.0.0/24'
option mesh 'all'
config server 'cabin'
option subnet '10.78.0.0/24'
option mesh 'circles'
config circle 'fam'
option server 'cabin'
config person 'anna'
option server 'home'
option access 'both'
config person 'boris'
option server 'home'
option access 'lan'
config person 'clara'
option server 'home'
option access 'internet'
config person 'eva'
option server 'home'
option access 'lan'
list service 'nas'
config person 'hana'
option server 'cabin'
option access 'both'
option circle 'fam'
config person 'ivan'
option server 'cabin'
option access 'both'
option circle 'fam'
config person 'kira'
option server 'cabin'
option access 'both'
config device 'r1'
option person 'anna'
option kind 'router'
option address '10.77.0.2'
list behind_net '192.168.2.9/24'
list behind_net '10.77.0.128/25'
list behind_net 'the garage'
list behind_net '192.168.2.128/25'
list behind_net '192.168.50.0/24'
list behind_net '10.78.0.0/16'
config device 'phone'
option person 'anna'
option address '10.77.0.3'
list behind_net '192.168.9.0/24'
config device 'r2'
option person 'boris'
option kind 'router'
option address '10.77.0.4'
list behind_net '192.168.2.0/23'
list behind_net '172.16.9.0/24'
config device 'r3'
option person 'clara'
option kind 'router'
option address '10.77.0.5'
option behind_net '192.168.30.0/24'
config device 'r4'
option person 'eva'
option kind 'router'
option address '10.77.0.6'
list behind_net '192.168.40.0/24'
config device 'r5'
option person 'hana'
option kind 'router'
option address '10.78.0.2'
list behind_net '192.168.60.0/24'
config device 'iphone'
option person 'ivan'
option address '10.78.0.3'
config device 'kphone'
option person 'kira'
option address '10.78.0.4'
`
func household(t *testing.T, text string) *Model {
t.Helper()
c, err := uci.Parse(text)
if err != nil {
t.Fatal(err)
}
return Load(c, nil)
}
func TestNetworksInEffect(t *testing.T) {
m := household(t, sites)
// the router has 192.168.50.0/24 itself; a tunnel's subnet is never behind anyone; r1 came first
got := m.BehindOf([]string{"192.168.50.0/24", "192.168.77.0/24"})
want := map[string][]string{"r1": {"192.168.2.0/24"}, "r2": {"172.16.9.0/24"}, "r3": {"192.168.30.0/24"}, "r4": {"192.168.40.0/24"}, "r5": {"192.168.60.0/24"}}
if !reflect.DeepEqual(got, want) {
t.Errorf("in effect: %v, want %v", got, want)
}
// what the router has itself is not known: only the settings speak
if got := m.BehindOf(nil)["r1"]; !reflect.DeepEqual(got, []string{"192.168.2.0/24", "192.168.50.0/24"}) {
t.Errorf("r1 with nothing known of the router: %v", got)
}
// more than a router may have: the first BehindMost count
many := "config server 's'\n\toption subnet '10.77.0.0/24'\n\nconfig person 'p'\n\toption server 's'\n\nconfig device 'r'\n\toption person 'p'\n\toption kind 'router'\n"
for i := 0; i < BehindMost+3; i++ {
many += "\tlist behind_net '192.168." + string(rune('0'+i/10)) + string(rune('0'+i%10)) + ".0/24'\n"
}
if got := household(t, many).BehindOf(nil)["r"]; len(got) != BehindMost || got[BehindMost-1] != "192.168.7.0/24" {
t.Errorf("over the most: %v", got)
}
}
func TestWhatANetworkRunsInto(t *testing.T) {
m := household(t, sites)
own := []string{"192.168.50.0/24"}
for _, c := range []struct {
net, device string
want *Clash
}{
{"192.168.70.0/24", "", nil},
{"10.77.0.0/25", "", &Clash{Net: "10.77.0.0/24", Server: "home"}},
{"10.78.0.0/16", "", &Clash{Net: "10.78.0.0/24", Server: "cabin"}},
{"192.168.50.128/25", "", &Clash{Net: "192.168.50.0/24"}},
{"192.168.60.0/24", "", &Clash{Net: "192.168.60.0/24", Device: "r5"}},
// its own network is no clash
{"192.168.60.0/24", "r5", nil},
{"172.16.0.0/16", "r5", &Clash{Net: "172.16.9.0/24", Device: "r2"}},
} {
n, _ := ipnet.Any(c.net)
if got := m.BehindClash(n, c.device, own); !reflect.DeepEqual(got, c.want) {
t.Errorf("%s for %q: %+v, want %+v", c.net, c.device, got, c.want)
}
}
}
func TestWhoReachesWhatIsBehind(t *testing.T) {
m := household(t, sites)
behind := m.BehindOf([]string{"192.168.50.0/24"})
for _, c := range []struct {
person, device string
want []string
}{
// everyone reaches everyone on the server: every network of people who are part of home, but its own
{"anna", "phone", []string{"192.168.2.0/24", "172.16.9.0/24"}},
{"anna", "r1", []string{"172.16.9.0/24"}},
{"boris", "r2", []string{"192.168.2.0/24"}},
// the internet alone, or a few home services: no part of home
{"clara", "r3", nil},
{"eva", "r4", nil},
// within circles: the circle's router, and nobody else's
{"ivan", "iphone", []string{"192.168.60.0/24"}},
{"kira", "kphone", nil},
{"hana", "r5", nil},
} {
if got := m.BehindReach(m.People[c.person], c.device, behind); !reflect.DeepEqual(got, c.want) {
t.Errorf("%s's %s reaches %v, want %v", c.person, c.device, got, c.want)
}
}
m.Servers["home"].Mesh = "off"
if got := m.BehindReach(m.People["anna"], "phone", behind); got != nil {
t.Errorf("devices do not reach each other, yet anna's phone reaches %v", got)
}
}
// What a router's owner asked for is read with the router, means nothing on another kind of device, and is
// in effect nowhere while the router waits.
func TestRequestsAsWritten(t *testing.T) {
m := household(t, sites+`
config device 'r6'
option person 'kira'
option kind 'router'
option address '10.78.0.5'
option waiting '1'
option asked '1700000000'
list ask_net '192.168.61.0/24'
list behind_net '192.168.62.0/24'
config device 'r7'
option person 'kira'
option kind 'router'
option address '10.78.0.6'
option declined 'because'
list declined_net '192.168.63.0/24'
config device 'tablet'
option person 'kira'
option kind 'tablet'
option address '10.78.0.7'
option waiting '1'
option declined 'talk'
list ask_net '192.168.64.0/24'
`)
r6, r7, tablet := m.Devices["r6"], m.Devices["r7"], m.Devices["tablet"]
if !r6.Waiting || r6.Asked != 1700000000 || !reflect.DeepEqual(r6.Ask, []string{"192.168.61.0/24"}) || r6.Declined != "" {
t.Errorf("a router that waits: %+v", r6)
}
if r7.Waiting || r7.Declined != "plain" || !reflect.DeepEqual(r7.DeclinedNets, []string{"192.168.63.0/24"}) || r7.Asked != 0 {
t.Errorf("a network turned down for a reason nobody knows: %+v", r7)
}
if tablet.Waiting || tablet.Ask != nil || tablet.Declined != "" {
t.Errorf("a tablet asks for nothing: %+v", tablet)
}
if got := m.BehindOf(nil)["r6"]; got != nil {
t.Errorf("a waiting router's network is in effect: %v", got)
}
if m.Servers["home"].PortalRouters != "ask" || m.Servers["home"].PortalNets != "ask" {
t.Errorf("the rules a server starts with: %q, %q", m.Servers["home"].PortalRouters, m.Servers["home"].PortalNets)
}
set := household(t, "config server 's'\n\toption portal_routers 'free'\n\toption portal_nets 'free'\n\nconfig server 'o'\n\toption portal_routers 'off'\n\toption portal_nets 'never'\n")
if s, o := set.Servers["s"], set.Servers["o"]; s.PortalRouters != "free" || s.PortalNets != "free" || o.PortalRouters != "off" || o.PortalNets != "ask" {
t.Errorf("the rules as set: %+v, %+v", s, o)
}
}
+105
View File
@@ -0,0 +1,105 @@
// What follows from the settings about a server's addresses and a device's link, as dawnline.core works
// them out (server_address, tunnel_mtu, device_mtu, endpoint_host, dns_list, client_dns). Pure.
package model
import "github.com/tickcount/luci-app-dawnline/backend/ipnet"
const (
// autoMTU is a tunnel's MTU when none is set, before its disguise's padding; mobileMTU what a phone
// or a tablet gets at the most, and the least a tunnel has.
autoMTU = 1380
mobileMTU = 1280
// A device's own MTU is taken within this range.
mtuMin, mtuMax = 1280, 1500
)
// ToInt is a value as a whole number as ucode reads one (what is after the point is dropped), or dflt
// when it is empty or no number.
func ToInt(v string, dflt int) int {
if v == "" {
return dflt
}
n, ok := number(v)
if !ok {
return dflt
}
return int(n)
}
// Number is a value as ucode's unary plus reads it; ok is false for what is no number.
func Number(v string) (float64, bool) { return number(v) }
// ServerAddress is the router's address inside a server's subnet (its first host), or "".
func ServerAddress(srv *Server) string {
n, ok := ipnet.Subnet(srv.Subnet)
if !ok {
return ""
}
return ipnet.String(n.First())
}
// TunnelMTU is the server's tunnel MTU: the one set, or the automatic one for its disguise.
func TunnelMTU(srv *Server) int {
if srv.MTU != 0 {
return srv.MTU
}
return max(mobileMTU, autoMTU-ToInt(srv.Obf["s4"], 0))
}
// DeviceMTU is the MTU a device's configuration carries: its own when the admin set one, else the
// tunnel's, at most 1280 for phones and tablets.
func DeviceMTU(srv *Server, dev *Device) int {
if dev.MTU >= mtuMin && dev.MTU <= mtuMax {
return dev.MTU
}
mtu := TunnelMTU(srv)
if dev.Kind == "phone" || dev.Kind == "tablet" {
return min(mtu, mobileMTU)
}
return mtu
}
// EndpointHost is the address devices connect to: the server's own, else the portal's.
func (m *Model) EndpointHost(srv *Server) string {
if srv.Endpoint != "" {
return srv.Endpoint
}
return m.Settings.PortalHost
}
// DNSList is the DNS a server's clients are given: the servers set for it, else the router's address in
// its subnet (which never changes after setup; the router forwards each query where it belongs).
func DNSList(srv *Server) []string {
if srv == nil {
return []string{}
}
if len(srv.DNS) > 0 {
return srv.DNS
}
if a := ServerAddress(srv); a != "" {
return []string{a}
}
return []string{}
}
// ClientDNS is the DNS a person's devices use. Home-only people keep their device's DNS unless they chose
// home names; then the first server is Dawnline's resolver (reached through the tunnel) and the second
// the fallback the device uses when the tunnel is down.
func (m *Model) ClientDNS(srv *Server, p *Person) []string {
if p == nil || p.Access != "lan" {
return DNSList(srv)
}
if p.DNSMode != "home" {
return []string{}
}
out := []string{}
a := ServerAddress(srv)
if a != "" {
out = append(out, a)
}
if f := m.Settings.HomeDNSFallback; f != "" && f != a {
out = append(out, f)
}
return out
}
+478
View File
@@ -0,0 +1,478 @@
// Package model is Dawnline's settings as the backend works with them: the servers, the people, their
// devices, the circles and the home services, read from /etc/config/dawnline with every default filled in
// and every value brought to its type.
//
// It reads exactly what the ucode model reads (dawnline.core load(), dawnline.schema get()): the same
// defaults, the same leniency with what older versions and hands have written. testdata holds the two to
// each other: each *.json is what ucode made of the *.uci beside it (scripts/ucode-golden.sh).
//
// Reading only, and no state of the router: who is online, what is used, which tunnel is up live elsewhere.
package model
import (
"regexp"
"strconv"
"strings"
"time"
"github.com/tickcount/luci-app-dawnline/backend/uci"
"github.com/tickcount/luci-app-dawnline/backend/zone"
)
// What a value may be (dawnline.core).
var (
Access = []string{"lan", "internet", "both"}
Kinds = []string{"computer", "phone", "tablet", "router", "other"}
MobileKinds = []string{"phone", "tablet"}
Mesh = []string{"off", "all", "circles"}
// PortalRouters is what a person may do about a router on their own page: nothing (the admin adds
// it), ask for one, or add one at once. PortalNets: ask for a network behind it, or add one at once.
PortalRouters = []string{"off", "ask", "free"}
PortalNets = []string{"ask", "free"}
// Declined is why the admin turned a person's request down, as the settings keep it: the networks
// share addresses with one here, they are not needed here, the person should talk to the admin
// first, or no reason given. Each page words it in its reader's language.
Declined = []string{"overlap", "unneeded", "talk", "plain"}
// ObfKeys are the AmneziaWG disguise options a server stores.
ObfKeys = []string{"jc", "jmin", "jmax", "s1", "s2", "s3", "s4", "h1", "h2", "h3", "h4", "i1", "i2", "i3", "i4", "i5",
"header_protection_key", "content_padding_addition", "rekey_after_time", "rekey_timeout", "reject_after_time",
"keepalive_timeout", "max_handshake_attempts", "random_trailers", "disable_cookies"}
)
// circleColors is how many colours a circle may have.
const circleColors = 8
// Model is the whole of the settings.
type Model struct {
Settings Settings `json:"settings"`
Servers map[string]*Server `json:"servers"`
People map[string]*Person `json:"people"`
Devices map[string]*Device `json:"devices"`
Services map[string]*Service `json:"services"`
Circles map[string]*Circle `json:"circles"`
// The ids in the file's order: what is done for each server, person or device is done in the order the
// admin made them, the same on every run.
serverIDs, personIDs, deviceIDs []string
circleIDs, serviceIDs []string
}
// ServerIDs, PersonIDs and DeviceIDs are the ids in the file's order.
func (m *Model) ServerIDs() []string { return m.serverIDs }
func (m *Model) PersonIDs() []string { return m.personIDs }
func (m *Model) DeviceIDs() []string { return m.deviceIDs }
// WithoutServers is the same settings with no server at all (what a teardown works from).
func (m *Model) WithoutServers() *Model {
out := *m
out.Servers, out.serverIDs = map[string]*Server{}, nil
return &out
}
// CircleIDs and ServiceIDs are the circles and the services in the file's order: the order they are listed in.
func (m *Model) CircleIDs() []string { return m.circleIDs }
func (m *Model) ServiceIDs() []string { return m.serviceIDs }
// Settings is the `settings` section.
type Settings struct {
PortalEnabled bool `json:"portal_enabled"`
PortalPort int `json:"portal_port"`
PortalHost string `json:"portal_host"`
PortalAlt []string `json:"portal_alt"`
PortalCert string `json:"portal_cert"`
PortalKey string `json:"portal_key"`
PortalRedirect string `json:"portal_redirect"`
DefaultDeviceLimit int `json:"default_device_limit"`
GeoEnabled bool `json:"geo_enabled"`
GeoProvider string `json:"geo_provider"`
Hostnames bool `json:"hostnames"`
Domain string `json:"domain"`
LogConnections bool `json:"log_connections"`
LogLevel string `json:"log_level"`
Watchdog bool `json:"watchdog"`
HomeDNSFallback string `json:"home_dns_fallback"`
Updates Updates `json:"updates"`
Retention Retention `json:"retention"`
}
// Updates is when and what Dawnline updates on its own.
type Updates struct {
Check bool `json:"check"`
Interval string `json:"interval"`
Auto bool `json:"auto"`
Mode string `json:"mode"`
Time string `json:"time"`
Targets []string `json:"targets"`
Keep bool `json:"keep"`
Mirrors bool `json:"mirrors"`
}
// Retention is how long the log and the traffic history are kept, as written: who applies it reads the
// values by their own rules. A value is a string, a list of strings, or nil when it is not set.
type Retention struct {
LogKeepDays any `json:"log_keep_days"`
LogMax any `json:"log_max"`
LogCategory any `json:"log_category"`
LogConnections any `json:"log_connections"`
LogPersist any `json:"log_persist"`
UsageKeepDays any `json:"usage_keep_days"`
UsageKeepMonths any `json:"usage_keep_months"`
}
// Server is one AmneziaWG server.
type Server struct {
ID string `json:"id"`
Name string `json:"name"`
Ifname string `json:"ifname"`
Port int `json:"port"`
Subnet string `json:"subnet"`
Endpoint string `json:"endpoint"`
MTU int `json:"mtu"` // 0: worked out
DNS []string `json:"dns"`
Keepalive int `json:"keepalive"`
PrivateKey string `json:"private_key"`
PublicKey string `json:"public_key"`
Preset string `json:"preset"`
LanZone string `json:"lan_zone"`
WanZone string `json:"wan_zone"`
AutoWan bool `json:"auto_wan"`
WanDevice string `json:"wan_device"`
AutoLan bool `json:"auto_lan"`
LanDevices []string `json:"lan_devices"`
DetectedWan string `json:"detected_wan"`
DetectedLan string `json:"detected_lan"`
LanLike bool `json:"lan_like"`
Mesh string `json:"mesh"`
// PortalRouters and PortalNets are what people may do about routers on their own pages (see the lists).
PortalRouters string `json:"portal_routers"`
PortalNets string `json:"portal_nets"`
Enabled bool `json:"enabled"`
Obf map[string]string `json:"obf"`
DeviceMesh bool `json:"device_mesh"`
// Blocked: why the server is kept down (another tunnel has its interface's name), when it is.
Blocked any `json:"blocked,omitempty"`
}
// Person is someone with access.
type Person struct {
ID string `json:"id"`
Server string `json:"server"`
Name string `json:"name"`
Access string `json:"access"`
DeviceLimit int `json:"device_limit"`
Code string `json:"code"`
CodeSet int `json:"code_set"`
Expires string `json:"expires"`
QuotaGB float64 `json:"quota_gb"`
QuotaPeriod string `json:"quota_period"`
Paused bool `json:"paused"`
DNSMode string `json:"dns_mode"`
BonusGB float64 `json:"bonus_gb"`
BonusUntil int `json:"bonus_until"`
Services []string `json:"services"`
HomeNets []string `json:"home_nets"`
Circle string `json:"circle"`
Note string `json:"note"`
Created int `json:"created"`
// Devices are the ids of the person's devices, in the file's order.
Devices []string `json:"devices"`
}
// Device is one device of a person.
type Device struct {
ID string `json:"id"`
Person string `json:"person"`
Name string `json:"name"`
Kind string `json:"kind"`
Address string `json:"address"`
PublicKey string `json:"public_key"`
PrivateKey string `json:"private_key"`
PresharedKey string `json:"preshared_key"`
Created int `json:"created"`
CreatedBy string `json:"created_by"`
Disabled bool `json:"disabled"`
MTU int `json:"mtu"` // 0: the server's
// Keepalive is nil for the server's.
Keepalive *int `json:"keepalive"`
LanBypass bool `json:"lan_bypass"`
// Behind is the networks behind a router, as written: BehindOf tells which of them are in effect.
Behind []string `json:"behind,omitempty"`
// What its owner asked for on their own page and the admin has not answered: Waiting, the router itself
// (added there, it is no device of the tunnel until the admin takes it); Ask, networks behind it
// besides the ones it has; Asked, when (the later of the two).
Waiting bool `json:"waiting,omitempty"`
Ask []string `json:"ask,omitempty"`
Asked int `json:"asked,omitempty"`
// Declined is why the admin turned the last of that down ("": nothing is turned down), DeclinedNets
// the networks it was about (none: the router itself). The owner reads it until they clear it or ask again.
Declined string `json:"declined,omitempty"`
DeclinedNets []string `json:"declined_nets,omitempty"`
}
// Circle is a group of people whose devices reach each other.
type Circle struct {
ID string `json:"id"`
Server string `json:"server"`
Name string `json:"name"`
Color int `json:"color"`
}
// Service is something at home a person may be let reach.
type Service struct {
ID string `json:"id"`
Name string `json:"name"`
Address string `json:"address"`
Ports []string `json:"ports"`
}
// Load builds the model from the parsed file. `blocked` is which servers are kept down and why
// (/var/run/dawnline/netifd-blocked.json: nil when there is none).
func Load(c *uci.Config, blocked map[string]any) *Model {
set := c.Section("settings")
if set == nil {
set = &uci.Section{Values: map[string]uci.Value{}}
}
m := &Model{
Settings: settings(set),
Servers: map[string]*Server{}, People: map[string]*Person{}, Devices: map[string]*Device{},
Services: map[string]*Service{}, Circles: map[string]*Circle{},
}
for _, r := range c.OfType("server") {
id := r.Name
srv := &Server{
ID: id, Name: text(r, "name", id), Ifname: text(r, "ifname", id),
Port: toInt(r, "port", 51820), Subnet: text(r, "subnet", ""), Endpoint: text(r, "endpoint", ""),
MTU: toInt(r, "mtu", 0), DNS: list(r, "dns"), Keepalive: toInt(r, "keepalive", 25),
PrivateKey: text(r, "private_key", ""), PublicKey: text(r, "public_key", ""),
Preset: text(r, "preset", "standard"), LanZone: text(r, "lan_zone", "lan"), WanZone: text(r, "wan_zone", "wan"),
AutoWan: truth(r, "auto_wan", true), WanDevice: text(r, "wan_device", ""),
AutoLan: truth(r, "auto_lan", true), LanDevices: list(r, "lan_device"),
DetectedWan: text(r, "detected_wan", ""), DetectedLan: text(r, "detected_lan", ""),
LanLike: truth(r, "lan_like", true), Enabled: truth(r, "enabled", true), Obf: map[string]string{},
}
// Older files: device_mesh 0/1.
if mesh, _ := r.Get("mesh"); has(Mesh, mesh) {
srv.Mesh = mesh
} else if truth(r, "device_mesh", true) {
srv.Mesh = "all"
} else {
srv.Mesh = "off"
}
// a router and its networks are asked of the admin unless the admin said otherwise
srv.PortalRouters, srv.PortalNets = "ask", "ask"
if v, _ := r.Get("portal_routers"); has(PortalRouters, v) {
srv.PortalRouters = v
}
if v, _ := r.Get("portal_nets"); has(PortalNets, v) {
srv.PortalNets = v
}
for _, k := range ObfKeys {
if v, ok := r.Get(k); ok && v != "" {
srv.Obf[k] = v
}
}
srv.DeviceMesh = srv.Mesh != "off"
if why, kept := blocked[id]; kept && why != nil && why != false {
srv.Blocked = why
}
if _, twice := m.Servers[id]; !twice {
m.serverIDs = append(m.serverIDs, id)
}
m.Servers[id] = srv
}
for _, r := range c.OfType("person") {
id := r.Name
p := &Person{
ID: id, Server: text(r, "server", ""), Name: text(r, "name", id), Access: "internet",
DeviceLimit: toInt(r, "device_limit", m.Settings.DefaultDeviceLimit),
Code: text(r, "code", ""), CodeSet: toInt(r, "code_set", 0), Expires: text(r, "expires", ""),
QuotaGB: num(r, "quota_gb", 0), QuotaPeriod: "month", Paused: truth(r, "paused", false),
DNSMode: "device", BonusGB: num(r, "bonus_gb", 0),
BonusUntil: toInt(r, "bonus_until", 0), Services: list(r, "service"), HomeNets: list(r, "home_net"),
Circle: text(r, "circle", ""), Note: text(r, "note", ""), Created: toInt(r, "created", 0), Devices: []string{},
}
if a, _ := r.Get("access"); has(Access, a) {
p.Access = a
}
if v, _ := r.Get("quota_period"); v == "total" {
p.QuotaPeriod = "total"
}
if v, _ := r.Get("dns_mode"); v == "home" {
p.DNSMode = "home"
}
// Extra data from before limit months lasted until the 1st of the month after the one it was given in.
if p.BonusUntil == 0 {
month, _ := r.Get("bonus_month")
p.BonusUntil = monthEnd(month)
}
if _, twice := m.People[id]; !twice {
m.personIDs = append(m.personIDs, id)
}
m.People[id] = p
}
for _, r := range c.OfType("device") {
id := r.Name
d := &Device{
ID: id, Person: text(r, "person", ""), Name: text(r, "name", id), Kind: "other",
Address: text(r, "address", ""), PublicKey: text(r, "public_key", ""), PrivateKey: text(r, "private_key", ""),
PresharedKey: text(r, "preshared_key", ""), Created: toInt(r, "created", 0), CreatedBy: text(r, "created_by", "admin"),
Disabled: truth(r, "disabled", false), MTU: toInt(r, "mtu", 0), LanBypass: truth(r, "lan_bypass", false),
}
if k, _ := r.Get("kind"); has(Kinds, k) {
d.Kind = k
}
if nets := list(r, "behind_net"); len(nets) > 0 {
d.Behind = nets
}
// a request is a router's: on anything else the lines mean nothing
if d.Kind == "router" {
d.Waiting = truth(r, "waiting", false)
if nets := list(r, "ask_net"); len(nets) > 0 {
d.Ask = nets
}
if d.Waiting || d.Ask != nil {
d.Asked = toInt(r, "asked", 0)
}
if v, _ := r.Get("declined"); v != "" {
d.Declined = "plain"
if has(Declined, v) {
d.Declined = v
}
if nets := list(r, "declined_net"); len(nets) > 0 {
d.DeclinedNets = nets
}
}
}
// Its own keep-alive, when it has one that is a number.
if v, ok := r.Get("keepalive"); ok && v != "" {
if n, isNumber := number(v); isNumber {
k := int(n)
d.Keepalive = &k
}
}
if _, twice := m.Devices[id]; !twice {
m.deviceIDs = append(m.deviceIDs, id)
}
m.Devices[id] = d
if p := m.People[d.Person]; p != nil {
p.Devices = append(p.Devices, id)
}
}
for _, r := range c.OfType("circle") {
id := r.Name
m.circleIDs = append(m.circleIDs, id)
m.Circles[id] = &Circle{ID: id, Server: text(r, "server", ""), Name: text(r, "name", id), Color: toInt(r, "color", 0) % circleColors}
}
for _, r := range c.OfType("service") {
id := r.Name
m.serviceIDs = append(m.serviceIDs, id)
m.Services[id] = &Service{ID: id, Name: text(r, "name", id), Address: text(r, "address", ""), Ports: list(r, "port")}
}
return m
}
/* ---------- values, read as dawnline.core reads them ---------- */
func has(set []string, v string) bool {
for _, x := range set {
if x == v {
return true
}
}
return false
}
// text is an option's string, or the default when it is not set.
func text(r *uci.Section, key, dflt string) string {
if v, ok := r.Get(key); ok {
return v
}
return dflt
}
// A number as ucode reads one from a string: spaces round it, a sign, then a decimal (which begins with a
// digit) or 0x, 0b, 0o and their digits. Empty is zero.
var numeric = regexp.MustCompile(`^[+-]?(0[xX][0-9a-fA-F]+|0[bB][01]+|0[oO][0-7]+|[0-9]+(\.[0-9]*)?([eE][+-]?[0-9]+)?)$`)
func number(s string) (float64, bool) {
t := strings.TrimSpace(s)
if t == "" {
return 0, true
}
if !numeric.MatchString(t) {
return 0, false
}
sign, digits := 1.0, strings.TrimLeft(t, "+-")
if strings.HasPrefix(t, "-") {
sign = -1
}
if len(digits) > 1 && digits[0] == '0' && strings.ContainsRune("xXbBoO", rune(digits[1])) {
base := map[byte]int{'x': 16, 'X': 16, 'b': 2, 'B': 2, 'o': 8, 'O': 8}[digits[1]]
n, err := strconv.ParseInt(digits[2:], base, 64)
return sign * float64(n), err == nil
}
f, err := strconv.ParseFloat(strings.TrimSuffix(digits, "."), 64)
return sign * f, err == nil
}
// toInt is an option as a whole number (what is after the point is dropped), or the default when it is
// not set, empty or no number.
func toInt(r *uci.Section, key string, dflt int) int {
v, ok := r.Get(key)
if !ok || v == "" {
return dflt
}
n, isNumber := number(v)
if !isNumber {
return dflt
}
return int(n)
}
func num(r *uci.Section, key string, dflt float64) float64 {
v, ok := r.Get(key)
if !ok || v == "" {
return dflt
}
n, isNumber := number(v)
if !isNumber {
return dflt
}
return n
}
// truth is an option as yes or no: 1, true, yes and on are yes, anything else that is written is no.
func truth(r *uci.Section, key string, dflt bool) bool {
v, ok := r.Get(key)
if !ok || v == "" {
return dflt
}
return v == "1" || v == "true" || v == "yes" || v == "on"
}
var separators = regexp.MustCompile(`[\s,]+`)
// list is a list option's entries, or an option's string cut at spaces and commas.
func list(r *uci.Section, key string) []string {
v, ok := r.Values[key]
if !ok {
return []string{}
}
if v.IsList {
return append([]string{}, v.List...)
}
return separators.Split(strings.TrimSpace(v.Str), -1)
}
var yearMonth = regexp.MustCompile(`^([0-9]{4})-([0-9]{2})$`)
// monthEnd is the first moment after a calendar month ("YYYY-MM") in the router's time; 0 for anything else.
func monthEnd(month string) int {
g := yearMonth.FindStringSubmatch(month)
if g == nil {
return 0
}
y, _ := strconv.Atoi(g[1])
mon, _ := strconv.Atoi(g[2])
return int(time.Date(y, time.Month(mon)+1, 1, 0, 0, 0, 0, zone.Local()).Unix())
}
+103
View File
@@ -0,0 +1,103 @@
package model
import (
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"github.com/tickcount/luci-app-dawnline/backend/uci"
"github.com/tickcount/luci-app-dawnline/backend/zone"
)
// Each fixture read by this model is what the ucode model read of it (the *.json beside it, written by
// scripts/ucode-golden.sh in an OpenWrt container whose clock is UTC).
func TestHeldToUcode(t *testing.T) {
zone.Set(time.UTC)
files, _ := filepath.Glob("testdata/*.uci")
if len(files) < 2 {
t.Fatalf("fixtures: %v", files)
}
for _, f := range files {
text, err := os.ReadFile(f)
if err != nil {
t.Fatal(err)
}
c, err := uci.Parse(string(text))
if err != nil {
t.Fatalf("%s: %v", f, err)
}
mine, err := json.Marshal(Load(c, nil))
if err != nil {
t.Fatal(err)
}
theirs, err := os.ReadFile(strings.TrimSuffix(f, ".uci") + ".json")
if err != nil {
t.Fatal(err)
}
var got, want any
json.Unmarshal(mine, &got)
if err := json.Unmarshal(theirs, &want); err != nil {
t.Fatalf("%s: the golden is not JSON: %v", f, err)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("%s: read differently than ucode reads it:\n%s", f, strings.Join(differ("", got, want), "\n"))
}
}
}
// differ names where two documents part, so a failure says which field.
func differ(path string, got, want any) []string {
g, gok := got.(map[string]any)
w, wok := want.(map[string]any)
if gok && wok {
var out []string
for k := range w {
if _, has := g[k]; !has {
out = append(out, path+"."+k+": missing, ucode has "+show(w[k]))
}
}
for k, v := range g {
if _, has := w[k]; !has {
out = append(out, path+"."+k+": "+show(v)+", ucode has none")
continue
}
out = append(out, differ(path+"."+k, v, w[k])...)
}
return out
}
if reflect.DeepEqual(got, want) {
return nil
}
return []string{path + ": " + show(got) + ", ucode has " + show(want)}
}
func show(v any) string {
b, _ := json.Marshal(v)
return string(b)
}
func TestNumbersAsUcodeReadsThem(t *testing.T) {
for s, want := range map[string]float64{" 90 ": 90, "0x10": 16, "1e3": 1000, "1.9": 1.9, "-3": -3, "": 0, "010": 10, "+5": 5, "5.": 5, "0b11": 3, "0o17": 15, "-1.9": -1.9} {
if got, ok := number(s); !ok || got != want {
t.Errorf("%q: %v %v, want %v", s, got, ok, want)
}
}
for _, s := range []string{"12abc", "1 2", ".5", "Infinity", "auto"} {
if _, ok := number(s); ok {
t.Errorf("%q read as a number", s)
}
}
}
// A server another tunnel keeps down says why.
func TestBlocked(t *testing.T) {
c, _ := uci.Parse("config server 'home'\nconfig server 'cabin'\n")
m := Load(c, map[string]any{"cabin": "another tunnel has its name"})
if m.Servers["home"].Blocked != nil || m.Servers["cabin"].Blocked != "another tunnel has its name" {
t.Fatalf("blocked: %v %v", m.Servers["home"].Blocked, m.Servers["cabin"].Blocked)
}
}
+179
View File
@@ -0,0 +1,179 @@
// The `settings` section read by its schema (dawnline.schema SETTINGS and get()): each setting has a type,
// a default and, for a number, a range; a value that is missing or not of its type reads as the default.
// The words the admin is told about a bad value stay with whoever saves settings; this only reads.
package model
import (
"net/netip"
"regexp"
"strconv"
"strings"
"github.com/tickcount/luci-app-dawnline/backend/uci"
)
// The update policy's choices (dawnline.updates).
var (
updateIntervals = []string{"6h", "12h", "1d", "7d"}
updateTargets = []string{"app", "amneziawg", "packages"}
)
func settings(s *uci.Section) Settings {
return Settings{
PortalEnabled: flag(s, "portal_enabled", false),
PortalPort: ranged(s, "portal_port", 8443, 1, 65535),
PortalHost: word(s, "portal_host", ""),
PortalAlt: words(s, "portal_alt", []string{}),
PortalCert: word(s, "portal_cert", ""),
PortalKey: word(s, "portal_key", ""),
PortalRedirect: word(s, "portal_redirect", ""),
DefaultDeviceLimit: ranged(s, "default_device_limit", 3, 1, 32),
// Off until the admin turns it on: lookups send people's addresses to a third party.
GeoEnabled: flag(s, "geo_enabled", false),
GeoProvider: choice(s, "geo_provider", "ipwho.is", []string{"ipwho.is", "ipapi.co"}),
Hostnames: flag(s, "hostnames", true),
Domain: word(s, "domain", "lan"),
LogConnections: flag(s, "log_connections", true),
LogLevel: choice(s, "log_level", "info", []string{"error", "warn", "info", "debug"}),
Watchdog: flag(s, "watchdog", true),
// Written as "none" for no fallback; not set means the default.
HomeDNSFallback: fallbackDNS(s),
Updates: updates(s),
Retention: Retention{
LogKeepDays: raw(s, "log_keep_days"), LogMax: raw(s, "log_max"), LogCategory: raw(s, "log_category"),
LogConnections: raw(s, "log_connections"), LogPersist: raw(s, "log_persist"),
UsageKeepDays: raw(s, "usage_keep_days"), UsageKeepMonths: raw(s, "usage_keep_months"),
},
}
}
// raw is a value as it is written: a string, a list, or nil.
func raw(s *uci.Section, key string) any {
v, ok := s.Values[key]
switch {
case !ok:
return nil
case v.IsList:
return append([]string{}, v.List...)
}
return v.Str
}
// flag is a yes or no (schema's: 1 on true yes enabled, 0 off false no disabled, any case; else the default).
func flag(s *uci.Section, key string, dflt bool) bool {
v, _ := s.Get(key)
switch strings.ToLower(strings.TrimSpace(v)) {
case "1", "on", "true", "yes", "enabled":
return true
case "0", "off", "false", "no", "disabled":
return false
}
return dflt
}
var wholeNumber = regexp.MustCompile(`^-?[0-9]{1,9}$`)
// ranged is a whole number within its range, or the default.
func ranged(s *uci.Section, key string, dflt, lo, hi int) int {
v, _ := s.Get(key)
v = strings.TrimSpace(v)
if !wholeNumber.MatchString(v) {
return dflt
}
n, _ := strconv.Atoi(v)
if n < lo || n > hi {
return dflt
}
return n
}
// word is a string setting, or the default when it is not set or empty.
func word(s *uci.Section, key, dflt string) string {
if v, ok := s.Get(key); ok && v != "" {
return v
}
return dflt
}
// words is a list setting without its empty entries (one written as an option is a list of one).
func words(s *uci.Section, key string, dflt []string) []string {
v, ok := s.Values[key]
if !ok {
return dflt
}
in := v.List
if !v.IsList {
in = []string{v.Str}
}
out := []string{}
for _, x := range in {
if x != "" {
out = append(out, x)
}
}
return out
}
func choice(s *uci.Section, key, dflt string, values []string) string {
if v, ok := s.Get(key); ok && has(values, v) {
return v
}
return dflt
}
func fallbackDNS(s *uci.Section) string {
v, ok := s.Get("home_dns_fallback")
switch {
case !ok || v == "":
return "1.1.1.1"
case v == "none":
return ""
}
if a, err := netip.ParseAddr(v); err == nil && a.Is4() {
return v
}
return "1.1.1.1"
}
// on is the update policy's yes or no (dawnline.updates: 1 true on yes; anything else written is no).
func on(s *uci.Section, key string, dflt bool) bool {
v, ok := s.Get(key)
if !ok || v == "" {
return dflt
}
return v == "1" || v == "true" || v == "on" || v == "yes"
}
var clock = regexp.MustCompile(`^([01]?[0-9]|2[0-3]):[0-5][0-9]$`)
func updates(s *uci.Section) Updates {
u := Updates{
Check: on(s, "update_check", true), Interval: "1d", Auto: on(s, "update_auto", true), Mode: "scheduled",
Time: "04:00", Keep: on(s, "update_keep", false), Mirrors: on(s, "update_mirrors", true),
// AmneziaWG is left out by default: a new kernel module restarts every tunnel.
Targets: []string{"app", "packages"},
}
if v, _ := s.Get("update_interval"); has(updateIntervals, v) {
u.Interval = v
}
if v, _ := s.Get("update_mode"); v == "immediate" {
u.Mode = "immediate"
}
if v, _ := s.Get("update_time"); clock.MatchString(v) {
u.Time = v
}
if v, ok := s.Values["update_targets"]; ok && (v.IsList || v.Str != "") {
in := v.List
if !v.IsList {
in = []string{v.Str}
}
u.Targets = []string{}
for _, x := range in {
if has(updateTargets, x) {
u.Targets = append(u.Targets, x)
}
}
}
return u
}
+288
View File
@@ -0,0 +1,288 @@
{
"settings": {
"portal_enabled": true,
"portal_port": 8443,
"portal_host": "vpn.example.com",
"portal_alt": [
"alt.example.com",
"203.0.113.7"
],
"portal_cert": "",
"portal_key": "",
"portal_redirect": "https://example.com/",
"default_device_limit": 5,
"geo_enabled": true,
"geo_provider": "ipwho.is",
"hostnames": false,
"domain": "home.arpa",
"log_connections": true,
"log_level": "debug",
"watchdog": false,
"home_dns_fallback": "",
"updates": {
"check": false,
"interval": "12h",
"auto": true,
"mode": "immediate",
"time": "04:00",
"targets": [
"app",
"amneziawg"
],
"keep": true,
"mirrors": true
},
"retention": {
"log_keep_days": "14",
"log_max": "50",
"log_category": [
"connections",
"problems"
],
"log_connections": null,
"log_persist": "10min",
"usage_keep_days": " 90 ",
"usage_keep_months": "many"
}
},
"servers": {
"home": {
"id": "home",
"name": "Home",
"ifname": "dawn0",
"port": 4500,
"subnet": "10.77.0.0/24",
"endpoint": "vpn.example.com",
"mtu": 0,
"dns": [
"10.77.0.1",
"1.1.1.1"
],
"keepalive": 0,
"private_key": "yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=",
"public_key": "xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=",
"preset": "quiet",
"lan_zone": "lan",
"wan_zone": "wan",
"auto_wan": false,
"wan_device": "pppoe-wan",
"auto_lan": true,
"lan_devices": [
"br-lan",
"br-guest"
],
"detected_wan": "",
"detected_lan": "",
"lan_like": false,
"mesh": "circles",
"portal_routers": "ask",
"portal_nets": "ask",
"enabled": true,
"obf": {
"jc": "5",
"jmin": "11",
"jmax": "42",
"s1": "12",
"h1": "1",
"i1": "<r 2><b 0x01000001000000000000>",
"header_protection_key": "yvVKA41To0000000000000000000IUdcl4ZiyFE=",
"rekey_after_time": "100-120",
"random_trailers": "on"
},
"device_mesh": true
},
"cabin": {
"id": "cabin",
"name": "cabin",
"ifname": "cabin",
"port": 51820,
"subnet": "",
"endpoint": "",
"mtu": 0,
"dns": [
"9.9.9.9",
"149.112.112.112"
],
"keepalive": 25,
"private_key": "",
"public_key": "",
"preset": "standard",
"lan_zone": "lan",
"wan_zone": "wan",
"auto_wan": true,
"wan_device": "",
"auto_lan": true,
"lan_devices": [
],
"detected_wan": "",
"detected_lan": "",
"lan_like": true,
"mesh": "off",
"portal_routers": "ask",
"portal_nets": "ask",
"enabled": false,
"obf": {
},
"device_mesh": false
}
},
"people": {
"anna": {
"id": "anna",
"server": "home",
"name": "Anna",
"access": "both",
"device_limit": 2,
"code": "abcdef-ghijkl-mnopqr",
"code_set": 1790000000,
"expires": "2026-12-31",
"quota_gb": 1.5,
"quota_period": "total",
"paused": false,
"dns_mode": "home",
"bonus_gb": 20,
"bonus_until": 1795000000,
"services": [
"nas"
],
"home_nets": [
"br-lan"
],
"circle": "family",
"note": "A note, with a comma",
"created": 1780000000,
"devices": [
"d_1",
"d_2"
]
},
"boris": {
"id": "boris",
"server": "cabin",
"name": "boris",
"access": "internet",
"device_limit": 5,
"code": "",
"code_set": 0,
"expires": "",
"quota_gb": 0,
"quota_period": "month",
"paused": true,
"dns_mode": "device",
"bonus_gb": 0,
"bonus_until": 1798761600,
"services": [
"nas",
"printer"
],
"home_nets": [
],
"circle": "",
"note": "",
"created": 0,
"devices": [
]
},
"nobody": {
"id": "nobody",
"server": "",
"name": "nobody",
"access": "internet",
"device_limit": 5,
"code": "",
"code_set": 0,
"expires": "",
"quota_gb": 0,
"quota_period": "month",
"paused": false,
"dns_mode": "device",
"bonus_gb": 0,
"bonus_until": 0,
"services": [
],
"home_nets": [
],
"circle": "",
"note": "",
"created": 0,
"devices": [
]
}
},
"devices": {
"d_1": {
"id": "d_1",
"person": "anna",
"name": "Phone",
"kind": "phone",
"address": "10.77.0.2",
"public_key": "u4pL0000000000000000000000000000DyRrogDM=",
"private_key": "",
"preshared_key": "Yc0000000000000000000000000000bRABGUovbrNy4=",
"created": 1780000100,
"created_by": "portal",
"disabled": false,
"mtu": 1280,
"keepalive": 0,
"lan_bypass": true
},
"d_2": {
"id": "d_2",
"person": "anna",
"name": "d_2",
"kind": "other",
"address": "",
"public_key": "",
"private_key": "",
"preshared_key": "",
"created": 0,
"created_by": "admin",
"disabled": true,
"mtu": 0,
"keepalive": null,
"lan_bypass": false
},
"d_3": {
"id": "d_3",
"person": "gone",
"name": "Orphan",
"kind": "router",
"address": "",
"public_key": "",
"private_key": "",
"preshared_key": "",
"created": 0,
"created_by": "admin",
"disabled": false,
"mtu": 0,
"keepalive": 60,
"lan_bypass": false
}
},
"services": {
"nas": {
"id": "nas",
"name": "NAS",
"address": "192.168.1.10",
"ports": [
"445",
"8080-8090"
]
},
"printer": {
"id": "printer",
"name": "printer",
"address": "192.168.1.20",
"ports": [
]
}
},
"circles": {
"family": {
"id": "family",
"server": "home",
"name": "Family",
"color": 3
}
}
}
+139
View File
@@ -0,0 +1,139 @@
# A fuller installation, with what older versions wrote and what a hand has broken: the Go model
# (backend/model) must read it exactly as the ucode one does (scripts/ucode-golden.sh writes rich.json).
config settings 'settings'
option portal_enabled 'yes'
option portal_port '99999'
option portal_host 'vpn.example.com'
list portal_alt 'alt.example.com'
list portal_alt ''
list portal_alt '203.0.113.7'
option portal_redirect 'https://example.com/'
option default_device_limit '5'
option hostnames 'off'
option domain 'home.arpa'
option geo_enabled 'TRUE'
option geo_provider 'nowhere'
option log_level 'debug'
option watchdog '0'
option log_keep_days '14'
option log_max '50'
option log_persist '10min'
list log_category 'connections'
list log_category 'problems'
option usage_keep_days ' 90 '
option usage_keep_months 'many'
option home_dns_fallback 'none'
option update_check '0'
option update_interval '12h'
option update_auto 'on'
option update_mode 'immediate'
option update_time '25:00'
list update_targets 'app'
list update_targets 'firmware'
list update_targets 'amneziawg'
option update_keep '1'
config server 'home'
option name 'Home'
option ifname 'dawn0'
option port '4500'
option subnet '10.77.0.0/24'
option endpoint 'vpn.example.com'
option private_key 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk='
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
option mtu 'auto'
list dns '10.77.0.1'
list dns '1.1.1.1'
option keepalive '0'
option preset 'quiet'
option auto_wan '0'
option wan_device 'pppoe-wan'
list lan_device 'br-lan'
list lan_device 'br-guest'
option lan_like '0'
option mesh 'circles'
option jc '5'
option jmin '11'
option jmax '42'
option s1 '12'
option h1 '1'
option i1 '<r 2><b 0x01000001000000000000>'
option header_protection_key 'yvVKA41To0000000000000000000IUdcl4ZiyFE='
option rekey_after_time '100-120'
option random_trailers 'on'
config server 'cabin'
option port 'x'
option dns '9.9.9.9, 149.112.112.112'
option device_mesh '0'
option enabled '0'
option mesh 'everyone'
config person 'anna'
option server 'home'
option name 'Anna'
option access 'both'
option device_limit '2'
option code 'abcdef-ghijkl-mnopqr'
option code_set '1790000000'
option expires '2026-12-31'
option quota_gb '1.5'
option quota_period 'total'
option dns_mode 'home'
option bonus_gb '20'
option bonus_until '1795000000'
list service 'nas'
list home_net 'br-lan'
option circle 'family'
option note 'A note, with a comma'
option created '1780000000'
config person 'boris'
option server 'cabin'
option access 'everything'
option paused '1'
option quota_gb 'lots'
option bonus_month '2026-12'
option service 'nas printer'
config person 'nobody'
config device 'd_1'
option person 'anna'
option name 'Phone'
option kind 'phone'
option address '10.77.0.2'
option public_key 'u4pL0000000000000000000000000000DyRrogDM='
option preshared_key 'Yc0000000000000000000000000000bRABGUovbrNy4='
option created '1780000100'
option created_by 'portal'
option mtu '1280'
option keepalive '0'
option lan_bypass '1'
config device 'd_2'
option person 'anna'
option kind 'toaster'
option disabled 'yes'
option keepalive 'often'
config device 'd_3'
option person 'gone'
option name 'Orphan'
option kind 'router'
option keepalive '60'
config circle 'family'
option server 'home'
option name 'Family'
option color '11'
config service 'nas'
option name 'NAS'
option address '192.168.1.10'
list port '445'
list port '8080-8090'
config service 'printer'
option address '192.168.1.20'
+155
View File
@@ -0,0 +1,155 @@
{
"settings": {
"portal_enabled": true,
"portal_port": 8443,
"portal_host": "vpn.example.com",
"portal_alt": [
],
"portal_cert": "",
"portal_key": "",
"portal_redirect": "",
"default_device_limit": 3,
"geo_enabled": false,
"geo_provider": "ipwho.is",
"hostnames": true,
"domain": "lan",
"log_connections": false,
"log_level": "info",
"watchdog": true,
"home_dns_fallback": "1.1.1.1",
"updates": {
"check": true,
"interval": "7d",
"auto": true,
"mode": "scheduled",
"time": "04:00",
"targets": [
"app"
],
"keep": false,
"mirrors": true
},
"retention": {
"log_keep_days": null,
"log_max": null,
"log_category": null,
"log_connections": "0",
"log_persist": null,
"usage_keep_days": null,
"usage_keep_months": null
}
},
"servers": {
"main": {
"id": "main",
"name": "Main",
"ifname": "awgmain",
"port": 51820,
"subnet": "10.9.0.0/29",
"endpoint": "",
"mtu": 1380,
"dns": [
],
"keepalive": 25,
"private_key": "yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=",
"public_key": "xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=",
"preset": "standard",
"lan_zone": "lan",
"wan_zone": "wan",
"auto_wan": true,
"wan_device": "",
"auto_lan": true,
"lan_devices": [
],
"detected_wan": "",
"detected_lan": "",
"lan_like": true,
"mesh": "all",
"portal_routers": "ask",
"portal_nets": "ask",
"enabled": true,
"obf": {
"jc": "4",
"jmin": "64",
"jmax": "128",
"s4": "12"
},
"device_mesh": true
}
},
"people": {
"alice": {
"id": "alice",
"server": "main",
"name": "Alice",
"access": "both",
"device_limit": 3,
"code": "abcdef-ghijkl-mnopqr",
"code_set": 0,
"expires": "",
"quota_gb": 0,
"quota_period": "month",
"paused": false,
"dns_mode": "device",
"bonus_gb": 0,
"bonus_until": 0,
"services": [
],
"home_nets": [
],
"circle": "",
"note": "",
"created": 0,
"devices": [
"alice_phone"
]
},
"bob": {
"id": "bob",
"server": "main",
"name": "Bob",
"access": "internet",
"device_limit": 3,
"code": "XyZ12345",
"code_set": 0,
"expires": "",
"quota_gb": 2,
"quota_period": "month",
"paused": false,
"dns_mode": "device",
"bonus_gb": 0,
"bonus_until": 0,
"services": [
],
"home_nets": [
],
"circle": "",
"note": "",
"created": 0,
"devices": [
]
}
},
"devices": {
"alice_phone": {
"id": "alice_phone",
"person": "alice",
"name": "Phone",
"kind": "phone",
"address": "10.9.0.2",
"public_key": "AuTb2wZ8C1032Ksn76nFgXzOJgT86OgEVbEE7ClpNy8=",
"private_key": "",
"preshared_key": "",
"created": 0,
"created_by": "admin",
"disabled": false,
"mtu": 0,
"keepalive": null,
"lan_bypass": false
}
},
"services": {
},
"circles": {
}
}
+44
View File
@@ -0,0 +1,44 @@
# Test fixture: a small installation (one server, two people, one device).
# migrate.test.uc expects bob's random code, the server's stored MTU 1380,
# the old portal title and uhttpd's error_page: the one-time steps remove them.
config settings 'settings'
option portal_enabled '1'
option portal_port '8443'
option portal_host 'vpn.example.com'
option portal_title 'My VPN'
option log_connections '0'
option update_interval '7d'
list update_targets 'app'
config server 'main'
option name 'Main'
option ifname 'awgmain'
option port '51820'
option subnet '10.9.0.0/29'
option private_key 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk='
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
option mtu '1380'
option jc '4'
option jmin '64'
option jmax '128'
option s4 '12'
config person 'alice'
option server 'main'
option name 'Alice'
option code 'abcdef-ghijkl-mnopqr'
option access 'both'
config person 'bob'
option server 'main'
option name 'Bob'
option code 'XyZ12345'
option quota_gb '2'
config device 'alice_phone'
option person 'alice'
option name 'Phone'
option kind 'phone'
option address '10.9.0.2'
option public_key 'AuTb2wZ8C1032Ksn76nFgXzOJgT86OgEVbEE7ClpNy8='
+174
View File
@@ -0,0 +1,174 @@
// What follows from the settings about time and tunnels: a device's keep-alive, how long it may go
// between two handshakes, how long after one it still counts as online, and which tunnel a server has.
// As dawnline.core, dawnline.awg and dawnline.live work them out (tests/ucode/awg.test.uc has the cases
// these are held to). Pure: the settings in, numbers out.
package model
import (
"net/netip"
"regexp"
"strconv"
"strings"
)
const (
// OnlineWindow is how long after its handshake a device counts as online, at the least: a WireGuard
// session is dropped 180 s after its handshake and a device that is there renews it every 2 minutes
// (a little slack for a renewal that needs a retry).
OnlineWindow = 190
// SleepWindow is the same for a phone or a tablet: asleep, its system holds the tunnel's timers and its
// session lapses for minutes and comes back by itself. That silence is sleep, not leaving.
SleepWindow = 600
// A device's own keep-alive is taken within this range (seconds; 0 is off).
keepaliveMax = 600
)
// DeviceKeepalive is the keep-alive a device's configuration carries, in seconds (0: off): its own when the
// admin set one, else the server's.
func DeviceKeepalive(srv *Server, dev *Device) int {
if dev != nil && dev.Keepalive != nil && *dev.Keepalive >= 0 && *dev.Keepalive <= keepaliveMax {
return *dev.Keepalive
}
return srv.Keepalive
}
// KeepaliveRange is that keep-alive as the device sends it, lo to hi seconds; ok is false when it is off.
// With header protection (AmneziaWG 3.1, whose apps take ranges) it is jittered over ten seconds, since a
// fixed beat would be the one regular thing left.
func KeepaliveRange(srv *Server, dev *Device) (lo, hi int, ok bool) {
k := DeviceKeepalive(srv, dev)
if k <= 0 {
return 0, 0, false
}
if srv.Obf["header_protection_key"] != "" {
return k, k + 10, true
}
return k, k, true
}
// IdleHandshake is the longest an idle device goes between two handshakes, in seconds; ok is false when
// its keep-alive is off (an idle device then sends nothing at all). Its keep-alives are what it sends, and
// the first one after its key's rekey time (WireGuard's 120 s; past 180 s the key is refused anyway)
// starts a handshake: up to one keep-alive past that time, or each keep-alive once they are further apart.
func IdleHandshake(srv *Server, dev *Device) (int, bool) {
lo, hi, ok := KeepaliveRange(srv, dev)
if !ok {
return 0, false
}
rekey := 120
if _, top, given := uintRange(srv.Obf["rekey_after_time"], 65535); given && top != 0 {
rekey = top
}
rekey = min(rekey, 180)
if lo > rekey {
return hi, true
}
return rekey + hi, true
}
// OnlineWindowOf is how long after its last handshake a device still counts as online, in seconds:
// OnlineWindow, or 30 s more than an idle device goes between handshakes when that is longer (it renews
// its session only with its keep-alive, and a fixed window would see it leave and come back between two).
// A phone or a tablet never less than SleepWindow.
func OnlineWindowOf(srv *Server, dev *Device) int {
w := OnlineWindow
if srv != nil {
if h, ok := IdleHandshake(srv, dev); ok {
w = max(w, h+30)
}
}
if dev != nil && has(MobileKinds, dev.Kind) {
w = max(w, SleepWindow)
}
return w
}
// uintOf is a whole number as AmneziaWG writes one, up to top.
func uintOf(s string, top int) (int, bool) {
if s == "" || len(s) > 10 {
return 0, false
}
for i := 0; i < len(s); i++ {
if s[i] < '0' || s[i] > '9' {
return 0, false
}
}
n, err := strconv.Atoi(s)
return n, err == nil && n <= top
}
// uintRange is a number or a range as AmneziaWG writes them ("5", "5-15"), each end up to top.
func uintRange(v string, top int) (lo, hi int, ok bool) {
p := strings.Split(strings.TrimSpace(v), "-")
if len(p) > 2 {
return 0, 0, false
}
lo, ok = uintOf(p[0], top)
if !ok {
return 0, 0, false
}
hi = lo
if len(p) == 2 {
if hi, ok = uintOf(p[1], top); !ok {
return 0, 0, false
}
}
return lo, hi, lo <= hi
}
// Tunnel is a server's link.
type Tunnel struct {
Ifname string
Subnet string
// Address is the router's own in the tunnel: the subnet's first.
Address string
}
var ifname = regexp.MustCompile(`^[a-z][a-z0-9_]{0,11}$`)
// ValidIfname tells a server's interface name: also a netifd section and an nftables string, so nothing else.
func ValidIfname(s string) bool { return ifname.MatchString(s) }
// TunnelOf is the server's tunnel: it has one when it has its keys, is not kept down, and its interface's
// name and subnet are usable.
func TunnelOf(srv *Server) (Tunnel, bool) {
if srv == nil || srv.PrivateKey == "" || srv.Blocked != nil || !ValidIfname(srv.Ifname) {
return Tunnel{}, false
}
p, ok := parseCIDR(srv.Subnet)
if !ok {
return Tunnel{}, false
}
return Tunnel{Ifname: srv.Ifname, Subnet: srv.Subnet, Address: p.Masked().Addr().Next().String()}, true
}
// TunnelIfnames is the interfaces of the servers that run: turned on, with a tunnel that is Dawnline's.
// What the tunnels' reader is asked for.
func (m *Model) TunnelIfnames() []string {
out := []string{}
for _, id := range m.serverIDs {
srv := m.Servers[id]
if !srv.Enabled {
continue
}
if t, ok := TunnelOf(srv); ok {
out = append(out, t.Ifname)
}
}
return out
}
var cidr = regexp.MustCompile(`^[0-9.]+/[0-9]+$`)
// parseCIDR reads "a.b.c.d/len" with a prefix a tunnel can have (8 to 30).
func parseCIDR(s string) (netip.Prefix, bool) {
if !cidr.MatchString(s) {
return netip.Prefix{}, false
}
p, err := netip.ParsePrefix(s)
if err != nil || !p.Addr().Is4() || p.Bits() < 8 || p.Bits() > 30 {
return netip.Prefix{}, false
}
return p, true
}
+90
View File
@@ -0,0 +1,90 @@
package model
import "testing"
func ka(n int) *Device { return &Device{Keepalive: &n} }
// The cases of tests/ucode/awg.test.uc («keepalive_range and idle_handshake») and live.test.uc's windows.
func TestKeepaliveAndIdleHandshake(t *testing.T) {
srv := &Server{Keepalive: 25, Obf: map[string]string{}}
jittered := &Server{Keepalive: 25, Obf: map[string]string{"header_protection_key": "k", "rekey_after_time": "100-120"}}
rng := func(s *Server, d *Device) [3]int {
lo, hi, ok := KeepaliveRange(s, d)
if !ok {
return [3]int{-1, -1, 0}
}
return [3]int{lo, hi, 1}
}
for name, c := range map[string]struct {
got, want [3]int
}{
"the server's, no range": {rng(srv, &Device{}), [3]int{25, 25, 1}},
"the device's own": {rng(srv, ka(120)), [3]int{120, 120, 1}},
"off for the device": {rng(srv, ka(0)), [3]int{-1, -1, 0}},
"off on the server": {rng(&Server{Obf: map[string]string{}}, &Device{}), [3]int{-1, -1, 0}},
"jittered with 3.1": {rng(jittered, &Device{}), [3]int{25, 35, 1}},
"the device's own, jittered": {rng(jittered, ka(60)), [3]int{60, 70, 1}},
"out of range: the server's own": {rng(srv, ka(9999)), [3]int{25, 25, 1}},
} {
if c.got != c.want {
t.Errorf("%s: %v, want %v", name, c.got, c.want)
}
}
idle := func(s *Server, d *Device) int {
h, ok := IdleHandshake(s, d)
if !ok {
return -1
}
return h
}
for name, c := range map[string][2]int{
"within the rekey time: up to one keep-alive past it": {idle(srv, &Device{}), 145},
"Maximum: RekeyAfterTime 100-120, keep-alive up to 35": {idle(jittered, &Device{}), 155},
"every second keep-alive": {idle(srv, ka(100)), 220},
"every keep-alive once they are further apart": {idle(srv, ka(300)), 300},
"past 180 s the key is refused anyway": {idle(&Server{Keepalive: 25, Obf: map[string]string{"rekey_after_time": "200-400"}}, &Device{}), 205},
"keep-alive off": {idle(srv, ka(0)), -1},
} {
if c[0] != c[1] {
t.Errorf("%s: %d, want %d", name, c[0], c[1])
}
}
}
func TestOnlineWindow(t *testing.T) {
srv := &Server{Keepalive: 25, Obf: map[string]string{}}
for name, c := range map[string][2]int{
"a computer with the usual keep-alive": {OnlineWindowOf(srv, &Device{Kind: "computer"}), 190},
"a long keep-alive: 30 s past its next handshake": {OnlineWindowOf(srv, &Device{Kind: "computer", Keepalive: ka(300).Keepalive}), 330},
"a phone sleeps": {OnlineWindowOf(srv, &Device{Kind: "phone"}), 600},
"a tablet too": {OnlineWindowOf(srv, &Device{Kind: "tablet"}), 600},
"no server": {OnlineWindowOf(nil, &Device{Kind: "router"}), 190},
} {
if c[0] != c[1] {
t.Errorf("%s: %d, want %d", name, c[0], c[1])
}
}
}
func TestTunnels(t *testing.T) {
good := &Server{ID: "home", Ifname: "dawn0", Subnet: "10.77.0.0/24", PrivateKey: "k", Enabled: true}
if tn, ok := TunnelOf(good); !ok || tn.Address != "10.77.0.1" || tn.Ifname != "dawn0" {
t.Fatalf("tunnel: %+v %v", tn, ok)
}
for name, s := range map[string]*Server{
"no keys": {Ifname: "dawn0", Subnet: "10.77.0.0/24"},
"kept down": {Ifname: "dawn0", Subnet: "10.77.0.0/24", PrivateKey: "k", Blocked: "taken"},
"a bad name": {Ifname: "Dawn-0", Subnet: "10.77.0.0/24", PrivateKey: "k"},
"no subnet": {Ifname: "dawn0", PrivateKey: "k"},
"a host, not a net": {Ifname: "dawn0", Subnet: "10.77.0.1", PrivateKey: "k"},
"too small a subnet": {Ifname: "dawn0", Subnet: "10.77.0.0/31", PrivateKey: "k"},
} {
if _, ok := TunnelOf(s); ok {
t.Errorf("%s: has a tunnel", name)
}
}
m := &Model{Servers: map[string]*Server{"home": good, "off": {Ifname: "dawn1", Subnet: "10.78.0.0/24", PrivateKey: "k"}}, serverIDs: []string{"off", "home"}}
if got := m.TunnelIfnames(); len(got) != 1 || got[0] != "dawn0" {
t.Fatalf("ifnames: %v", got)
}
}