Skip to content

Commit

Permalink
Replace body of hasPermissionToDir with unix.Access
Browse files Browse the repository at this point in the history
Rip out the body of interp.hasPermissionToDir and replace it with just a
call to unix.Access(path, unix.X_OK).

Update the function signature of hasPermissionToDir in os_notunix.go,
too.
  • Loading branch information
theclapp committed Sep 28, 2023
1 parent d8a48c2 commit c5b3b2f
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 58 deletions.
2 changes: 1 addition & 1 deletion interp/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -963,7 +963,7 @@ func (r *Runner) changeDir(ctx context.Context, path string) int {
if err != nil || !info.IsDir() {
return 1
}
if !hasPermissionToDir(info) {
if !hasPermissionToDir(path) {
return 1
}
r.Dir = path
Expand Down
2 changes: 1 addition & 1 deletion interp/os_notunix.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ func mkfifo(path string, mode uint32) error {
}

// hasPermissionToDir is a no-op on Windows.
func hasPermissionToDir(info os.FileInfo) bool {
func hasPermissionToDir(string) bool {
return true
}
58 changes: 2 additions & 56 deletions interp/os_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,6 @@
package interp

import (
"os"
"os/user"
"strconv"
"syscall"

"golang.org/x/sys/unix"
)

Expand All @@ -20,55 +15,6 @@ func mkfifo(path string, mode uint32) error {

// hasPermissionToDir returns true if the OS current user has execute
// permission to the given directory
func hasPermissionToDir(info os.FileInfo) bool {
user, err := user.Current()
if err != nil {
return false // unknown user; assume no permissions
}
uid, err := strconv.Atoi(user.Uid)
if err != nil {
return false // on POSIX systems, Uid should always be a decimal number
}
if uid == 0 {
return true // super-user
}

st, _ := info.Sys().(*syscall.Stat_t)
if st == nil {
panic("unexpected info.Sys type")
}
perm := info.Mode().Perm()

// user (u)
if st.Uid == uint32(uid) {
return perm&0o100 != 0
}

// group (g) -- check the users's actual group, and then all the other
// groups they're in.
gid, err := strconv.Atoi(user.Gid)
if err != nil {
return false // on POSIX systems, Gid should always be a decimal number
}
if st.Gid == uint32(gid) {
return perm&0o010 != 0
}
gids, err := user.GroupIds()
if err != nil {
// If we can't get the list of group IDs, we can't know if the group
// permissions, so default to false/no access.
return false
}
for _, gid := range gids {
gid, err := strconv.Atoi(gid)
if err != nil {
return false
}
if st.Gid == uint32(gid) {
return perm&0o010 != 0
}
}

// remaining users (o)
return perm&0o001 != 0
func hasPermissionToDir(path string) bool {
return unix.Access(path, unix.X_OK) == nil
}

0 comments on commit c5b3b2f

Please sign in to comment.