Skip to content

Commit

Permalink
Treat XDG_CONFIG_HOME and $HOME/.config the same way
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
rhatdan committed Sep 5, 2024
1 parent 9f9e76b commit cd53592
Showing 1 changed file with 25 additions and 15 deletions.
40 changes: 25 additions & 15 deletions pkg/homedir/homedir_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,24 @@ func isWriteableOnlyByOwner(perm os.FileMode) bool {
return (perm & 0o722) == 0o700
}

// GetConfigHome returns XDG_CONFIG_HOME.
// GetConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set.
//
// ConfigHome returns XDG_CONFIG_HOME.
// ConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set.
// Verifies ownership of config directory matches the current process or
// returns error.
// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
func GetConfigHome() (string, error) {
rootlessConfigHomeDir, rootlessConfigHomeDirError = ConfigHome()
if rootlessConfigHomeDirError == nil {
_ = os.MkdirAll(rootlessConfigHomeDir, 0o700)
}

return rootlessConfigHomeDir, rootlessConfigHomeDirError
}

// ConfigHome returns XDG_CONFIG_HOME. (Deprecated)
// ConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set.
// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
func ConfigHome() (string, error) {
rootlessConfigHomeDirOnce.Do(func() {
cfgHomeDir := os.Getenv("XDG_CONFIG_HOME")
if cfgHomeDir == "" {
Expand All @@ -115,18 +128,15 @@ func GetConfigHome() (string, error) {
rootlessConfigHomeDirError = fmt.Errorf("cannot resolve %s: %w", home, err)
return
}
tmpDir := filepath.Join(resolvedHome, ".config")
_ = os.MkdirAll(tmpDir, 0o700)
st, err := os.Stat(tmpDir)
if err != nil {
rootlessConfigHomeDirError = err
return
} else if int(st.Sys().(*syscall.Stat_t).Uid) == os.Geteuid() {
cfgHomeDir = tmpDir
} else {
rootlessConfigHomeDirError = fmt.Errorf("path %q exists and it is not owned by the current user", tmpDir)
return
}
cfgHomeDir = filepath.Join(resolvedHome, ".config")
}
st, err := os.Stat(cfgHomeDir)
if err != nil {
rootlessConfigHomeDirError = err
return
} else if int(st.Sys().(*syscall.Stat_t).Uid) != os.Geteuid() {
rootlessConfigHomeDirError = fmt.Errorf("path %q exists and it is not owned by the current user", tmpDir)
return
}
rootlessConfigHomeDir = cfgHomeDir
})
Expand Down

0 comments on commit cd53592

Please sign in to comment.