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
//! Adopting an inherited descriptor — this crate's only `unsafe`
//!
//! **Why unsafe here, and nowhere else.** The daemonization contract (spec
//! §3) is that the CLI re-execs itself detached and the child reports
//! `{pid, version}` on an inherited pipe once the socket is bound. Adopting
//! an inherited descriptor is the one operation std offers no safe path
//! for: `OwnedFd`/`File` can only be built from a raw number through
//! `from_raw_fd`, which is unsafe because nothing in the type system proves
//! the number names a descriptor this process owns.
//!
//! **All of it, confined to this file (IR-22).** [`adopt_fd`] is `unsafe
//! fn`, not a safe fn hiding an internal unsafe block: the ordering
//! precondition that makes adoption sound (call this before the process
//! opens anything of its own — see scenario (c) below) is a CALLER
//! obligation this function cannot verify from inside itself, so the type
//! system pushes it out to whoever calls it. [`crate::boot::BootOptions::ready_fd`]
//! is `Option<`[`std::fs::File`]`>`, an already-owned handle — `boot`
//! itself never calls this function and contains no unsafe of its own (see
//! that field's own doc). The crate's actual unsafe surface today, counted
//! honestly: [`adopt_fd`]'s own definition here, plus this file's own
//! test-only call sites exercising it directly against synthetic fds (see
//! below) — every syntactic site lives in this one file. The intended
//! PRODUCTION caller is the CLI's `main` (Phase 3), a different crate, as
//! its literal first fd-touching statement, before a tokio runtime even
//! exists — not written yet, so it adds no site here today. What actually
//! matters for soundness is unaffected by exactly how many test sites this
//! file accumulates: only a real production call's ordering claim has to
//! hold against a genuinely inherited descriptor; every test site adopts a
//! fd it created itself moments earlier in the same test, which is a
//! narrower, locally-checkable obligation, not a widening of the
//! exception.
//!
//! **Rejected alternative:** have the parent pass a socket path
//! (`SHEP_READY_SOCK`) and let the child connect and write. It is entirely
//! safe and was the first design. Its cost is a second socket in the boot
//! path — one more thing to place inside 0700, unlink, and recover when
//! stale — to replace a five-line adoption, and it puts the readiness
//! handshake on a different mechanism from the one the spec, systemd
//! `Type=notify` integration, and every comparable supervisor use. Not
//! worth it.
//!
//! **Invariant:** the descriptor was inherited across `exec` from our own
//! parent and is not otherwise owned in this process. **Checked, not
//! assumed:** [`adopt_fd`] refuses anything below fd 3 (stdio is owned
//! elsewhere) and calls `fcntl(fd, F_GETFD)` first, so a closed or
//! never-opened number returns [`SysError::BadFd`] instead of being
//! adopted. **Failure scenarios considered:**
//! (a) a hostile `SHEP_READY_FD=1` — refused by the fd-3 floor, so stdout
//! is never closed underneath the logger;
//! (b) a stale number for a descriptor closed since exec — refused by the
//! `fcntl` probe;
//! (c) a number that has been *recycled* into another live descriptor
//! since exec — this is a REAL hazard, not a theoretical one, and an
//! earlier version of this essay was wrong to call it "impossible in
//! practice": `F_GETFD` only proves a number is open RIGHT NOW, never
//! who opened it, so it cannot distinguish a genuinely inherited
//! descriptor from a number the daemon's OWN later steps happened to
//! reuse. Concretely: an earlier version of `boot()` called adoption
//! *after* `bind_socket`/`write_pidfile` had already opened (and, for
//! the pidfile's temp file, closed) descriptors of their own — a stale
//! `SHEP_READY_FD` could then land on the freshly-bound listener's own
//! fd, and dropping the wrongly-adopted `File` closed that listener out
//! from under `tokio`, reproducibly, through nothing more exotic than
//! the ordinary `boot()` API (`BootOptions { ready_fd: Some(stale) }`).
//! This is exactly why [`adopt_fd`] is `unsafe fn`: the precondition
//! that actually closes this hole — call it before this process has
//! opened any descriptor of its own — is a CALLER obligation no amount
//! of internal checking can verify from inside `adopt_fd` itself, so
//! the type system now forces every call site to write down its own
//! justification instead of letting the invariant erode silently on a
//! future reorder. **Decision 1 (2026-08-08) removed the whole class
//! of risk this scenario describes from this crate structurally**,
//! rather than merely re-ordering around it again: `boot` no longer
//! calls [`adopt_fd`] at all, so it is no longer possible for anything
//! `boot` itself does — bind a socket, open a tempfile, install signal
//! handlers — to land between adoption and use. The intended
//! PRODUCTION caller is the CLI's `main` (Phase 3), which discharges
//! the ordering precondition by being the literal first fd-touching
//! statement of the whole process, before a tokio runtime — the thing
//! that made `boot`'s own attempt at this structurally impossible to
//! guarantee, since `boot` is `async` and a runtime with its own live
//! poller fds necessarily exists before `boot` is ever called — even
//! exists. See [`crate::boot::BootOptions::ready_fd`]'s own doc;
//!
//! (d) double adoption — a future production caller (the CLI's `main`,
//! Phase 3) is expected to call [`adopt_fd`] at most once, consuming
//! the number into an owning [`std::fs::File`] that closes it on drop,
//! so a second production adoption of the same fd should not occur; if
//! it somehow did, scenario (b)'s `BadFd` refusal catches it, since the
//! first adoption already closed the number. (This crate's *tests*
//! call `adopt_fd` directly, and more than once across the suite, each
//! time against a fd the test itself just created — a different,
//! lower-stakes situation than production double-adoption, and not
//! what this scenario is about.)
// IR-24 exception — seven sites total, all in this file (its own definition plus 6 test call sites; `boot.rs` has none — see the essay above and `crate::boot::BootOptions::ready_fd`'s doc).
use fmt;
use File;
use ;
/// Lowest fd number this daemon will ever adopt. 0/1/2 are stdio, owned by
/// the logger and inherited-terminal plumbing elsewhere in the process —
/// adopting one of those into an owning [`File`] would silently steal it out
/// from under whatever already holds it.
const RESERVED_FD_FLOOR: RawFd = 3;
/// Takes ownership of a descriptor inherited across `exec`.
///
/// # Errors
/// - [`SysError::ReservedFd`] — `fd` is below 3 (stdio is owned elsewhere).
/// - [`SysError::BadFd`] — `fd` names no open descriptor in this process.
///
/// # Safety
///
/// The caller must call this before this process opens (or closes) any
/// descriptor of its own — before binding a socket, opening a file,
/// spawning anything that inherits fds. `F_GETFD` (used internally) only
/// proves a number is CURRENTLY open, never who opened it or what it now
/// names, so calling this after the process has touched its own descriptors
/// risks adopting a number the kernel has since recycled into something the
/// process already owns; dropping the returned [`File`] would then close
/// that resource out from under its real owner instead of the intended
/// inherited pipe. See this module's rationale essay, scenario (c), for a
/// worked example of exactly this happening.
///
/// The intended caller is the CLI's `main` (Phase 3, a different crate —
/// not written yet): its literal first fd-touching statement, before a
/// tokio runtime (or anything else) exists. Nothing in `shep-daemon` calls
/// this function in production today; [`crate::boot::boot`] receives an
/// already-adopted [`std::fs::File`] via
/// [`crate::boot::BootOptions::ready_fd`] and never touches a raw fd
/// itself — see that field's own doc for why adoption moved out of `boot`.
pub unsafe
/// Errors adopting an inherited descriptor.
///
/// `#[non_exhaustive]`: today's two variants cover a disqualified fd number
/// and one the OS says is not open, and a future adoption check — rejecting
/// an fd that is open but of the wrong kind, not a socket where one is
/// required — would need its own variant rather than stretching
/// [`Self::BadFd`] past what `fcntl` actually told the caller, and
/// shep-daemon is a published library an out-of-tree matcher should not
/// break for (IR-20).