Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(yggctl): prefer system bus when run as root #143

Merged
merged 1 commit into from
Jul 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 {
subpop marked this conversation as resolved.
Show resolved Hide resolved
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
}