Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions contrib/cmd/fs-idmap/fs-idmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"fmt"
"log"
"os"
"os/exec"
"syscall"
Expand All @@ -11,40 +10,52 @@ import (
)

func main() {
if len(os.Args) < 2 {
log.Fatalf("usage: %s path_to_mount_set_attr", os.Args[0])
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "usage:", os.Args[0], "path_to_mount_set_attr")
os.Exit(1)
}

src := os.Args[1]
treeFD, err := unix.OpenTree(-1, src, uint(unix.OPEN_TREE_CLONE|unix.OPEN_TREE_CLOEXEC|unix.AT_EMPTY_PATH|unix.AT_RECURSIVE))
if err := supportsIDMap(src); err != nil {
fmt.Fprintln(os.Stderr, "fatal error:", err)
os.Exit(1)
}
}

func supportsIDMap(src string) error {
treeFD, err := unix.OpenTree(unix.AT_FDCWD, src, uint(unix.OPEN_TREE_CLONE|unix.OPEN_TREE_CLOEXEC|unix.AT_EMPTY_PATH))
if err != nil {
log.Fatalf("error calling open_tree %q: %v", src, err)
return fmt.Errorf("error calling open_tree %q: %w", src, err)
}
defer unix.Close(treeFD)

cmd := exec.Command("/usr/bin/sleep", "5")
cmd := exec.Command("sleep", "5")
cmd.SysProcAttr = &syscall.SysProcAttr{
Cloneflags: syscall.CLONE_NEWUSER,
UidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: 65536, Size: 65536}},
GidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: 65536, Size: 65536}},
}
if err := cmd.Start(); err != nil {
log.Fatalf("failed to run the helper binary: %v", err)
return fmt.Errorf("failed to run the helper binary: %w", err)
}
defer func() {
_ = cmd.Process.Kill()
_ = cmd.Wait()
}()

path := fmt.Sprintf("/proc/%d/ns/user", cmd.Process.Pid)
var userNsFile *os.File
if userNsFile, err = os.Open(path); err != nil {
log.Fatalf("unable to get user ns file descriptor: %v", err)
return
return fmt.Errorf("unable to get user ns file descriptor: %w", err)
}
defer userNsFile.Close()

attr := unix.MountAttr{
Attr_set: unix.MOUNT_ATTR_IDMAP,
Userns_fd: uint64(userNsFile.Fd()),
}
if err := unix.MountSetattr(treeFD, "", unix.AT_EMPTY_PATH|unix.AT_RECURSIVE, &attr); err != nil {
log.Fatalf("error calling mount_setattr: %v", err)
if err := unix.MountSetattr(treeFD, "", unix.AT_EMPTY_PATH, &attr); err != nil {
return fmt.Errorf("error calling mount_setattr: %w", err)
}

return nil
}