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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package guestseed
import (
"encoding/json"
"fmt"
"regexp"
"runtime"
"slices"
"sort"
"strings"
"github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/cloudinit"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/selfexe"
)
const (
GuestBinariesUnit = cloudinit.GuestBinariesUnit
GuestBinariesScript = "/usr/local/bin/setup-guest-binaries.sh"
GuestBinariesDir = "/usr/local/bin"
GuestBinaryOpenTunnel = "opentunnel"
GuestBinaryAgent = "socialweb-guest-agent"
GuestBinaryWootty = "wootty"
GuestBinaryAtirc = "atirc"
GuestBinarySocialwebComputer = "socialweb-computer"
GuestAgentUnit = "socialweb-guest-agent.service"
GuestSecretsUnit = cloudinit.GuestSecretsUnit
GuestAgentBinary = GuestBinariesDir + "/" + GuestBinaryAgent
GuestAgentBidderPath = cloudinit.GuestAgentConfigDir + "/bidder.json"
GuestDownloadsRoute = "/v1/downloads"
guestBinaryAttempts = 60
guestBinaryGone = 2
)
var (
GuestArches = []string{"x86_64", "aarch64"}
GuestTools = []string{GuestBinarySocialwebComputer}
sha256HexRE = regexp.MustCompile(`^[0-9a-f]{64}$`)
guestBinaryNameRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
unitNameRE = regexp.MustCompile(`^[A-Za-z0-9@._-]+\.service$`)
)
type GuestBinaryPin struct {
Name string
Arch string
Sha256 string
}
type GuestBinaryNeeds struct {
OpenTunnel bool
Agent bool
Wootty bool
Atirc bool
Tools []string
Secrets bool
WebRTC bool
Units []string
}
type WebRTCOptions struct {
UDPPort int `json:"udpPort"`
HostAddresses []string `json:"hostAddresses"`
}
type guestAgentBidder struct {
Base string `json:"base"`
Audience string `json:"audience"`
AcceptPath string `json:"acceptPath"`
WebRTC *WebRTCOptions `json:"webrtc,omitempty"`
}
func GuestDownloadName(name, arch string) string {
return name + "-" + arch
}
type SelfDownload struct {
Name string
Path string
selfexe.Pin
}
func SelfDownloadOf() (SelfDownload, error) {
if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
return SelfDownload{}, fmt.Errorf("guestseed: the bidder runs %s/%s; it serves %s to linux/amd64 guests only", runtime.GOOS, runtime.GOARCH, GuestBinarySocialwebComputer)
}
pin, err := selfexe.Sum()
if err != nil {
return SelfDownload{}, err
}
return SelfDownload{Name: GuestDownloadName(GuestBinarySocialwebComputer, "x86_64"), Path: selfexe.Path, Pin: pin}, nil
}
func (n GuestBinaryNeeds) ToolsErr() error {
for _, tool := range n.Tools {
if !slices.Contains(GuestTools, tool) {
return fmt.Errorf("guestseed: the guest asks for guest tool %q; a bidder serves only %s", tool, strings.Join(GuestTools, ", "))
}
}
return nil
}
func (n GuestBinaryNeeds) Any() bool {
return n.OpenTunnel || n.Agent || n.Wootty || n.Atirc || len(n.Tools) > 0
}
func (n GuestBinaryNeeds) Names() []string {
var out []string
if n.OpenTunnel {
out = append(out, GuestBinaryOpenTunnel)
}
if n.Wootty {
out = append(out, GuestBinaryWootty)
}
if n.Atirc {
out = append(out, GuestBinaryAtirc)
}
if n.Agent {
out = append(out, GuestBinaryAgent)
}
for _, tool := range n.Tools {
if !slices.Contains(out, tool) {
out = append(out, tool)
}
}
return out
}
func GuestBinariesNeeded(userData string) GuestBinaryNeeds {
const unitDir = "/etc/systemd/system/"
out := GuestBinaryNeeds{}
for _, p := range cloudinit.WriteFilePaths(userData) {
if tool, ok := cloudinit.GuestToolOf(p); ok {
out.Tools = append(out.Tools, tool)
continue
}
switch {
case p == cloudinit.GuestAgentTunnelsPath:
out.Agent = true
out.WebRTC = true
case p == cloudinit.GuestAgentSecretsPath:
out.Agent = true
out.Secrets = true
case p == cloudinit.GuestAgentAgentPath:
out.Agent = true
out.Atirc = true
out.Units = append(out.Units, cloudinit.AgentUnit)
case p == cloudinit.GuestAgentAssociationPath:
out.Agent = true
out.Units = append(out.Units, cloudinit.GuestRequesterUnit, cloudinit.GuestRequesterReleaseUnit)
case strings.HasPrefix(p, unitDir+"guest-tunnel-") && !strings.HasPrefix(p, unitDir+"guest-tunnel-report-") && strings.HasSuffix(p, ".service"):
out.OpenTunnel = true
out.Units = append(out.Units, strings.TrimPrefix(p, unitDir))
case strings.HasPrefix(p, unitDir+cloudinit.ShellUnitPrefix) && strings.HasSuffix(p, ".service"):
out.Wootty = true
out.Units = append(out.Units, strings.TrimPrefix(p, unitDir))
}
}
if out.Agent {
out.Units = append(out.Units, GuestAgentUnit)
}
if out.Secrets {
out.Units = append(out.Units, GuestSecretsUnit)
}
sort.Strings(out.Units)
sort.Strings(out.Tools)
out.Tools = slices.Compact(out.Tools)
return out
}
func GuestBinaryPins(downloads map[string]string, names []string) ([]GuestBinaryPin, error) {
var out []GuestBinaryPin
for _, name := range names {
found := false
for _, arch := range GuestArches {
sum, ok := downloads[GuestDownloadName(name, arch)]
if !ok {
continue
}
out = append(out, GuestBinaryPin{Name: name, Arch: arch, Sha256: sum})
found = true
}
if !found {
return nil, fmt.Errorf("guestseed: the bidder serves no %s download for any of %s", name, strings.Join(GuestArches, ", "))
}
}
return out, nil
}
func GuestBinariesModule(base string, pins []GuestBinaryPin, units []string) (cloudinit.UserDataModule, error) {
base = strings.TrimRight(strings.TrimSpace(base), "/")
if err := checkURLLike(base, "guest downloads base"); err != nil {
return nil, err
}
if len(pins) == 0 {
return nil, fmt.Errorf("guestseed: the guest binaries module names no binary")
}
var wants strings.Builder
for _, pin := range pins {
if !guestBinaryNameRE.MatchString(pin.Name) {
return nil, fmt.Errorf("guestseed: guest binary name %q is not a file name", pin.Name)
}
if !slices.Contains(GuestArches, pin.Arch) {
return nil, fmt.Errorf("guestseed: guest binary %s arch %q is not an arch", pin.Name, pin.Arch)
}
if !sha256HexRE.MatchString(pin.Sha256) {
return nil, fmt.Errorf("guestseed: guest binary %s-%s sha256 %q is not 64 lowercase hex characters", pin.Name, pin.Arch, pin.Sha256)
}
fmt.Fprintf(&wants, "want %s %s %s\n", pin.Name, pin.Arch, pin.Sha256)
}
var needs []string
for _, pin := range pins {
if !slices.Contains(needs, pin.Name) {
needs = append(needs, pin.Name)
fmt.Fprintf(&wants, "need %s\n", pin.Name)
}
}
for _, unit := range units {
if !unitNameRE.MatchString(unit) {
return nil, fmt.Errorf("guestseed: %q is not a systemd service name", unit)
}
}
script := `#!/usr/bin/env bash
set -uo pipefail
BASE="` + base + `"
case "$(uname -m)" in
x86_64|amd64) ARCH=x86_64 ;;
aarch64|arm64) ARCH=aarch64 ;;
*) echo "setup-guest-binaries: the bidder serves no binaries for $(uname -m); giving up for good"; exit ` + fmt.Sprint(guestBinaryGone) + ` ;;
esac
FAIL=0
GONE=0
HAVE=" "
fetch() {
local name="$1" sum="$2" dest="` + GuestBinariesDir + `/$1" tmp got code rc all404=1
if [ -x "${dest}" ] && [ "$(sha256sum "${dest}" | cut -d' ' -f1)" = "${sum}" ]; then
echo "setup-guest-binaries: installed ${name} sha256 ${sum}"
return 0
fi
tmp="$(mktemp "` + GuestBinariesDir + `/.${name}.XXXXXX")" || return 1
for attempt in $(seq 1 ` + fmt.Sprint(guestBinaryAttempts) + `); do
code="$(curl -q -fsS --noproxy '*' --connect-timeout 10 -m 300 -o "${tmp}" -w '%{http_code}' "${BASE}` + GuestDownloadsRoute + `/${sum}/${name}-${ARCH}")"
rc=$?
if [ "${rc}" = 0 ]; then
all404=0
got="$(sha256sum "${tmp}" | cut -d' ' -f1)"
if [ "${got}" = "${sum}" ]; then
chmod 0755 "${tmp}" && mv -f "${tmp}" "${dest}"
echo "setup-guest-binaries: installed ${name} sha256 ${got}"
return 0
fi
echo "setup-guest-binaries: ${name} from ${BASE} has sha256 ${got}, not ${sum} (attempt ${attempt})"
else
[ "${code}" = 404 ] || all404=0
echo "setup-guest-binaries: fetching ${name} from ${BASE} failed: curl exit ${rc}, http ${code:-none} (attempt ${attempt})"
fi
sleep 3
done
rm -f "${tmp}"
if [ "${all404}" = 1 ]; then
echo "setup-guest-binaries: the bidder no longer serves ${name} sha256 ${sum} (HTTP 404 on every attempt: its download set changed since this guest was provisioned, e.g. a bidder upgrade); giving up for good"
return ` + fmt.Sprint(guestBinaryGone) + `
fi
echo "setup-guest-binaries: gave up on ${name}; the unit retries"
return 1
}
want() {
[ "$2" = "${ARCH}" ] || return 0
HAVE="${HAVE}$1 "
fetch "$1" "$3"
case "$?" in
0) ;;
` + fmt.Sprint(guestBinaryGone) + `) GONE=1 ;;
*) FAIL=1 ;;
esac
}
need() {
case "${HAVE}" in *" $1 "*) return 0 ;; esac
echo "setup-guest-binaries: the bidder serves no ${1} for ${ARCH}; giving up on it for good"
GONE=1
}
` + wants.String() + `[ "${FAIL}" = 0 ] || exit 1
[ "${GONE}" = 0 ] || exit ` + fmt.Sprint(guestBinaryGone) + `
exit 0
`
unit := []string{
"[Unit]",
"Description=Install the guest binaries the bidder serves",
"After=network-online.target",
"Wants=network-online.target",
}
if len(units) > 0 {
unit = append(unit, "Before="+strings.Join(units, " "))
}
unit = append(unit,
"StartLimitIntervalSec=0",
"",
"[Service]",
"Type=oneshot",
"RemainAfterExit=yes",
"TimeoutStartSec=0",
"ExecStart="+GuestBinariesScript,
"Restart=on-failure",
"RestartSec=10",
"RestartPreventExitStatus="+fmt.Sprint(guestBinaryGone),
"StandardOutput=journal+console",
"StandardError=journal+console",
"",
"[Install]",
"WantedBy=multi-user.target",
"",
)
content := strings.Join(unit, "\n")
return func(cloudinit.Context) (cloudinit.UserDataPatch, error) {
return cloudinit.UserDataPatch{
WriteFiles: []cloudinit.WriteFileEntry{
{Path: GuestBinariesScript, Owner: "root:root", Permissions: "0700", Content: script},
{Path: "/etc/systemd/system/" + GuestBinariesUnit, Owner: "root:root", Permissions: "0644", Content: content},
},
RuncmdPrepend: []any{
"systemctl daemon-reload",
"systemctl enable --no-block " + GuestBinariesUnit,
"systemctl start --no-block " + GuestBinariesUnit,
},
}, nil
}, nil
}
func GuestAgentModule(base, audience, acceptPath string, secrets bool, webrtc *WebRTCOptions) (cloudinit.UserDataModule, error) {
base = strings.TrimRight(strings.TrimSpace(base), "/")
if err := checkURLLike(base, "guest agent base"); err != nil {
return nil, err
}
if err := checkAbsolute(acceptPath); err != nil {
return nil, err
}
if webrtc != nil && (webrtc.UDPPort < 1 || webrtc.UDPPort > 65535 || len(webrtc.HostAddresses) == 0) {
return nil, fmt.Errorf("guestseed: the guest agent webrtc port %d with %d host addresses is not a forwarded LAN port", webrtc.UDPPort, len(webrtc.HostAddresses))
}
raw, err := json.Marshal(guestAgentBidder{Base: base, Audience: audience, AcceptPath: acceptPath, WebRTC: webrtc})
if err != nil {
return nil, fmt.Errorf("guestseed: encoding %s: %w", GuestAgentBidderPath, err)
}
unit := strings.Join([]string{
"[Unit]",
"Description=socialweb guest agent: the webrtc tunnels, the sealed secrets fallback, the agent start and the requester association of the guest",
"After=network-online.target " + GuestBinariesUnit,
"Wants=network-online.target",
"Requires=" + GuestBinariesUnit,
"ConditionPathExists=|" + cloudinit.GuestAgentTunnelsPath,
"ConditionPathExists=|" + cloudinit.GuestAgentSecretsPath,
"ConditionPathExists=|" + cloudinit.GuestAgentAgentPath,
"ConditionPathExists=|" + cloudinit.GuestAgentAssociationPath,
"StartLimitIntervalSec=0",
"",
"[Service]",
"Type=simple",
"ExecStart=" + GuestAgentBinary,
"Restart=always",
"RestartSec=2",
"StandardOutput=journal+console",
"StandardError=journal+console",
"",
"[Install]",
"WantedBy=multi-user.target",
"",
}, "\n")
files := []cloudinit.WriteFileEntry{
{Path: GuestAgentBidderPath, Owner: "root:root", Permissions: "0644", Content: string(raw) + "\n"},
{Path: "/etc/systemd/system/" + GuestAgentUnit, Owner: "root:root", Permissions: "0644", Content: unit},
}
runcmd := []any{
"systemctl daemon-reload",
"systemctl enable --no-block " + GuestAgentUnit,
"systemctl start --no-block " + GuestAgentUnit,
}
if secrets {
files = append(files, cloudinit.WriteFileEntry{Path: "/etc/systemd/system/" + GuestSecretsUnit, Owner: "root:root", Permissions: "0644", Content: guestSecretsUnit})
runcmd = append(runcmd, "systemctl enable --no-block "+GuestSecretsUnit, "systemctl start --no-block "+GuestSecretsUnit)
}
return func(cloudinit.Context) (cloudinit.UserDataPatch, error) {
return cloudinit.UserDataPatch{WriteFiles: files, RuncmdPrepend: runcmd}, nil
}, nil
}
var guestSecretsUnit = strings.Join([]string{
"[Unit]",
"Description=socialweb guest secrets: wait until the bundle is written, by setup-secrets.service (getSecrets) or by the guest agent (the sealed fallback)",
"After=" + GuestBinariesUnit,
"Requires=" + GuestBinariesUnit,
"ConditionPathExists=" + cloudinit.GuestAgentSecretsPath,
"",
"[Service]",
"Type=oneshot",
"RemainAfterExit=yes",
"TimeoutStartSec=infinity",
"ExecStart=" + GuestAgentBinary + " wait-secrets",
"StandardOutput=journal+console",
"StandardError=journal+console",
"",
"[Install]",
"WantedBy=multi-user.target",
"",
}, "\n")