aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/state/data.go
blob: 454938856ae41545b2800badfb7bf254c7ed2c09 (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
package state

import (
	"encoding/gob"
	"os"
	"path"

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

// we unfortunately have to assume there are never races between processes
// this and launcher should eventually be replaced by a server process

type launcherState struct {
	PID        int
	Launcher   string
	Argv       []string
	Command    []string
	Capability internal.Enablements
}

// ReadLaunchers reads all launcher state file entries for the requested user
// and if decode is true decodes these launchers as well.
func ReadLaunchers(runDirPath, uid string, decode bool) ([]*launcherState, error) {
	var f *os.File
	var r []*launcherState
	launcherPrefix := path.Join(runDirPath, uid)

	if pl, err := os.ReadDir(launcherPrefix); err != nil {
		return nil, err
	} else {
		for _, e := range pl {
			if err = func() error {
				if f, err = os.Open(path.Join(launcherPrefix, e.Name())); err != nil {
					return err
				} else {
					defer func() {
						if f.Close() != nil {
							// unreachable
							panic("foreign state file closed prematurely")
						}
					}()

					var s launcherState
					r = append(r, &s)
					if decode {
						return gob.NewDecoder(f).Decode(&s)
					} else {
						return nil
					}
				}
			}(); err != nil {
				return nil, err
			}
		}
	}

	return r, nil
}