//go:build unix
package install
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"syscall"
)
// HostSystem is the real System: it shells out to useradd and the rest.
type HostSystem struct{}
func (HostSystem) Geteuid() int { return os.Geteuid() }
func (HostSystem) Hostname() (string, error) { return os.Hostname() }
func (HostSystem) Executable() (string, error) { return os.Executable() }
func (HostSystem) LookPath(n string) (string, error) { return exec.LookPath(n) }
func (HostSystem) Run(ctx context.Context, name string, args ...string) ([]byte, error) {
out, err := exec.CommandContext(ctx, name, args...).CombinedOutput()
if err != nil {
return out, fmt.Errorf("%s %s: %v: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))
}
return out, nil
}
func (h HostSystem) RunAs(ctx context.Context, who, name string, args ...string) ([]byte, error) {
return h.Run(ctx, "runuser", append([]string{"-u", who, "--", name}, args...)...)
}
func (HostSystem) UserExists(name string) bool { _, err := user.Lookup(name); return err == nil }
func (HostSystem) GroupExists(name string) bool { _, err := user.LookupGroup(name); return err == nil }
func (HostSystem) InGroup(who, group string) bool {
u, err := user.Lookup(who)
if err != nil {
return false
}
g, err := user.LookupGroup(group)
if err != nil {
return false
}
ids, err := u.GroupIds()
if err != nil {
return false
}
for _, id := range ids {
if id == g.Gid {
return true
}
}
return false
}
func (h HostSystem) AddGroup(name string) error {
_, err := h.Run(context.Background(), "groupadd", "--system", name)
return err
}
func (h HostSystem) AddUser(u User) error {
args := []string{"--system", "--gid", u.Group, "--shell", u.Shell, "--no-create-home"}
if u.Home != "" {
args = append(args, "--home-dir", u.Home)
}
_, err := h.Run(context.Background(), "useradd", append(args, u.Name)...)
return err
}
func (h HostSystem) AddToGroup(who, group string) error {
_, err := h.Run(context.Background(), "usermod", "-aG", group, who)
return err
}
func (h HostSystem) DelUser(name string) error {
_, err := h.Run(context.Background(), "userdel", name)
return err
}
func (h HostSystem) DelGroup(name string) error {
_, err := h.Run(context.Background(), "groupdel", name)
return err
}
// lchownTo changes the owner of path itself, never of what a link
// there points at.
func lchownTo(path, owner, group string) error {
uid, gid, err := ids(owner, group)
if err != nil {
return err
}
return os.Lchown(path, uid, gid)
}
func ids(owner, group string) (uid, gid int, err error) {
uid, gid = -1, -1
if owner != "" {
u, err := user.Lookup(owner)
if err != nil {
return 0, 0, err
}
uid, _ = strconv.Atoi(u.Uid)
}
if group != "" {
g, err := user.LookupGroup(group)
if err != nil {
return 0, 0, err
}
gid, _ = strconv.Atoi(g.Gid)
}
return uid, gid, nil
}
// Mkdir makes the directory, or repairs one that is there. What is
// there must be a real directory: a link, a file or anything else is
// refused, and the owner and mode are set through the open directory,
// so a link swapped in meanwhile is not followed.
func (HostSystem) Mkdir(path, owner, group string, mode fs.FileMode) error {
if fi, err := os.Lstat(path); errors.Is(err, fs.ErrNotExist) {
if err := os.Mkdir(path, 0o700); err != nil {
return err
}
} else if err != nil {
return err
} else if !fi.IsDir() {
return fmt.Errorf("%s is not a directory (it is a link or a file); refusing to use it", path)
}
d, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_DIRECTORY, 0)
if err != nil {
return fmt.Errorf("%s: %v", path, err)
}
defer d.Close()
uid, gid, err := ids(owner, group)
if err != nil {
return err
}
if err := d.Chown(uid, gid); err != nil {
return err
}
return d.Chmod(mode)
}
func (h HostSystem) WriteFile(path string, data []byte, owner, group string, mode fs.FileMode) error {
return h.put(path, bytes.NewReader(data), owner, group, mode)
}
func (h HostSystem) CopyFile(src, dst, owner, group string, mode fs.FileMode) error {
f, err := os.OpenFile(src, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return err
}
defer f.Close()
return h.put(dst, f, owner, group, mode)
}
// put writes a new file beside path and renames it into place. The new
// file is made exclusively, without following a link, and with its mode
// from the first byte: a secret is never written and then restricted.
func (HostSystem) put(path string, r io.Reader, owner, group string, mode fs.FileMode) error {
tmp := path + ".new"
if err := os.Remove(tmp); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW, mode)
if err != nil {
return err
}
uid, gid, err := ids(owner, group)
if err == nil {
err = f.Chown(uid, gid)
}
if err == nil {
err = f.Chmod(mode) // the umask may have cut the mode made
}
if err == nil {
_, err = io.Copy(f, r)
}
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Rename(tmp, path)
}
if err != nil {
os.Remove(tmp)
}
return err
}
func (HostSystem) Rename(from, to string) error { return os.Rename(from, to) }
func (HostSystem) ReadFile(path string) ([]byte, error) {
f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return nil, err
}
defer f.Close()
data, err := io.ReadAll(io.LimitReader(f, readFileMax+1))
if err != nil {
return nil, err
}
if len(data) > readFileMax {
return nil, fmt.Errorf("%s: larger than %d bytes, which ReadFile does not read", path, readFileMax)
}
return data, nil
}
// readFileMax bounds what ReadFile reads whole. The program is copied
// and hashed as a stream instead: a release is well past this, and a
// silent short read once installed a program cut off at 64 MiB.
const readFileMax = 16 << 20
func (HostSystem) Sum256(path string) (string, error) {
f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func (HostSystem) ReadDir(path string) ([]string, error) {
es, err := os.ReadDir(path)
var names []string
for _, e := range es {
names = append(names, e.Name())
}
return names, err
}
func (HostSystem) Stat(path string) (Info, error) {
fi, err := os.Lstat(path) // a link is a link: it has no owner or mode worth trusting
if err != nil {
return Info{}, err
}
in := Info{Mode: fi.Mode().Perm(), IsDir: fi.IsDir()}
if st, ok := fi.Sys().(*syscall.Stat_t); ok {
in.Owner, in.Group = strconv.Itoa(int(st.Uid)), strconv.Itoa(int(st.Gid))
if u, err := user.LookupId(in.Owner); err == nil {
in.Owner = u.Username
}
if g, err := user.LookupGroupId(in.Group); err == nil {
in.Group = g.Name
}
}
return in, nil
}
func (HostSystem) Exists(path string) bool { _, err := os.Stat(path); return err == nil }
func (HostSystem) Remove(path string) error {
if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
return nil
}
func (HostSystem) RemoveAll(path string) error { return os.RemoveAll(filepath.Clean(path)) }
func (HostSystem) DiskFree(path string) (uint64, error) {
var st syscall.Statfs_t
if err := syscall.Statfs(path, &st); err != nil {
return 0, err
}
return uint64(st.Bavail) * uint64(st.Bsize), nil
}