@@ -2,8 +2,11 @@ package homedir
2
2
3
3
import (
4
4
"errors"
5
+ "fmt"
5
6
"os"
6
7
"path/filepath"
8
+
9
+ "github.com/containers/storage/pkg/unshare"
7
10
)
8
11
9
12
// GetDataHome returns XDG_DATA_HOME.
@@ -35,3 +38,47 @@ func GetCacheHome() (string, error) {
35
38
}
36
39
return filepath .Join (home , ".cache" ), nil
37
40
}
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