aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/app/setup.go
blob: 82765dfb8e115c06ef9dffc7170165e9a9e74ca8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package app

import (
	"errors"
	"fmt"
	"os"
	"os/user"
	"strconv"

	"git.ophivana.moe/cat/fortify/internal/state"
	"git.ophivana.moe/cat/fortify/internal/system"
)

type App struct {
	uid     int
	env     []string
	command []string

	enablements state.Enablements
	*user.User

	// absolutely *no* method of this type is thread-safe
	// so don't treat it as if it is
}

func (a *App) setEnablement(e state.Enablement) {
	if a.enablements.Has(e) {
		panic("enablement " + e.String() + " set twice")
	}

	a.enablements |= e.Mask()
}

func New(userName string, args []string) *App {
	a := &App{command: args}

	if u, err := user.Lookup(userName); err != nil {
		if errors.As(err, new(user.UnknownUserError)) {
			fmt.Println("unknown user", userName)
		} else {
			// unreachable
			panic(err)
		}

		// too early for fatal
		os.Exit(1)
	} else {
		a.User = u
	}

	if u, err := strconv.Atoi(a.Uid); err != nil {
		// usually unreachable
		panic("uid parse")
	} else {
		a.uid = u
	}

	if system.V.Verbose {
		fmt.Println("Running as user", a.Username, "("+a.Uid+"),", "command:", a.command)
	}

	return a
}