summaryrefslogtreecommitdiff
path: root/config.go
blob: 7160c19f50e5d7ede6be05120471cc1032f5aa62 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main

import (
	"context"
	"os"
	"os/signal"
	"os/user"
	"strconv"
	"strings"
	"syscall"

	"tildegit.org/tjp/sliderule/logging"
)

type config struct {
	hostname string

	geminiRoot string
	gopherRoot string

	geminiRepos string
	gopherRepos string

	tlsKeyFile  string
	tlsCertFile string

	privilegedUsers []string

	fingerResponses map[string]string

	geminiAutoAtom bool
}

func configure() config {
	privileged := strings.Split(os.Getenv("PRIVILEGED_FINGERPRINTS"), ",")

	fingers := map[string]string{}
	for _, pair := range os.Environ() {
		key, val, _ := strings.Cut(pair, "=")
		if !strings.HasPrefix(key, "FINGER_") {
			continue
		}
		fingers[strings.ToLower(key[7:])] = val
	}

	autoatom, err := strconv.ParseBool(os.Getenv("GEMINI_AUTOATOM"))
	if err != nil {
		autoatom = false
	}

	return config{
		hostname:    os.Getenv("HOST_NAME"),
		geminiRoot:  os.Getenv("GEMINI_ROOT"),
		gopherRoot:  os.Getenv("GOPHER_ROOT"),
		geminiRepos: os.Getenv("GEMINI_REPOS"),
		gopherRepos: os.Getenv("GOPHER_REPOS"),
		tlsKeyFile:  os.Getenv("TLS_KEY_FILE"),
		tlsCertFile: os.Getenv("TLS_CERT_FILE"),

		privilegedUsers: privileged,

		fingerResponses: fingers,

		geminiAutoAtom: autoatom,
	}
}

func dropPrivileges() (bool, error) {
	me, err := user.Current()
	if err != nil {
		return false, err
	}

	if me.Uid != "0" {
		return false, nil
	}

	nobody, err := user.Lookup("nobody")
	if err != nil {
		return false, err
	}
	uid, err := strconv.Atoi(nobody.Uid)
	if err != nil {
		return false, err
	}

	if err := syscall.Setuid(uid); err != nil {
		return false, err
	}
	return true, nil
}

func serverContext() (context.Context, logging.Logger, logging.Logger, logging.Logger, logging.Logger) {
	debug, info, warn, err := logging.DefaultLoggers()
	ctx, _ := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGHUP)
	ctx = context.WithValue(ctx, "debuglog", debug) //nolint:staticcheck
	ctx = context.WithValue(ctx, "infolog", info)   //nolint:staticcheck
	ctx = context.WithValue(ctx, "warnlog", warn)   //nolint:staticcheck
	ctx = context.WithValue(ctx, "errorlog", err)   //nolint:staticcheck

	return ctx, debug, info, warn, err
}