1use std::fmt;
14use std::io;
15use std::sync::{Mutex, PoisonError};
16
17use crate::handoff::ListenerHandle;
18#[cfg(unix)]
19use crate::sys::KindError;
20
21#[non_exhaustive]
27#[derive(Debug)]
28pub enum InheritError {
29 BadCount,
31 TooMany {
33 max: u32,
35 },
36 NotASocket {
38 fd: i32,
40 },
41 NotListening {
43 fd: i32,
45 },
46 WrongKind {
48 fd: i32,
50 },
51 NamesMismatch,
53 PidFdMismatch,
55 Os(io::Error),
57}
58
59impl fmt::Display for InheritError {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 match self {
62 InheritError::BadCount => f.write_str("LISTEN_FDS is not a valid count"),
63 InheritError::TooMany { max } => write!(f, "more than {max} inherited descriptors"),
64 InheritError::NotASocket { fd } => write!(f, "descriptor {fd} is not a socket"),
65 InheritError::NotListening { fd } => {
66 write!(f, "descriptor {fd} is not a listening socket")
67 }
68 InheritError::WrongKind { fd } => {
69 write!(f, "descriptor {fd} is not a TCP or Unix stream socket")
70 }
71 InheritError::NamesMismatch => f.write_str("LISTEN_FDNAMES does not match LISTEN_FDS"),
72 InheritError::PidFdMismatch => {
73 f.write_str("LISTEN_PIDFDID does not match this process")
74 }
75 InheritError::Os(e) => write!(f, "{e}"),
76 }
77 }
78}
79
80impl std::error::Error for InheritError {
81 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
82 match self {
83 InheritError::Os(e) => Some(e),
84 _ => None,
85 }
86 }
87}
88
89#[derive(Debug)]
91pub struct InheritedListener {
92 pub name: Option<String>,
94 pub handle: ListenerHandle,
96}
97
98#[cfg(unix)]
100const MAX_FDS: u32 = 64;
101#[cfg(unix)]
103const FIRST_FD: i32 = 3;
104
105struct Taken {
107 read: bool,
108 left: Vec<InheritedListener>,
109}
110
111static SYSTEMD: Mutex<Taken> = Mutex::new(Taken {
112 read: false,
113 left: Vec::new(),
114});
115
116pub fn systemd() -> Result<Vec<InheritedListener>, InheritError> {
146 let mut taken = SYSTEMD.lock().unwrap_or_else(PoisonError::into_inner);
147 read_once(&mut taken)?;
148 Ok(std::mem::take(&mut taken.left))
149}
150
151pub fn systemd_named(name: &str) -> Result<Option<InheritedListener>, InheritError> {
158 let mut taken = SYSTEMD.lock().unwrap_or_else(PoisonError::into_inner);
159 read_once(&mut taken)?;
160 Ok(taken
161 .left
162 .iter()
163 .position(|l| l.name.as_deref() == Some(name))
164 .map(|i| taken.left.remove(i)))
165}
166
167fn read_once(taken: &mut Taken) -> Result<(), InheritError> {
168 if taken.read {
169 return Ok(());
170 }
171 #[cfg(unix)]
172 {
173 let env = |k: &str| std::env::var(k).ok();
174 let plan = plan_systemd(&env, std::process::id(), FIRST_FD)?;
176 taken.read = true;
178 taken.left = take_systemd(plan)?;
179 }
180 taken.read = true;
181 Ok(())
182}
183
184#[cfg(unix)]
186type Plan = Vec<(i32, Option<String>)>;
187
188#[cfg(all(unix, any(test, fuzzing)))]
190fn from_systemd(
191 env: &dyn Fn(&str) -> Option<String>,
192 pid: u32,
193 first: i32,
194) -> Result<Vec<InheritedListener>, InheritError> {
195 take_systemd(plan_systemd(env, pid, first)?)
196}
197
198#[cfg(unix)]
200fn plan_systemd(
201 env: &dyn Fn(&str) -> Option<String>,
202 pid: u32,
203 first: i32,
204) -> Result<Plan, InheritError> {
205 match env("LISTEN_PID").and_then(|p| p.trim().parse::<u32>().ok()) {
207 Some(p) if p == pid => {}
208 _ => return Ok(Vec::new()),
209 }
210 #[cfg(target_os = "linux")]
211 if let Some(want) = env("LISTEN_PIDFDID") {
212 let want: u64 = want
213 .trim()
214 .parse()
215 .map_err(|_| InheritError::PidFdMismatch)?;
216 if crate::sys::pidfd_inode().map_err(InheritError::Os)? != want {
217 return Err(InheritError::PidFdMismatch);
218 }
219 }
220 let Some(count) = env("LISTEN_FDS") else {
221 return Ok(Vec::new());
222 };
223 let count: u32 = count.trim().parse().map_err(|_| InheritError::BadCount)?;
224 if count > MAX_FDS {
225 return Err(InheritError::TooMany { max: MAX_FDS });
226 }
227 let names: Option<Vec<String>> =
228 env("LISTEN_FDNAMES").map(|n| n.split(':').map(str::to_owned).collect());
229 if names.as_ref().is_some_and(|n| n.len() != count as usize) {
230 return Err(InheritError::NamesMismatch);
231 }
232 let fds: Vec<i32> = (0..count as i32).map(|i| first + i).collect();
233 if fds.iter().any(|&fd| crate::sys::close_on_exec(fd)) {
237 return Ok(Vec::new());
238 }
239 for &fd in &fds {
241 crate::sys::inherited_kind(fd).map_err(|e| kind_error(e, fd))?;
242 }
243 Ok(fds
244 .into_iter()
245 .enumerate()
246 .map(|(i, fd)| {
247 let name = names
248 .as_ref()
249 .and_then(|n| n.get(i))
250 .filter(|n| !n.is_empty())
251 .cloned();
252 (fd, name)
253 })
254 .collect())
255}
256
257#[cfg(unix)]
260fn take_systemd(plan: Plan) -> Result<Vec<InheritedListener>, InheritError> {
261 let mut out = Vec::with_capacity(plan.len());
262 for (fd, name) in plan {
263 let owned = crate::sys::claim_inherited(fd).map_err(InheritError::Os)?;
264 let handle =
265 ListenerHandle::verified(owned, name.clone()).map_err(|e| kind_error(e, fd))?;
266 out.push(InheritedListener { name, handle });
267 }
268 Ok(out)
269}
270
271#[cfg(all(fuzzing, unix))]
275pub(crate) fn fuzz_systemd_env(data: &[u8]) {
276 let text = String::from_utf8_lossy(data);
277 let mut parts = text.split('\0');
278 let pid = std::process::id();
279 let (fds, names, pidfd) = (parts.next(), parts.next(), parts.next());
280 let env = |k: &str| match k {
281 "LISTEN_PID" => Some(pid.to_string()),
282 "LISTEN_FDS" => fds.map(str::to_owned),
283 "LISTEN_FDNAMES" => names.map(str::to_owned),
284 "LISTEN_PIDFDID" => pidfd.map(str::to_owned),
285 _ => None,
286 };
287 if let Ok(list) = from_systemd(&env, pid, 1_000_000) {
288 assert!(list.is_empty(), "no descriptor is open up there");
289 }
290}
291
292#[cfg(all(fuzzing, not(unix)))]
293pub(crate) fn fuzz_systemd_env(_data: &[u8]) {}
294
295#[cfg(unix)]
296fn kind_error(e: KindError, fd: i32) -> InheritError {
297 match e {
298 KindError::NotASocket => InheritError::NotASocket { fd },
299 KindError::NotListening => InheritError::NotListening { fd },
300 KindError::WrongKind => InheritError::WrongKind { fd },
301 KindError::Os(e) => InheritError::Os(e),
302 }
303}
304
305#[cfg(unix)]
306static FASTCGI: Mutex<bool> = Mutex::new(false);
307
308#[cfg(unix)]
325pub fn fastcgi_listener() -> Result<Option<ListenerHandle>, InheritError> {
326 let mut taken = FASTCGI.lock().unwrap_or_else(PoisonError::into_inner);
327 if *taken {
328 return Ok(None);
329 }
330 let got = fastcgi_from(0)?;
331 if got.is_some() {
332 *taken = true;
333 }
334 Ok(got)
335}
336
337#[cfg(unix)]
338fn fastcgi_from(fd: i32) -> Result<Option<ListenerHandle>, InheritError> {
339 if crate::sys::close_on_exec(fd) {
341 return Ok(None);
342 }
343 match crate::sys::inherited_kind(fd) {
344 Ok(_) => {}
345 Err(KindError::Os(e)) => return Err(InheritError::Os(e)),
346 Err(_) => return Ok(None),
347 }
348 let owned = crate::sys::claim_inherited(fd).map_err(InheritError::Os)?;
351 ListenerHandle::verified(owned, None)
352 .map(Some)
353 .map_err(|e| kind_error(e, fd))
354}
355
356#[cfg(all(test, unix))]
357mod tests {
358 use super::*;
359 use std::collections::HashMap;
360 use std::os::fd::AsFd;
361
362 fn env(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
363 let map: HashMap<String, String> = vars
364 .iter()
365 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
366 .collect();
367 move |k| map.get(k).cloned()
368 }
369
370 fn place(base: i32, n: usize) -> Vec<std::net::TcpListener> {
372 (0..n)
373 .map(|i| {
374 let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
375 crate::sys::dup_to(l.as_fd(), base + i as i32).unwrap();
376 l
377 })
378 .collect()
379 }
380
381 #[test]
382 fn test_systemd_protocol() {
383 let me = std::process::id();
384 let pid = me.to_string();
385 assert!(from_systemd(&env(&[]), me, 900).unwrap().is_empty());
387 assert!(
388 from_systemd(&env(&[("LISTEN_PID", "1"), ("LISTEN_FDS", "1")]), me, 900)
389 .unwrap()
390 .is_empty()
391 );
392 assert!(
393 from_systemd(&env(&[("LISTEN_PID", &pid), ("LISTEN_FDS", "0")]), me, 900)
394 .unwrap()
395 .is_empty()
396 );
397 for bad in ["x", "-1", ""] {
399 assert!(matches!(
400 from_systemd(&env(&[("LISTEN_PID", &pid), ("LISTEN_FDS", bad)]), me, 900),
401 Err(InheritError::BadCount)
402 ));
403 }
404 assert!(matches!(
405 from_systemd(&env(&[("LISTEN_PID", &pid), ("LISTEN_FDS", "65")]), me, 900),
406 Err(InheritError::TooMany { max: 64 })
407 ));
408 assert!(matches!(
410 from_systemd(
411 &env(&[
412 ("LISTEN_PID", &pid),
413 ("LISTEN_FDS", "2"),
414 ("LISTEN_FDNAMES", "a")
415 ]),
416 me,
417 900
418 ),
419 Err(InheritError::NamesMismatch)
420 ));
421 assert!(matches!(
423 from_systemd(&env(&[("LISTEN_PID", &pid), ("LISTEN_FDS", "1")]), me, 990),
424 Err(InheritError::NotASocket { fd: 990 })
425 ));
426 let file = std::fs::File::open("/dev/null").unwrap();
427 crate::sys::dup_to(file.as_fd(), 991).unwrap();
428 assert!(matches!(
429 from_systemd(&env(&[("LISTEN_PID", &pid), ("LISTEN_FDS", "1")]), me, 991),
430 Err(InheritError::NotASocket { fd: 991 })
431 ));
432 crate::sys::close_number(991);
433 }
434
435 #[test]
436 fn test_systemd_takes_verified_listeners_with_names() {
437 let me = std::process::id();
438 let pid = me.to_string();
439 let ls = place(910, 2);
440 let got = from_systemd(
441 &env(&[
442 ("LISTEN_PID", &pid),
443 ("LISTEN_FDS", "2"),
444 ("LISTEN_FDNAMES", "web:"),
445 ]),
446 me,
447 910,
448 )
449 .unwrap();
450 assert_eq!(got.len(), 2);
451 assert_eq!(got[0].name.as_deref(), Some("web"));
452 assert_eq!(got[1].name, None, "an empty name is no name");
453 assert_eq!(
454 got[0].handle.local().socket_addr(),
455 Some(ls[0].local_addr().unwrap())
456 );
457 let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
459 let c = std::net::TcpStream::connect(l.local_addr().unwrap()).unwrap();
460 crate::sys::dup_to(c.as_fd(), 920).unwrap();
461 assert!(matches!(
462 from_systemd(&env(&[("LISTEN_PID", &pid), ("LISTEN_FDS", "1")]), me, 920),
463 Err(InheritError::NotListening { fd: 920 })
464 ));
465 crate::sys::close_number(920);
466 }
467
468 #[test]
469 fn test_fastcgi_descriptor_checks() {
470 let file = std::fs::File::open("/dev/null").unwrap();
472 crate::sys::dup_to(file.as_fd(), 930).unwrap();
473 assert!(fastcgi_from(930).unwrap().is_none());
474 crate::sys::close_number(930);
475 let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
476 let c = std::net::TcpStream::connect(l.local_addr().unwrap()).unwrap();
477 crate::sys::dup_to(c.as_fd(), 931).unwrap();
478 assert!(fastcgi_from(931).unwrap().is_none());
479 crate::sys::close_number(931);
480 crate::sys::dup_to(l.as_fd(), 932).unwrap();
481 let h = fastcgi_from(932).unwrap().unwrap();
482 assert_eq!(h.local().socket_addr(), Some(l.local_addr().unwrap()));
483 assert!(fastcgi_from(-1).unwrap().is_none());
484 }
485
486 #[test]
490 fn test_close_on_exec_descriptors_are_not_inherited() {
491 use std::os::fd::IntoRawFd;
492 let me = std::process::id();
493 let pid = me.to_string();
494 let _ls = place(940, 2);
495 let own = crate::sys::claim_inherited(941).unwrap().into_raw_fd();
497 assert_eq!(own, 941);
498 let got =
499 from_systemd(&env(&[("LISTEN_PID", &pid), ("LISTEN_FDS", "2")]), me, 940).unwrap();
500 assert!(got.is_empty(), "stale variables: nothing inherited");
501 assert!(crate::sys::inherited_kind(940).is_ok());
503 assert!(crate::sys::inherited_kind(941).is_ok());
504 assert!(fastcgi_from(941).unwrap().is_none());
505 assert!(crate::sys::inherited_kind(941).is_ok());
506 crate::sys::close_number(940);
507 crate::sys::close_number(941);
508 }
509}