Skip to content

Commit f74b71b

Browse files
committed
Treat XDG_CONFIG_HOME and $HOME/.config the same way
Currently we handle XDG_CONFIG_HOME and the fallback $HOME/.config differently. We create the later if it does not exist and verify that it is owned by the current user. This patch makes XDG_CONFIG_HOME follow the same pattern. Signed-off-by: Daniel J Walsh <[email protected]>
1 parent 465c38f commit f74b71b

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

pkg/homedir/homedir_unix.go

+32-2
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,39 @@ func isWriteableOnlyByOwner(perm os.FileMode) bool {
101101
return (perm & 0o722) == 0o700
102102
}
103103

104-
// GetConfigHome returns XDG_CONFIG_HOME.
104+
// ConfigHome returns XDG_CONFIG_HOME.
105+
// ConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set.
106+
// Verifies ownership of config directory matches the current process or
107+
// returns error.
108+
// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
109+
func GetConfigHome() (string, error) {
110+
rootlessConfigHomeDirOnce.Do(func() {
111+
tmpDir := os.Getenv("XDG_CONFIG_HOME")
112+
if tmpDir == "" {
113+
home := Get()
114+
resolvedHome, err := filepath.EvalSymlinks(home)
115+
if err != nil {
116+
rootlessConfigHomeDirError = fmt.Errorf("cannot resolve %s: %w", home, err)
117+
return
118+
}
119+
tmpDir = filepath.Join(resolvedHome, ".config")
120+
}
121+
st, err := os.Stat(tmpDir)
122+
if err == nil {
123+
if int(st.Sys().(*syscall.Stat_t).Uid) == os.Geteuid() {
124+
rootlessConfigHomeDir = tmpDir
125+
} else {
126+
rootlessConfigHomeDirError = fmt.Errorf("path %q exists and it is not owned by the current user", tmpDir)
127+
return
128+
}
129+
}
130+
})
131+
132+
return rootlessConfigHomeDir, rootlessConfigHomeDirError
133+
}
134+
135+
// GetConfigHome returns XDG_CONFIG_HOME. (Deprecated)
105136
// GetConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set.
106-
//
107137
// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
108138
func GetConfigHome() (string, error) {
109139
rootlessConfigHomeDirOnce.Do(func() {

0 commit comments

Comments
 (0)