From dc5986054186a6f8ff0b97d1efb511d031d9251e Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 21:12:25 +0100 Subject: [PATCH] M2 networkmanager: the watcher hears the rating MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit uplink-tools watch hears the network manager's PropertiesChanged on the system bus, keeps sign-in-asked and sign-in-ended as the rules say, at most 256 of them, and subscribes again when the system bus's socket comes back or on rating-again; nothing reads the rating on a timer. Builds: design 08 sign-in-page §12, §14, §20, §21, §22 --- .../networkmanager/cmd/uplink-tools/dbus.go | 220 ++++++++++ .../cmd/uplink-tools/manager.go | 7 +- .../cmd/uplink-tools/manager_test.go | 7 + .../networkmanager/cmd/uplink-tools/watch.go | 398 ++++++++++++++++++ .../cmd/uplink-tools/watch_test.go | 311 ++++++++++++++ modules/networkmanager/go.mod | 7 +- modules/networkmanager/go.sum | 14 +- 7 files changed, 954 insertions(+), 10 deletions(-) create mode 100644 modules/networkmanager/cmd/uplink-tools/dbus.go create mode 100644 modules/networkmanager/cmd/uplink-tools/watch.go create mode 100644 modules/networkmanager/cmd/uplink-tools/watch_test.go diff --git a/modules/networkmanager/cmd/uplink-tools/dbus.go b/modules/networkmanager/cmd/uplink-tools/dbus.go new file mode 100644 index 000000000..fa5a95638 --- /dev/null +++ b/modules/networkmanager/cmd/uplink-tools/dbus.go @@ -0,0 +1,220 @@ +package main + +// The watcher's system bus, through godbus: the network manager's properties and its PropertiesChanged, logind's +// SessionNew, and the system bus's socket coming back, heard as a file event of the kernel on its folder. + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "unsafe" + + "github.com/godbus/dbus/v5" + "golang.org/x/sys/unix" +) + +const ( + nmName = "org.freedesktop.NetworkManager" + nmPath = dbus.ObjectPath("/org/freedesktop/NetworkManager") + nmActive = "org.freedesktop.NetworkManager.Connection.Active" + nmDevice = "org.freedesktop.NetworkManager.Device" + propsIface = "org.freedesktop.DBus.Properties" + login1Name = "org.freedesktop.login1" + login1Path = dbus.ObjectPath("/org/freedesktop/login1") + login1Iface = "org.freedesktop.login1.Manager" +) + +// systemSocket is the system bus's socket, whose folder the watcher watches when its connection dropped. +var systemSocket = "/run/dbus/system_bus_socket" + +// ratingProperties are the network manager's properties whose change the watcher acts on (§14). +var ratingProperties = map[string]bool{"Connectivity": true, "PrimaryConnection": true, + "ConnectivityCheckEnabled": true, "ConnectivityCheckAvailable": true, "ConnectivityCheckUri": true} + +type dbusSystem struct { + conn *dbus.Conn +} + +func dialSystemBus() (systemBus, error) { + conn, err := dbus.ConnectSystemBus() + if err != nil { + return nil, err + } + return &dbusSystem{conn: conn}, nil +} + +func (d *dbusSystem) close() { d.conn.Close() } + +func (d *dbusSystem) listen() (<-chan signal, error) { + if err := d.conn.AddMatchSignal(dbus.WithMatchObjectPath(nmPath), dbus.WithMatchInterface(propsIface), + dbus.WithMatchMember("PropertiesChanged")); err != nil { + return nil, fmt.Errorf("hearing the network manager: %w", err) + } + if err := d.conn.AddMatchSignal(dbus.WithMatchObjectPath(login1Path), dbus.WithMatchInterface(login1Iface), + dbus.WithMatchMember("SessionNew")); err != nil { + return nil, fmt.Errorf("hearing logind: %w", err) + } + in := make(chan *dbus.Signal, 64) + d.conn.Signal(in) + out := make(chan signal) + go func() { + // godbus closes in when the connection drops. + for s := range in { + if heard, ok := readSignal(s); ok { + out <- heard + } + } + close(out) + }() + return out, nil +} + +// readSignal is what the watcher hears in a signal of the system bus: the network manager's PropertiesChanged naming +// a property of the rating, or logind's SessionNew with the new session's object. +func readSignal(s *dbus.Signal) (signal, bool) { + switch { + case s.Path == nmPath && s.Name == propsIface+".PropertiesChanged" && len(s.Body) >= 3: + if iface, _ := s.Body[0].(string); iface != nmName { + return signal{}, false + } + changed, _ := s.Body[1].(map[string]dbus.Variant) + for name := range changed { + if ratingProperties[name] { + return signal{Rating: true}, true + } + } + invalidated, _ := s.Body[2].([]string) + for _, name := range invalidated { + if ratingProperties[name] { + return signal{Rating: true}, true + } + } + case s.Path == login1Path && s.Name == login1Iface+".SessionNew" && len(s.Body) >= 2: + if path, ok := s.Body[1].(dbus.ObjectPath); ok { + return signal{Session: string(path)}, true + } + } + return signal{}, false +} + +func (d *dbusSystem) rating() (Rating, error) { + nm := d.conn.Object(nmName, nmPath) + var r Rating + for name, into := range map[string]any{"Connectivity": &r.Connectivity, "ConnectivityCheckEnabled": &r.CheckEnabled, + "ConnectivityCheckAvailable": &r.CheckAvailable, "ConnectivityCheckUri": &r.CheckURI} { + v, err := nm.GetProperty(nmName + "." + name) + if err != nil { + return Rating{}, fmt.Errorf("the network manager's %s: %w", name, err) + } + if err := v.Store(into); err != nil { + return Rating{}, fmt.Errorf("the network manager's %s: %w", name, err) + } + } + v, err := nm.GetProperty(nmName + ".PrimaryConnection") + if err != nil { + return Rating{}, fmt.Errorf("the network manager's PrimaryConnection: %w", err) + } + path, _ := v.Value().(dbus.ObjectPath) + r.Connection = string(path) + if !r.active() { + return r, nil + } + // A connection that went between the two reads is read as it is said: its name and link empty. + active := d.conn.Object(nmName, path) + if v, err := active.GetProperty(nmActive + ".Id"); err == nil { + r.Network, _ = v.Value().(string) + } + if v, err := active.GetProperty(nmActive + ".Devices"); err == nil { + if devices, _ := v.Value().([]dbus.ObjectPath); len(devices) > 0 { + if v, err := d.conn.Object(nmName, devices[0]).GetProperty(nmDevice + ".Interface"); err == nil { + r.Link, _ = v.Value().(string) + } + } + } + return r, nil +} + +// systemSocketThere fires once the system bus's socket is there: at once when it is, else when it is made in its +// folder (a file event of the kernel). Closing stop ends the wait. +func systemSocketThere(stop <-chan struct{}) <-chan struct{} { + return fileThere(systemSocket, stop) +} + +// fileThere fires once path is there: at once when it is, else at the file event that makes it in its folder. +func fileThere(path string, stop <-chan struct{}) <-chan struct{} { + out := make(chan struct{}) + fd, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK) + if err != nil { + journal("watching %s failed: %v", filepath.Dir(path), err) + return out + } + if _, err := unix.InotifyAddWatch(fd, filepath.Dir(path), unix.IN_CREATE|unix.IN_MOVED_TO); err != nil { + journal("watching %s failed: %v", filepath.Dir(path), err) + unix.Close(fd) + return out + } + f := os.NewFile(uintptr(fd), "inotify") + go func() { + <-stop + f.Close() + }() + go func() { + defer f.Close() + if _, err := os.Stat(path); err == nil { + sendOnce(out, stop) + return + } + for { + names, err := readInotify(f) + if err != nil { + return + } + for _, name := range names { + if name == filepath.Base(path) { + sendOnce(out, stop) + return + } + } + } + }() + return out +} + +func sendOnce(out chan<- struct{}, stop <-chan struct{}) { + select { + case out <- struct{}{}: + case <-stop: + } +} + +// readInotify reads the names of one read's file events; an error once the descriptor is closed. +func readInotify(f *os.File) ([]string, error) { + buf := make([]byte, 64*(unix.SizeofInotifyEvent+unix.NAME_MAX+1)) + n, err := f.Read(buf) + if err != nil { + if !errors.Is(err, os.ErrClosed) { + journal("a watch of file events failed: %v", err) + } + return nil, err + } + var names []string + for off := 0; off+unix.SizeofInotifyEvent <= n; { + ev := (*unix.InotifyEvent)(unsafe.Pointer(&buf[off])) + nameAt := off + unix.SizeofInotifyEvent + end := nameAt + int(ev.Len) + if end > n { + break + } + name := buf[nameAt:end] + for i, b := range name { + if b == 0 { + name = name[:i] + break + } + } + names = append(names, string(name)) + off = end + } + return names, nil +} diff --git a/modules/networkmanager/cmd/uplink-tools/manager.go b/modules/networkmanager/cmd/uplink-tools/manager.go index 2c1d23787..6d544cca2 100644 --- a/modules/networkmanager/cmd/uplink-tools/manager.go +++ b/modules/networkmanager/cmd/uplink-tools/manager.go @@ -51,5 +51,8 @@ func parseNmcli(out string) map[string]LinkDNS { return links } -// holder is what networkmanager adds to the seat's verbs (design 08 sign-in-page §11). -func holder(m Machine) holderOwn { return holderOwn{} } +// holder is what networkmanager adds to the seat's verbs (design 08 sign-in-page §11): the watcher, `uplink-tools +// watch`. +func holder(m Machine) holderOwn { + return holderOwn{Commands: map[string]func([]string) error{"watch": watch}} +} diff --git a/modules/networkmanager/cmd/uplink-tools/manager_test.go b/modules/networkmanager/cmd/uplink-tools/manager_test.go index 2782c34ae..66000ae2c 100644 --- a/modules/networkmanager/cmd/uplink-tools/manager_test.go +++ b/modules/networkmanager/cmd/uplink-tools/manager_test.go @@ -16,3 +16,10 @@ func TestNmcliIsReadPerDevice(t *testing.T) { t.Fatal("a link with no names was said") } } + +// networkmanager's own part: the watcher's subcommand (design 08 sign-in-page §11). +func TestNetworkManagerRunsItsWatcherAsASubcommand(t *testing.T) { + if run, err := command(holder(Machine{}), []string{"watch"}); err != nil || run == nil { + t.Fatalf("uplink-tools watch is not the watcher: %v", err) + } +} diff --git a/modules/networkmanager/cmd/uplink-tools/watch.go b/modules/networkmanager/cmd/uplink-tools/watch.go new file mode 100644 index 000000000..fac1f1345 --- /dev/null +++ b/modules/networkmanager/cmd/uplink-tools/watch.go @@ -0,0 +1,398 @@ +package main + +// The watcher (design 08 sign-in-page §11, §14, §20 to §22): `uplink-tools watch`, a process the machine's service +// manager starts at boot as the account and keeps running, needing no bus. It hears the network manager's +// PropertiesChanged on the system bus for the rating, the active connection and the check, keeps the events of §21 in +// the module's folder for the bundle to publish, and answers its socket. Nothing runs on a timer: it acts on a signal, +// on the system bus's socket coming back (a file event of the kernel) and on an ask on its socket. + +import ( + "errors" + "fmt" + "net/url" + "os" + "time" +) + +// keptBound is the most kept events pending/ holds; past it the oldest goes, with a journal line (§20). +const keptBound = 256 + +// The network manager's ratings of the network (NMConnectivityState). +const ( + ratingUnknown uint32 = 0 + ratingNone uint32 = 1 + ratingPortal uint32 = 2 + ratingLimited uint32 = 3 + ratingFull uint32 = 4 +) + +func ratingName(r uint32) string { + switch r { + case ratingNone: + return "NONE" + case ratingPortal: + return "PORTAL" + case ratingLimited: + return "LIMITED" + case ratingFull: + return "FULL" + } + return "UNKNOWN" +} + +// Rating is what the watcher reads of the network manager: its rating, whether its check is on and where it goes, and +// the active connection (its object, its name and its first device's interface; "" or "/" when none is active). +type Rating struct { + Connectivity uint32 + CheckEnabled bool + CheckAvailable bool + CheckURI string + Connection string + Network string + Link string +} + +func (r Rating) checkOn() bool { return r.CheckEnabled && r.CheckAvailable } +func (r Rating) active() bool { return r.Connection != "" && r.Connection != "/" } + +// The events of node-uplink the watcher keeps, and why an ask ended. +const ( + eventAsked = "sign-in-asked" + eventEnded = "sign-in-ended" + + whySignedIn = "signed-in" + whyLeft = "left" + whyNoLongerAsked = "no-longer-asked" +) + +// eventSubject is where a node-uplink event of node is published (§1). +func eventSubject(event, node string) string { + return "mesh.seat.node-uplink.event." + event + "." + node +} + +type signInAsked struct { + Node string `json:"node"` + Link string `json:"link"` + Network string `json:"network"` + Address string `json:"address"` + At string `json:"at"` +} + +type signInEnded struct { + Node string `json:"node"` + Link string `json:"link"` + Network string `json:"network"` + At string `json:"at"` + Why string `json:"why"` +} + +// signal is one thing the system bus said that the watcher hears: the network manager's rating changed, or logind +// has a new session (its object path). +type signal struct { + Rating bool + Session string +} + +// systemBus is the watcher's connection to the machine's system bus: subscribed, it hands every signal it hears on the +// channel, which closes when the connection drops. +type systemBus interface { + listen() (<-chan signal, error) + rating() (Rating, error) + close() +} + +// openAsk is the sign-in asked now: the connection, its network and link, and since when. +type openAsk struct { + Network string `json:"network"` + Link string `json:"link"` + Since time.Time `json:"since"` + connection string + address string +} + +// watcherState is the watcher's answer to `state` (§23's read). +type watcherState struct { + Subscribed bool `json:"subscribed"` + Rating string `json:"rating,omitempty"` + RatingAt *time.Time `json:"rating_at,omitempty"` + Ask *openAsk `json:"ask,omitempty"` + AsksOpened int `json:"asks_opened"` + AsksEnded int `json:"asks_ended"` + DroppedPastBound int `json:"dropped_past_bound"` +} + +// asked is an ask on the watcher's socket, handed to its loop, and the answer it sends back. +type asked struct { + ask string + reply chan askReply +} + +type askReply struct { + answer any + err error +} + +// Watcher is the watch: what it reads through, and the state its loop alone holds. +type Watcher struct { + Folder Folder + // Dial connects to the system bus. + Dial func() (systemBus, error) + // SocketThere fires once the system bus's socket is there: at once when it is, else at the file event of its + // folder; closing stop ends the wait. + SocketThere func(stop <-chan struct{}) <-chan struct{} + Now func() time.Time + + asks chan asked + bus systemBus + signals <-chan signal + socketAt <-chan struct{} + stopWait chan struct{} + started bool + state watcherState + rating *Rating + ask *openAsk +} + +func newWatcher(f Folder) *Watcher { + return &Watcher{Folder: f, Dial: dialSystemBus, SocketThere: systemSocketThere, Now: time.Now, asks: make(chan asked)} +} + +// watch is `uplink-tools watch`: the watcher, until its process is stopped. +func watch([]string) error { + f, err := theFolder() + if err != nil { + return err + } + if f.Node == "" { + return errors.New("no node named: the node-engine names it in MESH_NODE") + } + if err := os.MkdirAll(f.Dir, 0o700); err != nil { + return err + } + l, err := f.listen() + if err != nil { + return fmt.Errorf("the watcher's socket: %w", err) + } + w := newWatcher(f) + go serveSocket(l, w.askLoop) + w.run(nil) + return nil +} + +// askLoop hands one ask of the socket to the loop and waits for its answer. +func (w *Watcher) askLoop(ask string) (any, error) { + reply := make(chan askReply, 1) + w.asks <- asked{ask: ask, reply: reply} + r := <-reply + return r.answer, r.err +} + +// run is the watcher's loop, until stop closes: it subscribes, then acts on what it hears, one thing at a time. +func (w *Watcher) run(stop <-chan struct{}) { + if w.asks == nil { + w.asks = make(chan asked) + } + w.subscribe() + for { + select { + case <-stop: + w.unsubscribe() + return + case s, ok := <-w.signals: + if !ok { + journal("the system bus connection dropped; subscribing again when its socket is there") + w.unsubscribe() + w.waitSocket() + continue + } + w.heardSignal(s) + case <-w.socketAt: + w.socketAt = nil + w.subscribe() + case a := <-w.asks: + answer, err := w.answer(a.ask) + a.reply <- askReply{answer, err} + } + } +} + +// subscribe connects to the system bus, listens, reads the rating and acts on it: at the watcher's start as its start, +// after that as on a change (§14). One that fails waits for the system bus's socket. +func (w *Watcher) subscribe() { + w.unsubscribe() + bus, err := w.Dial() + if err == nil { + var signals <-chan signal + if signals, err = bus.listen(); err == nil { + w.bus, w.signals, w.state.Subscribed = bus, signals, true + } else { + bus.close() + } + } + if err != nil { + journal("subscribing on the system bus failed: %v; subscribing again when its socket is there", err) + w.waitSocket() + return + } + journal("subscribed on the system bus") + w.readRating() +} + +func (w *Watcher) unsubscribe() { + if w.stopWait != nil { + close(w.stopWait) + w.stopWait, w.socketAt = nil, nil + } + if w.bus != nil { + w.bus.close() + } + w.bus, w.signals, w.state.Subscribed = nil, nil, false +} + +func (w *Watcher) waitSocket() { + w.stopWait = make(chan struct{}) + w.socketAt = w.SocketThere(w.stopWait) +} + +func (w *Watcher) heardSignal(s signal) { + if s.Rating { + w.readRating() + } +} + +// readRating reads the rating now and acts on it: as the watcher's start the first time, as a change after. +func (w *Watcher) readRating() { + if w.bus == nil { + return + } + r, err := w.bus.rating() + if err != nil { + journal("reading the network manager's rating failed: %v", err) + return + } + atStart := !w.started + w.started = true + w.heard(r, atStart) +} + +// heard acts on a rating read: the check address, a journal line for a change, and the events of §21. +func (w *Watcher) heard(r Rating, atStart bool) { + old := w.rating + now := w.Now() + w.rating, w.state.RatingAt = &r, &now + w.state.Rating = ratingName(r.Connectivity) + if atStart || old == nil || old.Connectivity != r.Connectivity || old.Connection != r.Connection { + from := "none" + if old != nil { + from = ratingName(old.Connectivity) + } + journal("rating %s -> %s on %q", from, ratingName(r.Connectivity), r.Network) + } + if atStart || old == nil || old.CheckURI != r.CheckURI { + if err := w.Folder.writeCheckAddress(r.CheckURI); err != nil { + journal("writing the check address failed: %v", err) + } + } + if r.checkOn() && !webAddress(r.CheckURI) { + journal("the check address %q is not http or https: nothing kept, nothing opened", r.CheckURI) + return + } + if atStart { + if !r.checkOn() { + return + } + if r.Connectivity == ratingPortal && r.active() { + w.asked(r) + return + } + w.ended(r.Link, r.Network, whyNoLongerAsked) + return + } + if w.ask != nil { + switch { + case r.Connection != w.ask.connection: + w.ended(w.ask.Link, w.ask.Network, whyLeft) + case !r.checkOn() || (r.Connectivity != ratingPortal && r.Connectivity != ratingFull): + w.ended(w.ask.Link, w.ask.Network, whyNoLongerAsked) + case r.Connectivity == ratingFull: + w.ended(w.ask.Link, w.ask.Network, whySignedIn) + default: + return + } + } + if r.checkOn() && r.Connectivity == ratingPortal && r.active() { + w.asked(r) + } +} + +// webAddress says whether an address is one the watcher keeps and opens: http or https, with a host. +func webAddress(address string) bool { + u, err := url.Parse(address) + return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "" +} + +// asked keeps sign-in-asked for the active connection and holds the ask. +func (w *Watcher) asked(r Rating) { + now := w.Now() + w.ask = &openAsk{Network: r.Network, Link: r.Link, Since: now, connection: r.Connection, address: r.CheckURI} + w.state.AsksOpened++ + w.keep(eventAsked, signInAsked{Node: w.Folder.Node, Link: r.Link, Network: r.Network, Address: r.CheckURI, + At: stamp(now)}) +} + +// ended keeps sign-in-ended and drops the ask. +func (w *Watcher) ended(link, network, why string) { + if w.ask != nil { + w.state.AsksEnded++ + } + w.ask = nil + w.keep(eventEnded, signInEnded{Node: w.Folder.Node, Link: link, Network: network, At: stamp(w.Now()), Why: why}) +} + +// stamp is a time as the events say it: RFC 3339 in UTC, to the second. +func stamp(t time.Time) string { return t.UTC().Truncate(time.Second).Format(time.RFC3339) } + +// keep writes one event into pending/ and holds the folder to its bound, the oldest dropped with a journal line. +func (w *Watcher) keep(event string, body any) { + k, err := w.Folder.keep(event, eventSubject(event, w.Folder.Node), body) + if err != nil { + journal("keeping %s failed: %v", event, err) + return + } + journal("kept %s as %s", event, k.MessageID) + kept, err := w.Folder.pending() + if err != nil { + journal("reading the kept events failed: %v", err) + return + } + for i := 0; len(kept)-i > keptBound; i++ { + if err := w.Folder.drop(kept[i]); err != nil { + journal("dropping the kept event %s past the bound of %d failed: %v", kept[i].MessageID, keptBound, err) + continue + } + w.state.DroppedPastBound++ + journal("dropped the kept event %s past the bound of %d", kept[i].MessageID, keptBound) + } +} + +// answer answers an ask of the watcher's socket: its state, or rating-again, which subscribes again and acts on the +// rating read now as on a change (§12). +func (w *Watcher) answer(ask string) (any, error) { + switch ask { + case askState: + s := w.state + if w.ask != nil { + a := *w.ask + s.Ask = &a + } + return s, nil + case askRatingAgain: + journal("asked rating-again: subscribing again") + w.subscribe() + if !w.state.Subscribed { + return nil, errors.New("subscribing on the system bus failed; waiting for its socket") + } + return w.state, nil + } + return nil, fmt.Errorf("the watcher has no ask %q", ask) +} diff --git a/modules/networkmanager/cmd/uplink-tools/watch_test.go b/modules/networkmanager/cmd/uplink-tools/watch_test.go new file mode 100644 index 000000000..cd6951f7d --- /dev/null +++ b/modules/networkmanager/cmd/uplink-tools/watch_test.go @@ -0,0 +1,311 @@ +package main + +import ( + "encoding/json" + "fmt" + "strings" + "sync" + "testing" + "time" + + "github.com/godbus/dbus/v5" +) + +// The system bus stood in: the rating the test sets, each connection's signals on an unbuffered channel (a send +// returns once the watcher's loop took it), and the system bus's socket fired by the test. +type fakeSystem struct { + mu sync.Mutex + now Rating + reads int + dials int + buses []*fakeBus + socket chan struct{} +} + +type fakeBus struct { + sys *fakeSystem + signals chan signal + closed bool +} + +func (s *fakeSystem) dial() (systemBus, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.dials++ + b := &fakeBus{sys: s, signals: make(chan signal)} + s.buses = append(s.buses, b) + return b, nil +} + +func (s *fakeSystem) set(r Rating) { + s.mu.Lock() + s.now = r + s.mu.Unlock() +} + +func (s *fakeSystem) last() *fakeBus { + s.mu.Lock() + defer s.mu.Unlock() + return s.buses[len(s.buses)-1] +} + +func (s *fakeSystem) counts() (int, int) { + s.mu.Lock() + defer s.mu.Unlock() + return s.reads, s.dials +} + +func (b *fakeBus) listen() (<-chan signal, error) { return b.signals, nil } +func (b *fakeBus) close() { b.closed = true } +func (b *fakeBus) rating() (Rating, error) { + b.sys.mu.Lock() + defer b.sys.mu.Unlock() + b.sys.reads++ + return b.sys.now, nil +} + +// journalLines collects the journal for one test. +func journalLines(t *testing.T) func() []string { + t.Helper() + var mu sync.Mutex + var lines []string + was := journal + journal = func(format string, args ...any) { + mu.Lock() + lines = append(lines, fmt.Sprintf(format, args...)) + mu.Unlock() + } + t.Cleanup(func() { journal = was }) + return func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), lines...) + } +} + +var clockStart = time.Date(2026, 11, 24, 19, 0, 0, 0, time.UTC) + +// aWatcher is a watcher over the stood-in system bus, its clock one second on at each reading. +func aWatcher(t *testing.T, sys *fakeSystem) *Watcher { + t.Helper() + tick := clockStart + var mu sync.Mutex + return &Watcher{Folder: aFolder(t), Dial: sys.dial, Now: func() time.Time { + mu.Lock() + defer mu.Unlock() + tick = tick.Add(time.Second) + return tick + }, SocketThere: func(stop <-chan struct{}) <-chan struct{} { return sys.socket }, asks: make(chan asked)} +} + +// keptSaid is every kept event as ` `, in order. +func keptSaid(t *testing.T, f Folder) []string { + t.Helper() + kept, err := f.pending() + if err != nil { + t.Fatal(err) + } + var out []string + for _, k := range kept { + var b struct{ Node, Link, Network, Address, At, Why string } + if err := json.Unmarshal(k.Body, &b); err != nil { + t.Fatal(err) + } + event := strings.Split(k.MessageID, ".")[1] + if k.Subject != "mesh.seat.node-uplink.event."+event+".laptop" || b.Node != "laptop" || b.At == "" { + t.Errorf("kept %+v %+v", k, b) + } + if event == eventAsked && b.Address != "http://check.example.net/" { + t.Errorf("asked with the address %q", b.Address) + } + out = append(out, strings.Join(strings.Fields(fmt.Sprintf("%s %s %s %s", event, b.Why, b.Network, b.Link)), " ")) + } + return out +} + +func guest(connectivity uint32) Rating { + return Rating{Connectivity: connectivity, CheckEnabled: true, CheckAvailable: true, + CheckURI: "http://check.example.net/", Connection: "/org/freedesktop/NetworkManager/ActiveConnection/1", + Network: "guest-example", Link: "wlan0"} +} + +func other(connectivity uint32) Rating { + r := guest(connectivity) + r.Connection, r.Network, r.Link = "/org/freedesktop/NetworkManager/ActiveConnection/2", "home-example", "eth0" + return r +} + +func with(r Rating, change func(*Rating)) Rating { + change(&r) + return r +} + +// Each line of §21 keeps its event, and with the check off, or a check address that is not http or https, nothing is +// kept (design 08 sign-in-page §21, §25). +func TestEachLineOfTheRulesKeepsItsEvent(t *testing.T) { + off := func(r *Rating) { r.CheckEnabled = false } + unavailable := func(r *Rating) { r.CheckAvailable = false } + none := func(r *Rating) { r.Connection, r.Network, r.Link = "/", "", "" } + for _, c := range []struct { + name string + ratings []Rating + kept []string + }{ + {"PORTAL at the start", []Rating{guest(ratingPortal)}, []string{"sign-in-asked guest-example wlan0"}}, + {"FULL at the start", []Rating{guest(ratingFull)}, + []string{"sign-in-ended no-longer-asked guest-example wlan0"}}, + {"no connection at the start", []Rating{with(guest(ratingNone), none)}, + []string{"sign-in-ended no-longer-asked"}}, + {"PORTAL at a join", []Rating{guest(ratingFull), guest(ratingPortal)}, + []string{"sign-in-ended no-longer-asked guest-example wlan0", "sign-in-asked guest-example wlan0"}}, + {"staying PORTAL says it once", []Rating{guest(ratingPortal), guest(ratingPortal), guest(ratingPortal)}, + []string{"sign-in-asked guest-example wlan0"}}, + {"signed in", []Rating{guest(ratingPortal), guest(ratingFull), guest(ratingFull)}, + []string{"sign-in-asked guest-example wlan0", "sign-in-ended signed-in guest-example wlan0"}}, + {"the connection replaced, PORTAL again", []Rating{guest(ratingPortal), other(ratingPortal)}, + []string{"sign-in-asked guest-example wlan0", "sign-in-ended left guest-example wlan0", + "sign-in-asked home-example eth0"}}, + {"the connection gone", []Rating{guest(ratingPortal), with(guest(ratingNone), none)}, + []string{"sign-in-asked guest-example wlan0", "sign-in-ended left guest-example wlan0"}}, + {"LIMITED", []Rating{guest(ratingPortal), guest(ratingLimited)}, + []string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}}, + {"UNKNOWN", []Rating{guest(ratingPortal), guest(ratingUnknown)}, + []string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}}, + {"the check switched off while asked", []Rating{guest(ratingPortal), with(guest(ratingPortal), off)}, + []string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}}, + {"the check off", []Rating{with(guest(ratingPortal), off), with(guest(ratingFull), off), + with(guest(ratingPortal), off)}, nil}, + {"the check not available", []Rating{with(guest(ratingPortal), unavailable), with(guest(ratingPortal), unavailable)}, + nil}, + {"a check address not http", []Rating{with(guest(ratingPortal), func(r *Rating) { r.CheckURI = "ftp://check.example.net/" })}, + nil}, + } { + t.Run(c.name, func(t *testing.T) { + journalLines(t) + w := aWatcher(t, &fakeSystem{}) + for i, r := range c.ratings { + w.heard(r, i == 0) + } + if got := keptSaid(t, w.Folder); strings.Join(got, "|") != strings.Join(c.kept, "|") { + t.Fatalf("kept %q, want %q", got, c.kept) + } + }) + } +} + +// Past 256 kept events the oldest goes, with a journal line naming it, and the state counts it (§20, §25). +func TestPastTheBoundTheOldestKeptEventGoes(t *testing.T) { + lines := journalLines(t) + w := aWatcher(t, &fakeSystem{}) + for range keptBound { + if _, err := w.Folder.keep(eventEnded, eventSubject(eventEnded, "laptop"), map[string]string{}); err != nil { + t.Fatal(err) + } + } + w.heard(guest(ratingPortal), true) + kept, _ := w.Folder.pending() + if len(kept) != keptBound || kept[0].Sequence != 2 || kept[len(kept)-1].MessageID != "laptop.sign-in-asked.257" { + t.Fatalf("kept %d, from %d", len(kept), kept[0].Sequence) + } + said := strings.Join(lines(), "\n") + if !strings.Contains(said, "dropped the kept event laptop.sign-in-ended.1 past the bound of 256") || + w.state.DroppedPastBound != 1 { + t.Fatalf("the drop was not said: %s", said) + } +} + +// The system bus dropping and its socket coming back make the watcher subscribe again and act on the rating read then +// as on a change; rating-again does the same at once; between them, nothing reads the rating but a signal (§14, §25). +func TestTheWatcherSubscribesAgainAndRunsOnNoTimer(t *testing.T) { + lines := journalLines(t) + sys := &fakeSystem{socket: make(chan struct{})} + sys.set(guest(ratingFull)) + w := aWatcher(t, sys) + stop := make(chan struct{}) + done := make(chan struct{}) + go func() { w.run(stop); close(done) }() + defer func() { close(stop); <-done }() + state := func() watcherState { + s, err := w.askLoop(askState) + if err != nil { + t.Fatal(err) + } + return s.(watcherState) + } + if s := state(); !s.Subscribed || s.Rating != "FULL" { + t.Fatalf("at its start %+v", s) + } + for range 3 { + state() + } + if reads, _ := sys.counts(); reads != 1 { + t.Fatalf("the rating was read %d times with no signal: something reads it on a timer", reads) + } + sys.set(guest(ratingPortal)) + sys.last().signals <- signal{Rating: true} + if s := state(); s.Ask == nil || s.Ask.Network != "guest-example" { + t.Fatalf("PORTAL heard as %+v", s) + } + + close(sys.last().signals) + if s := state(); s.Subscribed { + t.Fatal("subscribed after the system bus dropped") + } + if !strings.Contains(strings.Join(lines(), "\n"), "the system bus connection dropped") { + t.Fatal("the drop was not written to the journal") + } + sys.set(guest(ratingFull)) + sys.socket <- struct{}{} + if s := state(); !s.Subscribed || s.Ask != nil || s.Rating != "FULL" { + t.Fatalf("after the socket came back %+v", s) + } + if got := keptSaid(t, w.Folder); got[len(got)-1] != "sign-in-ended signed-in guest-example wlan0" { + t.Fatalf("the rating read on subscribing again was not acted on as a change: %q", got) + } + + sys.set(guest(ratingPortal)) + if _, err := w.askLoop(askRatingAgain); err != nil { + t.Fatal(err) + } + if reads, dials := sys.counts(); dials != 3 || reads != 4 || !sys.buses[1].closed { + t.Fatalf("rating-again: %d dials, %d reads", dials, reads) + } + if s := state(); !s.Subscribed || s.Ask == nil || s.AsksOpened != 2 || s.AsksEnded != 1 { + t.Fatalf("after rating-again %+v", s) + } +} + +// The signals the watcher hears, as the system bus sends them (recorded with dbus-monitor): the network manager's +// PropertiesChanged for a property of the rating, not for another, and logind's SessionNew (§14, §17). +func TestTheWatcherHearsTheSystemBusSignals(t *testing.T) { + changed := func(props map[string]dbus.Variant, invalidated []string) *dbus.Signal { + return &dbus.Signal{Sender: ":1.5", Path: nmPath, Name: "org.freedesktop.DBus.Properties.PropertiesChanged", + Body: []any{"org.freedesktop.NetworkManager", props, invalidated}} + } + for _, c := range []struct { + name string + s *dbus.Signal + want signal + ok bool + }{ + {"Connectivity", changed(map[string]dbus.Variant{"Connectivity": dbus.MakeVariant(uint32(2))}, []string{}), + signal{Rating: true}, true}, + {"PrimaryConnection", changed(map[string]dbus.Variant{"PrimaryConnection": dbus.MakeVariant(dbus.ObjectPath("/"))}, + []string{}), signal{Rating: true}, true}, + {"ConnectivityCheckUri invalidated", changed(map[string]dbus.Variant{}, []string{"ConnectivityCheckUri"}), + signal{Rating: true}, true}, + {"another property", changed(map[string]dbus.Variant{"Metered": dbus.MakeVariant(uint32(4))}, []string{}), + signal{}, false}, + {"another interface", &dbus.Signal{Path: nmPath, Name: "org.freedesktop.DBus.Properties.PropertiesChanged", + Body: []any{"org.freedesktop.NetworkManager.Device", map[string]dbus.Variant{"Connectivity": dbus.MakeVariant(uint32(2))}, + []string{}}}, signal{}, false}, + {"SessionNew", &dbus.Signal{Sender: ":1.3", Path: login1Path, Name: "org.freedesktop.login1.Manager.SessionNew", + Body: []any{"4", dbus.ObjectPath("/org/freedesktop/login1/session/_34")}}, + signal{Session: "/org/freedesktop/login1/session/_34"}, true}, + } { + got, ok := readSignal(c.s) + if ok != c.ok || got != c.want { + t.Errorf("%s: heard %+v %v", c.name, got, ok) + } + } +} diff --git a/modules/networkmanager/go.mod b/modules/networkmanager/go.mod index ead847944..493db66c3 100644 --- a/modules/networkmanager/go.mod +++ b/modules/networkmanager/go.mod @@ -2,7 +2,11 @@ module networkmanager go 1.26.0 -require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 +require ( + git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 + github.com/godbus/dbus/v5 v5.1.0 + golang.org/x/sys v0.48.0 +) require ( github.com/klauspost/compress v1.20.1 // indirect @@ -10,5 +14,4 @@ require ( github.com/nats-io/nkeys v0.4.16 // indirect github.com/nats-io/nuid v1.0.1 // indirect golang.org/x/crypto v0.57.0 // indirect - golang.org/x/sys v0.48.0 // indirect ) diff --git a/modules/networkmanager/go.sum b/modules/networkmanager/go.sum index 0daef11ff..c822b945f 100644 --- a/modules/networkmanager/go.sum +++ b/modules/networkmanager/go.sum @@ -1,12 +1,14 @@ -github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= -github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= github.com/nats-io/nats.go v1.54.0/go.mod h1:y+DZoD1oBOYfZTU681eTUiUjI0vbqYGixNVFHcjHJ0k= -github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg= +github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA= github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs= -github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= +github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=