oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package fprobe
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "crypto/sha256"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "io/fs"
14 "net"
15 "os"
16 "path/filepath"
17 "strings"
18 "sync"
19 "sync/atomic"
20 "syscall"
21 "time"
22
23 "amadan.net/oficina/equipo/internal/runner/mac"
24 "amadan.net/oficina/equipo/internal/runner/mac/proc"
25 "amadan.net/oficina/equipo/internal/wire"
26)
27
28// Host is what the probes reach on the Mac. Every effect goes through it,
29// so the probes run on Linux against fakes and recorded outputs.
30type Host struct {
31 // Inputs are the inputs now (NewInputs), recorded with each result.
32 Inputs Inputs
33 // Paths are the §4.2 places; RuntimeRoot holds the connections'
34 // runtime copies; TokenFiles are where each Claude connection keeps
35 // its token (F3 reads them by path, F6 natively).
36 Paths mac.Paths
37 RuntimeRoot string
38 TokenFiles []string
39 // Tools are Xcode's (F5, F7); Simulators the capability report's.
40 Tools mac.Tools
41 Simulators []wire.Simulator
42 // Scratch is where probe trees are made (outside every denied place).
43 Scratch string
44 // P2Denied: this process's trusted P2 is denied (F5 runs only then).
45 P2Denied bool
46 // Secrets are the forms of every secret the runner knows (each
47 // connection's token, raw, hex and base64): F3 searches for them.
48 Secrets func(context.Context) ([][]byte, error)
49 // Turns is the Mac's turns: a probe run is one OpProbe turn, its
50 // launches inside it. nil takes none (tests).
51 Turns *mac.Turns
52 // Launch runs one probe launch of the pinned CLI with s's settings,
53 // worktree, prompt and limit, and returns once its end is known; ask
54 // hears each permission request the runner's tool answered, with its
55 // answer, before the CLI acts on it.
56 Launch func(ctx context.Context, s Spec, obs Observer) Outcome
57 // Live is the inputs now, read afresh (nil: Inputs); Runner is the
58 // runner's binary (its __fprobe helper); ProcArgs reads a process's
59 // KERN_PROCARGS2 outside the sandbox (nil: ProcArgs); Alive tells
60 // whether a process is still running, and whether that is known.
61 Live func(context.Context) (Inputs, []wire.Simulator)
62 Runner string
63 ProcArgs func(pid int) ([]byte, error)
64 Alive func(proc.ID) (alive, known bool)
65 // Listen opens a loopback port whose accepts are ground truth;
66 // Resolve looks a name up outside the sandbox; Exposed is P4's (the
67 // runner user can list a home by Unix permissions); Exec runs a
68 // command outside the sandbox (F7's control, F5's Keychain item);
69 // Lookup reads a process of the runner user (F4).
70 Listen func() (net.Listener, error)
71 Resolve func(ctx context.Context, name string) bool
72 Exposed func(home string) bool
73 Exec mac.Exec
74 Lookup func(pid int) (proc.Info, bool)
75 // Now is the clock (nil: time.Now).
76 Now func() time.Time
77 // Limits bound each launch (nil: the defaults).
78 Limits map[string]time.Duration
79}
80
81// limits are each launch's bound: A makes about a hundred tool calls, B
82// builds and tests P2's fixture (P2's own bound is 20 minutes), C waits
83// only for its child to start.
84var limits = map[string]time.Duration{LaunchA: 20 * time.Minute, LaunchB: 25 * time.Minute, LaunchC: 5 * time.Minute}
85
86func (h Host) limit(l string) time.Duration {
87 if d, ok := h.Limits[l]; ok {
88 return d
89 }
90 return limits[l]
91}
92
93func (h Host) now() time.Time {
94 if h.Now != nil {
95 return h.Now()
96 }
97 return time.Now()
98}
99
100// live is the inputs read now.
101func (h Host) live(ctx context.Context) Inputs {
102 in, _ := h.fresh(ctx)
103 return in
104}
105
106// fresh is the inputs and the simulators read now, together (#7: a
107// launch runs on the simulators its inputs name).
108func (h Host) fresh(ctx context.Context) (Inputs, []wire.Simulator) {
109 if h.Live != nil {
110 return h.Live(ctx)
111 }
112 return h.Inputs, h.Simulators
113}
114
115// procArgs reads pid's KERN_PROCARGS2 outside the sandbox.
116func (h Host) procArgs(pid int) ([]byte, error) {
117 if h.ProcArgs != nil {
118 return h.ProcArgs(pid)
119 }
120 return ProcArgs(pid)
121}
122
123// Spec is one probe launch. Protected execution evidence (the
124// controller's ruling, fix round 1): the model is the actor, so nothing
125// it can write or say counts. The one Bash command the launch's
126// permission tool allows is Command, the runner's script with this run's
127// nonce, and only while the script's bytes hash to ScriptSHA256. The
128// script lies in a directory outside the worktree and the scratch, which
129// no sandboxed command and no native write can reach; it records into
130// the launch's scratch, which native writes cannot reach and only the
131// script's Bash writes.
132type Spec struct {
133 Launch string
134 // Xcode: the sandboxed-Xcode settings (launch B); else no Xcode.
135 Xcode bool
136 // Tree is the probe tree, the launch's worktree (a real path).
137 Tree string
138 // Scratch is the launch's scratch (TMPDIR), where only the script
139 // writes; Script the probe script, ScriptSHA256 its digest, Nonce this
140 // run's argument (Command).
141 Scratch, Script, ScriptSHA256, Nonce string
142 // Protected are directories the script runs (F5's fixture) or reads,
143 // beside it; ProtectedSHA256 is the digest of every file in them.
144 Protected []string
145 ProtectedSHA256 string
146 // Prompt asks the model to run Command (and in A to make the native
147 // tool calls); Limit bounds the launch.
148 Prompt string
149 Limit time.Duration
150}
151
152// Command is the one Bash command a probe launch may run.
153func (s Spec) Command() string { return "bash " + s.Script + " " + s.Nonce }
154
155// Permit is whether the probe launch's permission tool may allow a
156// request its Engineering rules allow: Bash only as Command, with the
157// script unchanged; a native write only inside the tree.
158func (s Spec) Permit(tool string, input json.RawMessage) bool {
159 var in struct {
160 Command string `json:"command"`
161 FilePath string `json:"file_path"`
162 NotebookPath string `json:"notebook_path"`
163 }
164 if json.Unmarshal(input, &in) != nil {
165 return false
166 }
167 switch tool {
168 case "Bash":
169 if in.Command != s.Command() || s.Script == "" {
170 return false
171 }
172 b, ok := readFile(s.Script, 1<<20)
173 sum := sha256.Sum256(b)
174 // Every protected input too, as it is now, just before the run.
175 tree, err := treeDigest(s.Protected)
176 return ok && hex.EncodeToString(sum[:]) == s.ScriptSHA256 && (len(s.Protected) == 0 || err == nil && tree == s.ProtectedSHA256)
177 case "Write", "Edit", "MultiEdit", "NotebookEdit":
178 p := filepath.Clean(firstNonEmpty(in.FilePath, in.NotebookPath))
179 return s.Tree != "" && strings.HasPrefix(p, s.Tree+"/")
180 }
181 return true
182}
183
184// Observer is what the runner sees of a probe launch while it runs.
185type Observer struct {
186 // Ask hears each answer of the runner's permission tool, before the
187 // CLI acts on it.
188 Ask func(Ask)
189 // Started is the CLI's process once its group is on record.
190 Started func(pid int)
191 // Copy is the connection's runtime copy, before the CLI starts.
192 Copy func(dir string) error
193 // Event is each frame of the CLI's stream.
194 Event func(frame []byte)
195}
196
197// Ask is one permission request the runner's tool answered.
198type Ask struct {
199 Tool string
200 ToolUseID string
201 Input json.RawMessage
202 Allowed bool
203}
204
205// path is the file or directory a native tool's request names.
206func (a Ask) path() string { return inputPath(a.Input) }
207
208func inputPath(raw json.RawMessage) string {
209 var in struct {
210 FilePath string `json:"file_path"`
211 Path string `json:"path"`
212 }
213 _ = json.Unmarshal(raw, &in)
214 return filepath.Clean(firstNonEmpty(in.FilePath, in.Path))
215}
216
217// Outcome is how a probe launch ended: whether the CLI started, whether
218// its end (and its descendants') is proven, and why it did not start or
219// finish ("" when it finished).
220type Outcome struct {
221 Started, Proven bool
222 Reason string
223}
224
225// Run runs the launches due now (Due) in one OpProbe turn, keeping each
226// result, and returns them. Each launch's inputs are read afresh before
227// it and again after it: a launch they changed under is undecided. A
228// launch the turn could not be taken for, or that could not start, is
229// undecided too: tried again after Retry.
230func (s *Store) Run(ctx context.Context, h Host) []Result {
231 h.Inputs = h.live(ctx)
232 due := s.Due(h.Inputs, h.now(), h.P2Denied)
233 if len(due) == 0 {
234 return nil
235 }
236 var out []Result
237 ctx, give, err := h.Turns.Hold(ctx, mac.OpProbe)
238 if err != nil {
239 for _, l := range due {
240 s.try(l, h.Inputs, h.now())
241 out = append(out, undecided(l, h, wire.ProbeDetailTurnBusy))
242 }
243 return out
244 }
245 defer give()
246 for _, l := range due {
247 h.Inputs, h.Simulators = h.fresh(ctx)
248 at := h.now()
249 s.try(l, h.Inputs, at)
250 var probes []wire.Probe
251 switch l {
252 case LaunchA:
253 probes = launchA(ctx, h)
254 case LaunchB:
255 probes = launchB(ctx, h)
256 case LaunchC:
257 probes = launchC(ctx, h)
258 }
259 r := Result{Launch: l, Inputs: h.Inputs, At: at, Probes: probes}
260 if h.live(context.WithoutCancel(ctx)).changed(h.Inputs) != "" {
261 r.Probes = undecided(l, h, "inputs_changed").Probes
262 }
263 s.Put(r)
264 out = append(out, r)
265 if ctx.Err() != nil {
266 break
267 }
268 }
269 return out
270}
271
272// undecided is launch l's probes, each unavailable for why.
273func undecided(l string, h Host, why string) Result {
274 r := Result{Launch: l, Inputs: h.Inputs, At: h.now()}
275 for _, id := range launchProbes[l] {
276 r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.ProbeUnavailable, Detail: why})
277 }
278 return r
279}
280
281// all is every probe of launch l with one verdict and detail.
282func all(l, verdict, detail string) []wire.Probe {
283 var out []wire.Probe
284 for _, id := range launchProbes[l] {
285 out = append(out, wire.Probe{ID: id, Verdict: verdict, Detail: detail})
286 }
287 return out
288}
289
290// reasonCode is a launch's reason as a detail parameter: a code, never
291// words ("unknown" otherwise).
292func reasonCode(r string) string {
293 if r == "" || len(r) > 40 || strings.Trim(r, "abcdefghijklmnopqrstuvwxyz0123456789_") != "" {
294 return "unknown"
295 }
296 return r
297}
298
299// launched is what a launch's outcome says for its probes before any
300// observation: unavailable when the CLI never started, failed when its
301// end is not proven (nothing it did can be trusted), nil to go on.
302func launched(l string, o Outcome) []wire.Probe {
303 switch {
304 case !o.Started:
305 return all(l, wire.ProbeUnavailable, wire.ProbeDetail("launch_not_started", reasonCode(o.Reason)))
306 case !o.Proven:
307 return all(l, wire.ProbeFailed, wire.ProbeDetail("launch_unproven"))
308 }
309 return nil
310}
311
312// launchDir is one launch's places, all fresh and the runner's: the tree
313// (the worktree), run (the scratch, where only the script writes) and bin
314// (the script and the runner's lists for it, which nothing in the launch
315// can write).
316type launchDir struct {
317 root, run, bin string
318 t *tree
319}
320
321func newLaunchDir(scratch string) (*launchDir, error) {
322 if err := os.MkdirAll(scratch, 0o700); err != nil {
323 return nil, err
324 }
325 dir, err := os.MkdirTemp(scratch, "fprobe-")
326 if err != nil {
327 return nil, err
328 }
329 root, err := filepath.EvalSymlinks(dir)
330 if err != nil {
331 os.RemoveAll(dir)
332 return nil, err
333 }
334 d := &launchDir{root: root, run: filepath.Join(root, "run"), bin: filepath.Join(root, "bin"), t: &tree{root: filepath.Join(root, "tree"), planted: map[string][]byte{}}}
335 for _, p := range []string{d.t.root, d.run, d.bin} {
336 if err := os.Mkdir(p, 0o700); err != nil {
337 d.remove()
338 return nil, err
339 }
340 }
341 return d, nil
342}
343
344// remove deletes the launch's places whole (nothing is kept).
345func (d *launchDir) remove() { os.RemoveAll(d.root) }
346
347// spec is the launch's Spec with its script written (0500, in bin).
348func (d *launchDir) spec(l, script string, xcode bool) (Spec, error) {
349 path := filepath.Join(d.bin, "probe-"+strings.ToLower(l)+".sh")
350 if err := os.WriteFile(path, []byte(script), 0o500); err != nil {
351 return Spec{}, err
352 }
353 sum := sha256.Sum256([]byte(script))
354 return Spec{Launch: l, Xcode: xcode, Tree: d.t.root, Scratch: d.run, Script: path, ScriptSHA256: hex.EncodeToString(sum[:]), Nonce: nonce()}, nil
355}
356
357// protect makes dir (inside bin) one of the spec's protected inputs and
358// records the digest of every file in them.
359func (d *launchDir) protect(s *Spec, dir string) error {
360 if !strings.HasPrefix(dir, d.bin+"/") {
361 return errors.New("fprobe: a protected input outside bin")
362 }
363 s.Protected = append(s.Protected, dir)
364 sum, err := treeDigest(s.Protected)
365 s.ProtectedSHA256 = sum
366 return err
367}
368
369// treeDigest is the digest of every entry under dirs: each path, kind,
370// mode and content (a link's target), in order.
371func treeDigest(dirs []string) (string, error) {
372 h := sha256.New()
373 for _, dir := range dirs {
374 err := filepath.WalkDir(dir, func(p string, e fs.DirEntry, err error) error {
375 if err != nil {
376 return err
377 }
378 info, err := os.Lstat(p)
379 if err != nil {
380 return err
381 }
382 fmt.Fprintf(h, "%s %v\n", p, info.Mode())
383 switch {
384 case info.Mode()&fs.ModeSymlink != 0:
385 t, err := os.Readlink(p)
386 if err != nil {
387 return err
388 }
389 h.Write([]byte(t))
390 case info.Mode().IsRegular():
391 b, err := os.ReadFile(p)
392 if err != nil {
393 return err
394 }
395 fmt.Fprintf(h, "%d\n", len(b))
396 h.Write(b)
397 }
398 return nil
399 })
400 if err != nil {
401 return "", err
402 }
403 }
404 return hex.EncodeToString(h.Sum(nil)), nil
405}
406
407// list writes one of the runner's lists for the script.
408func (d *launchDir) list(name string, lines []string) error {
409 body := strings.Join(lines, "\n")
410 if body != "" {
411 body += "\n"
412 }
413 return os.WriteFile(filepath.Join(d.bin, name), []byte(body), 0o600)
414}
415
416// read is what the script recorded under run/out.
417func (d *launchDir) read(name string) string {
418 b, _ := readFile(filepath.Join(d.run, "out", name), 1<<20)
419 return string(b)
420}
421
422// find searches the tree and the scratch (where[rel] = "tree" or
423// "scratch").
424func (d *launchDir) find(needles map[string][][]byte) (map[string][]string, bool) {
425 hits, whole := d.t.find(needles)
426 run := &tree{root: d.run, planted: map[string][]byte{}}
427 rh, rwhole := run.find(needles)
428 for k, files := range rh {
429 for _, f := range files {
430 hits[k] = append(hits[k], "scratch:"+f)
431 }
432 }
433 return hits, whole && rwhole
434}
435
436// where splits found files into the scratch's (the script's) and the
437// tree's, by base name.
438func where(files []string) (scratch, inTree []string) {
439 for _, f := range files {
440 if rest, ok := strings.CutPrefix(f, "scratch:"); ok {
441 scratch = append(scratch, filepath.Base(rest))
442 } else {
443 inTree = append(inTree, filepath.Base(f))
444 }
445 }
446 return scratch, inTree
447}
448
449// evidence is what the runner saw of a launch: its tool's answers, the
450// CLI's tool events, the CLI's pid.
451type evidence struct {
452 mu sync.Mutex
453 asks []Ask
454 uses []*toolUse
455 ids map[string]*toolUse
456 pid int
457}
458
459// toolUse is one tool call as the CLI's own stream reports it: its
460// tool_use, and its tool_result once that comes.
461type toolUse struct {
462 ID, Tool string
463 Input json.RawMessage
464 Done, Error bool
465 Text string
466}
467
468func (e *evidence) ask(q Ask) { e.mu.Lock(); e.asks = append(e.asks, q); e.mu.Unlock() }
469
470func (e *evidence) started(pid int) { e.mu.Lock(); e.pid = pid; e.mu.Unlock() }
471
472// event reads one frame of the CLI's stream: an assistant message's
473// tool_use blocks and a user message's tool_result blocks. Anything else
474// (model text among it) is not evidence and is ignored.
475func (e *evidence) event(frame []byte) {
476 var f struct {
477 Type string `json:"type"`
478 Message struct {
479 Content []struct {
480 Type string `json:"type"`
481 ID string `json:"id"`
482 Name string `json:"name"`
483 Input json.RawMessage `json:"input"`
484 ToolUseID string `json:"tool_use_id"`
485 IsError bool `json:"is_error"`
486 Content json.RawMessage `json:"content"`
487 } `json:"content"`
488 } `json:"message"`
489 }
490 if json.Unmarshal(frame, &f) != nil {
491 return
492 }
493 e.mu.Lock()
494 defer e.mu.Unlock()
495 if e.ids == nil {
496 e.ids = map[string]*toolUse{}
497 }
498 for _, c := range f.Message.Content {
499 switch {
500 case f.Type == "assistant" && c.Type == "tool_use" && c.ID != "":
501 u := &toolUse{ID: c.ID, Tool: c.Name, Input: c.Input}
502 e.uses = append(e.uses, u)
503 e.ids[c.ID] = u
504 case f.Type == "user" && c.Type == "tool_result" && e.ids[c.ToolUseID] != nil:
505 u := e.ids[c.ToolUseID]
506 u.Done, u.Error, u.Text = true, c.IsError, resultText(c.Content)
507 }
508 }
509}
510
511// resultText is a tool_result's content: a string, or its text blocks.
512func resultText(raw json.RawMessage) string {
513 var s string
514 if json.Unmarshal(raw, &s) == nil {
515 return s
516 }
517 var blocks []struct {
518 Text string `json:"text"`
519 }
520 _ = json.Unmarshal(raw, &blocks)
521 var b strings.Builder
522 for _, x := range blocks {
523 b.WriteString(x.Text)
524 }
525 return b.String()
526}
527
528func (e *evidence) observer() Observer {
529 return Observer{Ask: e.ask, Started: e.started, Event: e.event}
530}
531
532// judged is a launch's probes unless the evidence does not hold: the
533// runner's tool never allowed Command, it allowed some other Bash
534// command, or the scratch does not hold this run's begin and end. Then no
535// success verdict stands, and each failure says why first.
536func (e *evidence) judged(probes []wire.Probe, s Spec, d *launchDir) []wire.Probe {
537 return e.judgedEnd(probes, s, d, true)
538}
539
540// judgedEnd is judged; with end false the script's end is not required
541// (launch C is cancelled by design while its script waits).
542func (e *evidence) judgedEnd(probes []wire.Probe, s Spec, d *launchDir, end bool) []wire.Probe {
543 e.mu.Lock()
544 ran, other := false, false
545 for _, q := range e.asks {
546 var in struct {
547 Command string `json:"command"`
548 }
549 _ = json.Unmarshal(q.Input, &in)
550 if q.Tool == "Bash" && q.Allowed {
551 ran, other = ran || in.Command == s.Command(), other || in.Command != s.Command()
552 }
553 }
554 e.mu.Unlock()
555 switch {
556 case !ran:
557 return notRun(probes, wire.ProbeDetail("script_not_run"))
558 case other:
559 return notRun(probes, wire.ProbeDetail("other_command"))
560 case strings.TrimSpace(d.read("begin")) != "begin "+s.Nonce || end && strings.TrimSpace(d.read("end")) != "end "+s.Nonce:
561 return notRun(probes, wire.ProbeDetail("records_foreign"))
562 }
563 return probes
564}
565
566// notRun marks probes for why: no success verdict stands, and each
567// failure says why first.
568func notRun(probes []wire.Probe, why string) []wire.Probe {
569 for i, p := range probes {
570 switch p.Verdict {
571 case wire.EngineeringProbeSuccess(p.ID):
572 probes[i].Verdict, probes[i].Detail = wire.ProbeFailed, why
573 case wire.ProbeFailed:
574 probes[i].Detail = wire.ProbeDetails(why, p.Detail)
575 }
576 }
577 return probes
578}
579
580// tree is the launch's worktree. planted maps each path the runner put
581// there to what it wrote (nil for a link): a planted file that no longer
582// holds it is searched like any other.
583type tree struct {
584 root string
585 planted map[string][]byte
586}
587
588func (t *tree) path(rel string) string { return filepath.Join(t.root, rel) }
589
590// plant writes a file the runner owns in the tree.
591func (t *tree) plant(rel string, body []byte, mode os.FileMode) error {
592 p := t.path(rel)
593 if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
594 return err
595 }
596 t.planted[p] = body
597 return os.WriteFile(p, body, mode)
598}
599
600// mark notes a path the runner made some other way (a link).
601func (t *tree) mark(rel string) string { p := t.path(rel); t.planted[p] = nil; return p }
602
603func readFile(p string, max int64) ([]byte, bool) {
604 info, err := os.Lstat(p)
605 if err != nil || !info.Mode().IsRegular() {
606 return nil, false
607 }
608 f, err := os.OpenFile(p, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
609 if err != nil {
610 return nil, false
611 }
612 defer f.Close()
613 b, err := io.ReadAll(io.LimitReader(f, max+1))
614 return b, err == nil && int64(len(b)) <= max
615}
616
617// scanBound bounds what the search reads of a tree.
618const scanBound = 64 << 20
619
620// find searches every regular file the runner did not plant (links are
621// never followed) for each of needles, and returns, per needle, the
622// files (relative) holding it. whole is false when the tree held more
623// than the search reads or a file could not be read whole: nothing it
624// did not read may count as absent.
625func (t *tree) find(needles map[string][][]byte) (hits map[string][]string, whole bool) {
626 hits, whole = map[string][]string{}, true
627 var read int64
628 _ = filepath.WalkDir(t.root, func(p string, d fs.DirEntry, err error) error {
629 if err != nil {
630 whole = false
631 return nil
632 }
633 want, planted := t.planted[p]
634 if d.IsDir() || planted && want == nil || !d.Type().IsRegular() {
635 return nil
636 }
637 b, ok := readFile(p, scanBound-read)
638 read += int64(len(b))
639 if !ok {
640 whole = false
641 return nil
642 }
643 if planted && bytes.Equal(b, want) {
644 return nil
645 }
646 rel, _ := filepath.Rel(t.root, p)
647 for name, forms := range needles {
648 for _, f := range forms {
649 if len(f) > 0 && bytes.Contains(b, f) {
650 hits[name] = append(hits[name], rel)
651 break
652 }
653 }
654 }
655 return nil
656 })
657 return hits, whole
658}
659
660// records reads a script's record file: "name code" per line, the first
661// line for a name counting.
662func records(raw string) map[string]string {
663 out := map[string]string{}
664 for _, line := range strings.Split(raw, "\n") {
665 f := strings.Fields(line)
666 if len(f) == 2 {
667 if _, seen := out[f[0]]; !seen {
668 out[f[0]] = f[1]
669 }
670 }
671 }
672 return out
673}
674
675// listener is a loopback port that counts what reached it.
676type listener struct {
677 l net.Listener
678 hits atomic.Int64
679 wg sync.WaitGroup
680}
681
682func listen(h Host) (*listener, error) {
683 l, err := h.Listen()
684 if err != nil {
685 return nil, err
686 }
687 x := &listener{l: l}
688 x.wg.Add(1)
689 go func() {
690 defer x.wg.Done()
691 for {
692 c, err := l.Accept()
693 if err != nil {
694 return
695 }
696 x.hits.Add(1)
697 c.Close()
698 }
699 }()
700 return x, nil
701}
702
703func (x *listener) port() string {
704 _, p, _ := net.SplitHostPort(x.l.Addr().String())
705 return p
706}
707
708// close stops it and says how many connections it saw.
709func (x *listener) close() int64 {
710 x.l.Close()
711 x.wg.Wait()
712 return x.hits.Load()
713}
714
715// nonce is a fresh sentinel value: what no sandboxed command may read.
716func nonce() string {
717 b := make([]byte, 16)
718 _, _ = rand.Read(b)
719 return "EQUIPO-NONCE-" + hex.EncodeToString(b)
720}
721
722// tag is a short fresh name part.
723func tag() string { return strings.TrimPrefix(nonce(), "EQUIPO-NONCE-")[:12] }
724
725// quote is s as one shell word.
726func quote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }
727
728func firstNonEmpty(s ...string) string {
729 for _, x := range s {
730 if x != "" {
731 return x
732 }
733 }
734 return ""
735}
736