Skip to content

Commit

Permalink
fix(yggctl): prefer system bus when run as root
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
subpop committed Jul 21, 2023
1 parent 0da66f8 commit 4e62969
Showing 1 changed file with 23 additions and 24 deletions.
47 changes: 23 additions & 24 deletions cmd/yggctl/actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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
}

0 comments on commit 4e62969

Please sign in to comment.