From 4e62969506fc95cea7f26dc7dddbe7e4fdd1b444 Mon Sep 17 00:00:00 2001 From: Link Dupont Date: Wed, 19 Jul 2023 13:03:47 -0400 Subject: [PATCH] fix(yggctl): prefer system bus when run as root yggctl will attempt to connect to the session bus only if DBUS_SESSION_BUS_ADDRESS is non-empty and the effective UID of the process is greater than zero. This results in root invocations of yggctl preferring the system bus over the session bus. Signed-off-by: Link Dupont --- cmd/yggctl/actions.go | 47 +++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/cmd/yggctl/actions.go b/cmd/yggctl/actions.go index cfb570d9..f45d279f 100644 --- a/cmd/yggctl/actions.go +++ b/cmd/yggctl/actions.go @@ -43,14 +43,7 @@ func generateControlMessageAction(c *cli.Context) error { } func workersAction(c *cli.Context) error { - var conn *dbus.Conn - var err error - - if os.Getenv("DBUS_SESSION_BUS_ADDRESS") != "" { - conn, err = dbus.ConnectSessionBus() - } else { - conn, err = dbus.ConnectSystemBus() - } + conn, err := connectBus() if err != nil { return cli.Exit(fmt.Errorf("cannot connect to bus: %w", err), 1) } @@ -91,14 +84,7 @@ func workersAction(c *cli.Context) error { } func dispatchAction(c *cli.Context) error { - var conn *dbus.Conn - var err error - - if os.Getenv("DBUS_SESSION_BUS_ADDRESS") != "" { - conn, err = dbus.ConnectSessionBus() - } else { - conn, err = dbus.ConnectSystemBus() - } + conn, err := connectBus() if err != nil { return cli.Exit(fmt.Errorf("cannot connect to bus: %w", err), 1) } @@ -136,14 +122,7 @@ func dispatchAction(c *cli.Context) error { } func listenAction(ctx *cli.Context) error { - var conn *dbus.Conn - var err error - - if os.Getenv("DBUS_SESSION_BUS_ADDRESS") != "" { - conn, err = dbus.ConnectSessionBus() - } else { - conn, err = dbus.ConnectSystemBus() - } + conn, err := connectBus() if err != nil { return cli.Exit(fmt.Errorf("cannot connect to bus: %w", err), 1) } @@ -209,3 +188,23 @@ func generateMessage(messageType, responseTo, directive, content string, metadat return nil, fmt.Errorf("unsupported message type: %v", messageType) } } + +func connectBus() (*dbus.Conn, error) { + var connect func(...dbus.ConnOption) (*dbus.Conn, error) + var conn *dbus.Conn + var err error + var errMsg string + if os.Getenv("DBUS_SESSION_BUS_ADDRESS") != "" && os.Geteuid() > 0 { + connect = dbus.ConnectSessionBus + errMsg = "cannot connect to session bus (" + os.Getenv("DBUS_SESSION_BUS_ADDRESS") + "): %w" + } else { + connect = dbus.ConnectSystemBus + errMsg = "cannot connect to system bus: %w" + } + + conn, err = connect() + if err != nil { + return nil, fmt.Errorf(errMsg, err) + } + return conn, nil +}