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 ( "bytes" "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 } func (d *dbusSystem) sessions(uid uint32) ([]loginSession, error) { var listed []struct { ID string UID uint32 User string Seat string Path dbus.ObjectPath } if err := d.conn.Object(login1Name, login1Path).Call(login1Iface+".ListSessions", 0).Store(&listed); err != nil { return nil, fmt.Errorf("logind's sessions: %w", err) } var out []loginSession for _, l := range listed { if l.UID != uid { continue } s, err := d.session(string(l.Path)) if err != nil { journal("reading session %s failed: %v", l.ID, err) continue } out = append(out, s) } return out, nil } func (d *dbusSystem) session(path string) (loginSession, error) { o := d.conn.Object(login1Name, dbus.ObjectPath(path)) s := loginSession{Path: path} var user struct { UID uint32 Path dbus.ObjectPath } for name, into := range map[string]any{"Id": &s.ID, "Type": &s.Type, "Remote": &s.Remote, "State": &s.State, "User": &user} { v, err := o.GetProperty("org.freedesktop.login1.Session." + name) if err != nil { return s, fmt.Errorf("session %s's %s: %w", path, name, err) } if err := dbus.Store([]any{v.Value()}, into); err != nil { return s, fmt.Errorf("session %s's %s: %w", path, name, err) } } s.UID = user.UID v, err := d.conn.Object(login1Name, user.Path).GetProperty("org.freedesktop.login1.User.RuntimePath") if err != nil { return s, fmt.Errorf("the user %d's RuntimePath: %w", user.UID, err) } s.RuntimePath, _ = v.Value().(string) return s, nil } // userEnvironment is the user manager's Environment, read over the session bus at bus. func userEnvironment(bus string) ([]string, error) { conn, err := dbus.Connect(bus) if err != nil { return nil, err } defer conn.Close() v, err := conn.Object("org.freedesktop.systemd1", "/org/freedesktop/systemd1"). GetProperty("org.freedesktop.systemd1.Manager.Environment") if err != nil { return nil, err } env, _ := v.Value().([]string) return env, nil } // fileEvents fires at each file event of the kernel that makes a file in one of dirs (a burst is one), until stop // closes. A folder that is not there is not watched, and said. func fileEvents(dirs []string, stop <-chan struct{}) <-chan struct{} { return watchFiles(dirs, nil, stop) } // fileMade fires at each file event of the kernel that makes name in dir, until stop closes. func fileMade(dir, name string, stop <-chan struct{}) <-chan struct{} { return watchFiles([]string{dir}, func(made string) bool { return made == name }, stop) } // watchFiles fires at each file event that makes a file in dirs whose name match takes (any, when nil). func watchFiles(dirs []string, match func(string) bool, stop <-chan struct{}) <-chan struct{} { out := make(chan struct{}, 1) fd, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK) if err != nil { journal("watching %v failed: %v", dirs, err) return out } for _, dir := range dirs { if _, err := unix.InotifyAddWatch(fd, dir, unix.IN_CREATE|unix.IN_MOVED_TO); err != nil { journal("watching %s failed: %v", dir, err) } } f := os.NewFile(uintptr(fd), "inotify") go func() { <-stop f.Close() }() go func() { defer f.Close() for { names, err := readInotify(f) if err != nil { return } matched := match == nil for _, name := range names { matched = matched || match(name) } if !matched { continue } select { case out <- struct{}{}: default: } } }() return out } // pathsMade hands each path a file event of the kernel makes in one of dirs, until stop closes; a folder that is not // there is not watched, and said. func pathsMade(dirs []string, stop <-chan struct{}) <-chan string { out := make(chan string, 16) fd, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK) if err != nil { journal("watching %v failed: %v", dirs, err) return out } wds := map[int32]string{} for _, dir := range dirs { wd, err := unix.InotifyAddWatch(fd, dir, unix.IN_CREATE|unix.IN_MOVED_TO) if err != nil { journal("watching %s failed: %v", dir, err) continue } wds[int32(wd)] = dir } f := os.NewFile(uintptr(fd), "inotify") go func() { <-stop f.Close() }() go func() { defer f.Close() buf := make([]byte, 64*(unix.SizeofInotifyEvent+unix.NAME_MAX+1)) for { n, err := f.Read(buf) if err != nil { return } 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 := string(bytes.TrimRight(buf[nameAt:end], "\x00")) off = end if dir, ok := wds[ev.Wd]; ok && name != "" { select { case out <- filepath.Join(dir, name): case <-stop: return } } } } }() return out }