Skip to content
quarry Artifact [4ad6d31fe9]
Login

Artifact [4ad6d31fe9]

Artifact 4ad6d31fe9e507d9d89d3aeb375097aa7b1f017b5976f170c68a0294de23ab76:


//go:build unix

package install

import (
	"bytes"
	"context"
	"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
}

func chownTo(path, owner, group string) error {
	uid, gid := -1, -1
	if owner != "" {
		u, err := user.Lookup(owner)
		if err != nil {
			return err
		}
		uid, _ = strconv.Atoi(u.Uid)
	}
	if group != "" {
		g, err := user.LookupGroup(group)
		if err != nil {
			return err
		}
		gid, _ = strconv.Atoi(g.Gid)
	}
	return os.Chown(path, uid, gid)
}

func (HostSystem) Mkdir(path, owner, group string, mode fs.FileMode) error {
	if err := os.Mkdir(path, mode); err != nil && !errors.Is(err, fs.ErrExist) {
		return err
	}
	if err := chownTo(path, owner, group); err != nil {
		return err
	}
	return os.Chmod(path, 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.Open(src)
	if err != nil {
		return err
	}
	defer f.Close()
	return h.put(dst, f, owner, group, mode)
}

func (HostSystem) put(path string, r io.Reader, owner, group string, mode fs.FileMode) error {
	tmp := path + ".new"
	f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
	if err != nil {
		return err
	}
	_, err = io.Copy(f, r)
	if cerr := f.Close(); err == nil {
		err = cerr
	}
	if err == nil {
		err = chownTo(tmp, owner, group)
	}
	if err == nil {
		err = os.Chmod(tmp, mode)
	}
	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) { return os.ReadFile(path) }

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.Stat(path)
	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
}