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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! Spawns `shep daemon` — this binary re-executed with its own hidden
//! `daemon` subcommand — detached from the parent's process group and
//! terminal, for `shep_client::spawn::connect_or_spawn`'s autostart path.
//!
//! No double-fork: `Command::process_group(0)` (stable since Rust 1.64 via
//! `std::os::unix::process::CommandExt`) plus redirected stdio is enough
//! for the daemon to survive the parent process exiting and its
//! controlling terminal closing, without any `unsafe` — and this crate is
//! `#![forbid(unsafe_code)]`.
//!
//! Redirecting stdio is not by itself enough to make the daemon *clean* of
//! its launcher, though: only fds 0/1/2 are replaced, and anything above
//! them that this process happens to hold without `FD_CLOEXEC` survives the
//! `exec` and is then held for the daemon's whole life. [`seal_inherited_fds`]
//! is what closes that, and its own doc carries the bug it was written for.
use File;
use io;
use DirBuilderExt as _;
use RawFd;
use CommandExt as _;
use Path;
use ;
use ;
use ShepPaths;
/// The shepherd's own stdout, inside `$SHEP_HOME/logs/`.
///
/// One owner for the name: this module creates the file and
/// `commands::logs`' `--daemon` flush empties it, and a copy that drifted
/// would leave `shep flush --daemon` truncating a file nothing writes to
/// while the real one grew.
pub const DAEMON_STDOUT_LOG: &str = "shepd.out.log";
/// The shepherd's own stderr — where its `tracing` records land. See
/// [`DAEMON_STDOUT_LOG`] for why the name lives here.
pub const DAEMON_STDERR_LOG: &str = "shepd.err.log";
/// Builds the fully configured `shep daemon` command — log directory
/// created, both log files opened — but does not spawn it.
///
/// Creating `paths.logs` here, before opening the two files below inside
/// it, duplicates one directory of `shep_daemon::boot::init_dirs` on
/// purpose: that function is authoritative and idempotent and still runs,
/// but only *after* `exec`, inside the child. On a cold `$SHEP_HOME`
/// nothing has created `paths.logs` yet at the point this function needs to
/// open files inside it, so without this the redirect below fails with
/// `ENOENT` and the daemon never starts. Do not remove it as
/// "redundant" — that is the exact failure this exists to prevent.
///
/// The `.mode(shep_daemon::boot::DIR_MODE)` below sets the directory's mode
/// at creation, via `DirBuilderExt`, rather than `create_dir_all` followed
/// by a separate `set_permissions` — matching
/// `shep_daemon::boot::create_dir_at_dir_mode`'s own TOCTOU discipline. A
/// create-then-chmod sequence leaves a window in which the directory exists
/// at whatever the ambient umask allows before the chmod narrows it; on a
/// shared machine that window is enough for another user to open a handle
/// that survives the later chmod. Requesting the mode at `mkdir` time
/// leaves no such window. Do not "simplify" this to `create_dir_all`.
///
/// # Errors
/// - The log directory could not be created.
/// - Either log file could not be opened for writing.
/// - [`std::env::current_exe`] failed to resolve this binary's own path.
///
/// Reached in production through [`launch_daemon`], which `main` hands to
/// `shep_client::spawn::connect_or_spawn` as its launcher — the binary's
/// only autostart.
/// `File::create`'s effect — the file exists and is empty — on a descriptor
/// opened `O_APPEND`.
///
/// # Why not `File::create`
///
/// The daemon inherits these two as fds 1 and 2 and never opens them itself,
/// so whatever mode they are opened in here is the mode they keep for the
/// daemon's whole life. `File::create` is `O_WRONLY|O_CREAT|O_TRUNC` with no
/// `O_APPEND`, which leaves the descriptor tracking its own offset — and a
/// descriptor tracking its own offset writes PAST an external truncation
/// rather than at offset 0 of the emptied file. Measured: ten bytes written,
/// the file truncated from outside, three more bytes written, and the file
/// is thirteen bytes of which the first ten are `NUL`. Under `O_APPEND` the
/// same sequence leaves three bytes. This is the sparse hole `open_append`'s
/// own doc argues about for a sheep's logs, in the one place shep opens a log
/// file that is not a sheep's — and `shep flush --daemon` is the truncation
/// that would otherwise walk into it.
///
/// The launch-time emptying is preserved rather than traded away: `std`
/// refuses `append(true)` together with `truncate(true)`
/// (`OpenOptions::get_creation_mode` returns `InvalidInput`), so the truncate
/// is a `set_len(0)` on the already-appending handle instead. Reusing one
/// `$SHEP_HOME`'s logs across relaunches is still the whole of their rotation
/// story.
///
/// # Errors
///
/// The file could not be opened, or could not be emptied once open.
/// Lowest descriptor [`seal_inherited_fds`] touches. 0/1/2 are stdio, which
/// [`launch_command`] replaces wholesale for the child and which this
/// process still needs for its own output afterwards — marking those
/// close-on-exec would change what every OTHER `exec` from this process
/// sees, to fix nothing the redirects have not already fixed.
const FIRST_NON_STDIO_FD: RawFd = 3;
/// The directory whose entries name this process's own open descriptors.
/// `/dev/fd` on macOS (the `fdesc` filesystem), a symlink to
/// `/proc/self/fd` on Linux; both list exactly the numbers this process
/// holds.
const FD_DIR: &str = "/dev/fd";
/// Marks every descriptor this process holds above stdio close-on-exec, so
/// the daemon inherits none of them.
///
/// # The bug this exists for
///
/// A daemon lives for as long as `$SHEP_HOME` has a flock, so ANY
/// descriptor it inherits by accident is held open for that whole time —
/// and the launcher's own stdio is exactly the kind of descriptor that
/// leaks in. `shep start` is normally run with its stdout and stderr on a
/// pipe (a CI runner, `$(shep start …)`, a test harness, a shell reading
/// the output). Whoever holds the read end waits for EOF, and EOF arrives
/// only when the LAST copy of the write end closes — so a copy sitting in
/// the daemon means the reader never returns, long after `shep start`
/// itself has exited and printed everything it had to say. The reader is
/// then blocked, at 0% CPU, on a process that finished minutes ago.
///
/// Reproduced against `cli_e2e`'s `concurrent_cold_starts_produce_exactly_one_daemon`,
/// which is where it was found: under load the case would stall
/// indefinitely — not fail — with both `shep start` processes exited, the
/// surviving daemon holding the write end of one racer's stdout pipe, and
/// the harness parked in `read_to_end` waiting for an EOF that could not
/// come. `assert_cmd`'s `.timeout()` does not bound it: that bounds the
/// *process* wait, and the reader-thread join happens after it.
///
/// # Why the sweep, rather than closing one known descriptor
///
/// Because the leak is not this process's to enumerate. A descriptor
/// arrives without `FD_CLOEXEC` when something `dup2`'d it into place —
/// which is what every parent does to hand us our own stdio, and what a
/// `fork` in a multi-threaded parent can leave behind at other numbers
/// besides. The launcher cannot know which of the numbers it holds are
/// its own and which are a caller's leftovers, so it stops asking: above
/// stdio, nothing at all crosses this `exec`. The daemon receives its
/// stdio through [`launch_command`]'s redirects and opens everything else
/// (socket, pidfile, log files) for itself, so there is nothing left for
/// it to legitimately want.
///
/// Marking rather than closing, and marking *here* rather than in the
/// daemon: this process still needs those descriptors — it is a live
/// client that will go on to connect and print — so closing them is not on
/// offer. `FD_CLOEXEC` costs it nothing and takes effect at exactly the
/// boundary that matters. The daemon cannot do this job for itself either:
/// by the time any of its own code runs, a tokio runtime has already
/// opened descriptors of its own, and nothing in the process can then tell
/// an inherited number from one it just allocated (the same
/// recycled-number hazard `shep_daemon::sys`'s rationale essay works
/// through for `adopt_fd`).
///
/// # Best-effort, deliberately
///
/// Every failure is ignored and the launch proceeds. An unreadable
/// `/dev/fd`, an entry that is not a number, a descriptor closed between
/// the listing and the `fcntl` — none of them is a reason to refuse to
/// start a daemon, because the worst case of doing nothing here is the
/// pre-existing behaviour this function improves on, not a corrupt one.
/// The sweep's own directory handle is in the listing and gets marked
/// along with everything else, which is harmless: it is closed before this
/// function returns.
///
/// Process-wide, so it belongs at a spawn site and not in a builder: a
/// concurrent thread that wanted a descriptor of its own inherited by a
/// child would be defeated by it. Nothing in this binary spawns anything
/// but the daemon.
/// Spawns `shep daemon`, detached from this process's group and terminal.
///
/// Returns the child so the caller (`shep_client::spawn::connect_or_spawn`)
/// can `try_wait()` it while probing for readiness, rather than blocking on
/// it directly.
///
/// [`seal_inherited_fds`] runs first, so the daemon crosses the `exec` with
/// nothing but the stdio [`launch_command`] gives it — see that function's
/// own doc for the hang that motivates it. Ordered before [`launch_command`]
/// rather than after so the two log files it opens are never in the sweep's
/// path at all: they are already close-on-exec (std opens every file that
/// way) and reach the child as stdio through `dup2`, which clears the flag
/// on the descriptor it creates.
///
/// # Errors
/// Whatever [`launch_command`] can fail with, plus the spawn itself.
///
/// This is the launcher `main` passes to
/// `shep_client::spawn::connect_or_spawn`, so a cold `$SHEP_HOME` gets a
/// daemon on the first command that needs one.
/// Windows' `DETACHED_PROCESS`: the child gets no console of its own and
/// does not inherit the parent's.
const DETACHED_PROCESS: u32 = 0x0000_0008;
/// Windows' `CREATE_NEW_PROCESS_GROUP`.
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
/// Windows' `CREATE_BREAKAWAY_FROM_JOB`.
const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
/// Spawns the detached shepherd.
///
/// **There IS a `seal_inherited_fds` counterpart here**, and an earlier
/// version of this doc claimed there was not. The claim was that Windows
/// inherits only handles explicitly marked inheritable, so `Command`
/// marking its three stdio handles was already the outcome the unix sweep
/// works to reach. That is true of what `std` prepares and false of what
/// actually gets inherited: `CreateProcess` with `bInheritHandles = TRUE`
/// — which `std` passes whenever stdio is redirected — hands over EVERY
/// inheritable handle the parent holds.
///
/// So a shepherd launched from a shell that gave `shep` a pipe for stdout
/// inherited that pipe and held it open for its whole life, and the shell
/// blocked forever waiting for it to close. `shep start | anything` hung;
/// bare `shep start` did not. `shep_daemon::sys_windows::seal_std_handles`
/// closes it, and is called below for exactly the reason
/// [`seal_inherited_fds`] is called on unix.
///
/// # The breakaway retry
///
/// `CREATE_BREAKAWAY_FROM_JOB` is not merely ignored when the containing job
/// forbids breakaway — `CreateProcess` FAILS, with `ERROR_ACCESS_DENIED`. So
/// asking for it unconditionally would make `shep start` fail outright
/// inside any harness that runs its children in a locked-down job, which is
/// a common shape rather than an exotic one.
///
/// Asking and then retrying without it gets both halves right: a shepherd
/// launched from an ordinary console breaks away and survives its parent,
/// and one launched inside a restrictive job still starts — bound to that
/// job's lifetime, which is the best available answer and strictly better
/// than refusing to start at all.
///
/// # Errors
/// Whatever [`launch_command`] can fail with, plus the spawn itself.
// The whole module asserts unix specifics — a `0700` mode read back off the
// log directory, `process_group` on the built `Command`, and the
// close-on-exec sweep, none of which exists on Windows. What the Windows arm
// claims instead (detached creation flags, the breakaway retry) is exercised
// end to end by `tests/cli_e2e.rs`, which starts a real detached shepherd.