From bbed36a634d899d3c86ff6135223287936c2f340 Mon Sep 17 00:00:00 2001 From: huwf5 Date: Sun, 1 Oct 2023 18:47:36 +0800 Subject: [PATCH] fix: make sure sudo mode can still open browser --- client/client.go | 4 ++-- cmd/client/main.go | 2 +- web/server/util/browser.go | 12 +++++++++++- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/client/client.go b/client/client.go index e544ad3e..a0ea05ad 100644 --- a/client/client.go +++ b/client/client.go @@ -462,10 +462,10 @@ func (c *Client) Close() { // Shutdown stops the client gracefully. func (c *Client) Shutdown() { defer c.Logger.Close() - c.ShutdownWithClosingLogger() + c.ShutdownWithoutClosingLogger() } -func (c *Client) ShutdownWithClosingLogger() { +func (c *Client) ShutdownWithoutClosingLogger() { if !atomic.CompareAndSwapUint32(&c.closing, 0, 1) { return } diff --git a/cmd/client/main.go b/cmd/client/main.go index 528371c8..3f40cf6f 100644 --- a/cmd/client/main.go +++ b/cmd/client/main.go @@ -62,7 +62,7 @@ func main() { continue } // avoid port conflict - c.ShutdownWithClosingLogger() + c.ShutdownWithoutClosingLogger() err = runCmd(os.Args) if err != nil { diff --git a/web/server/util/browser.go b/web/server/util/browser.go index 71b8bed0..dc0224b7 100644 --- a/web/server/util/browser.go +++ b/web/server/util/browser.go @@ -4,6 +4,7 @@ import ( "errors" "net/http" "net/url" + "os" "os/exec" "runtime" "strings" @@ -21,7 +22,16 @@ func OpenBrowser(url string) error { case "darwin": cmd = exec.Command("open", webUrl) case "linux": - cmd = exec.Command("xdg-open", webUrl) + // Check if running as root + if os.Geteuid() == 0 { + originalUser := os.Getenv("SUDO_USER") + if originalUser == "" { + originalUser = "nobody" // fallback user if SUDO_USER is not set + } + cmd = exec.Command("sudo", "-u", originalUser, "xdg-open", webUrl) + } else { + cmd = exec.Command("xdg-open", webUrl) + } default: return errors.New("unsupported platform to open browser") }