Skip to content

Commit a3a48cc

Browse files
committed
pkg/homedir: new function SetXdgDirs
Signed-off-by: Giuseppe Scrivano <[email protected]>
1 parent be1e7f7 commit a3a48cc

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

pkg/homedir/homedir.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@ package homedir
22

33
import (
44
"errors"
5+
"fmt"
56
"os"
67
"path/filepath"
8+
9+
"github.com/containers/storage/pkg/unshare"
710
)
811

912
// GetDataHome returns XDG_DATA_HOME.
@@ -35,3 +38,47 @@ func GetCacheHome() (string, error) {
3538
}
3639
return filepath.Join(home, ".cache"), nil
3740
}
41+
42+
// SetXdgDirs ensures the XDG_RUNTIME_DIR, DBUS_SESSION_BUS_ADDRESS and XDG_CONFIG_HOME env
43+
// variables are set when running as rootless.
44+
// containers/image uses XDG_RUNTIME_DIR to locate the auth file, XDG_CONFIG_HOME is
45+
// use for the containers.conf configuration file.
46+
func SetXdgDirs() error {
47+
rootless := unshare.IsRootless()
48+
if !rootless {
49+
return nil
50+
}
51+
52+
// Set up XDG_RUNTIME_DIR
53+
runtimeDir := os.Getenv("XDG_RUNTIME_DIR")
54+
55+
if runtimeDir == "" {
56+
var err error
57+
runtimeDir, err = GetRuntimeDir()
58+
if err != nil {
59+
return err
60+
}
61+
}
62+
if err := os.Setenv("XDG_RUNTIME_DIR", runtimeDir); err != nil {
63+
return fmt.Errorf("cannot set XDG_RUNTIME_DIR: %w", err)
64+
}
65+
66+
if os.Getenv("DBUS_SESSION_BUS_ADDRESS") == "" {
67+
sessionAddr := filepath.Join(runtimeDir, "bus")
68+
if _, err := os.Stat(sessionAddr); err == nil {
69+
os.Setenv("DBUS_SESSION_BUS_ADDRESS", fmt.Sprintf("unix:path=%s", sessionAddr))
70+
}
71+
}
72+
73+
// Set up XDG_CONFIG_HOME
74+
if cfgHomeDir := os.Getenv("XDG_CONFIG_HOME"); cfgHomeDir == "" {
75+
cfgHomeDir, err := GetConfigHome()
76+
if err != nil {
77+
return err
78+
}
79+
if err := os.Setenv("XDG_CONFIG_HOME", cfgHomeDir); err != nil {
80+
return fmt.Errorf("cannot set XDG_CONFIG_HOME: %w", err)
81+
}
82+
}
83+
return nil
84+
}

0 commit comments

Comments
 (0)