| 1 | use std::{env, fmt, mem}; |
| 2 | |
| 3 | /// Fetch any sockets provided by systemd, and their names if specified |
| 4 | /// |
| 5 | /// See [sd_listen_fds](https://www.freedesktop.org/software/systemd/man/sd_listen_fds.html). |
| 6 | /// |
| 7 | /// Succeeds with an empty `Vec` if no socket was provided, e.g. if not started by systemd, |
| 8 | /// including on non-Linux platforms. |
| 9 | #[cfg_attr(not(target_os = "linux"), inline)] |
| 10 | pub fn get() -> Result<Vec<(Option<String>, OwnedFd)>, Error> { |
| 11 | #[cfg(target_os = "linux")] |
| 12 | { |
| 13 | let Ok(pid) = env::var("LISTEN_PID") else { return Ok(Vec::new()); }; |
| 14 | let pid = pid.parse::<u32>().map_err(|_| Error::MalformedEnv)?; |
| 15 | if pid != std::process::id() { |
| 16 | return Ok(Vec::new()); |
| 17 | } |
| 18 | let Ok(fd_count) = env::var("LISTEN_FDS") else { return Ok(Vec::new()); }; |
| 19 | let fd_count = fd_count.parse::<u32>().map_err(|_| Error::MalformedEnv)?; |
| 20 | |
| 21 | const SD_LISTEN_FDS_START: u32 = 3; |
| 22 | if fd_count > u32::MAX - 3 { |
| 23 | return Err(Error::MalformedEnv); |
| 24 | } |
| 25 | |
| 26 | let names_raw = env::var("LISTEN_FDNAMES").unwrap_or_else(|_| String::new()); |
| 27 | let mut names = names_raw.split(':'); |
| 28 | let mut result = Vec::with_capacity(fd_count as usize); |
| 29 | for i in 0..fd_count { |
| 30 | let name = match names_raw.is_empty() { |
| 31 | false => names.next().map(str::to_owned), |
| 32 | true => None, |
| 33 | }; |
| 34 | let fd = OwnedFd { |
| 35 | inner: unsafe { |
| 36 | mem::transmute::<u32, std::os::fd::OwnedFd>(SD_LISTEN_FDS_START + i) |
| 37 | }, |
| 38 | }; |
| 39 | result.push((name, fd)); |
| 40 | } |
| 41 | |
| 42 | Ok(result) |
| 43 | } |
| 44 | #[cfg(not(target_os = "linux"))] |
| 45 | { |
| 46 | Ok(Vec::new()) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /// An owned Unix file descriptor |
| 51 | /// |
| 52 | /// Similar to `std::os::fd::OwnedFd`, but defined on all platforms. Uninhabited on non-Unix |
| 53 | /// targets. |
| 54 | #[repr(transparent)] |
| 55 | pub struct OwnedFd { |
| 56 | #[cfg(unix)] |
| 57 | inner: std::os::fd::OwnedFd, |
| 58 | #[cfg(not(unix))] |
| 59 | inner: Empty, |
| 60 | } |
| 61 | |
| 62 | impl OwnedFd { |
| 63 | /// Release ownership of the underlying file descriptor |
| 64 | #[inline] |
| 65 | pub fn into_raw(self) -> u32 { |
| 66 | #[cfg(unix)] |
| 67 | unsafe { |
| 68 | mem::transmute(self.inner) |
| 69 | } |
| 70 | #[cfg(not(unix))] |
| 71 | { |
| 72 | match self.inner {} |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /// Convert to std type. Only available on Unix targets. Prefer using the provided `From` |
| 77 | /// implementations to avoid requiring `cfg` gates. |
| 78 | #[inline] |
| 79 | #[cfg(unix)] |
| 80 | pub fn into_std(self) -> std::os::fd::OwnedFd { |
| 81 | #[cfg(unix)] |
| 82 | { |
| 83 | self.inner |
| 84 | } |
| 85 | #[cfg(not(unix))] |
| 86 | { |
| 87 | match self.inner {} |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | #[cfg(not(unix))] |
| 93 | enum Empty {} |
| 94 | |
| 95 | macro_rules! from { |
| 96 | ($($(#[$meta:meta])? $path:path),* $(,)?) => { |
| 97 | $( |
| 98 | $(#[$meta])? |
| 99 | impl From<OwnedFd> for $path { |
| 100 | #[inline] |
| 101 | fn from(x: OwnedFd) -> Self { |
| 102 | #[cfg(unix)] |
| 103 | { |
| 104 | Self::from(x.inner) |
| 105 | } |
| 106 | #[cfg(not(unix))] |
| 107 | { |
| 108 | match x.inner {} |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | )* |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | from!( |
| 117 | std::net::TcpListener, |
| 118 | std::net::TcpStream, |
| 119 | std::net::UdpSocket, |
| 120 | #[cfg(unix)] |
| 121 | std::os::unix::net::UnixListener, |
| 122 | #[cfg(unix)] |
| 123 | std::os::unix::net::UnixDatagram, |
| 124 | #[cfg(unix)] |
| 125 | std::os::unix::net::UnixStream, |
| 126 | ); |
| 127 | |
| 128 | #[non_exhaustive] |
| 129 | #[derive(Debug, Clone)] |
| 130 | pub enum Error { |
| 131 | /// The environment contained non-empty, malformed socket activation variables (`LISTEN_PID` |
| 132 | /// and/or `LISTEN_FDS`) |
| 133 | MalformedEnv, |
| 134 | } |
| 135 | |
| 136 | impl std::error::Error for Error {} |
| 137 | |
| 138 | impl fmt::Display for Error { |
| 139 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 140 | f.pad("malformed socket activation environment") |
| 141 | } |
| 142 | } |