Skip to main content

daemon_detect/
values.rs

1//! Validated domain values used by markers and service identities.
2//!
3//! Each wrapper enforces the limits of the OS surface the value is
4//! handed to at construction time, so detection and label derivation
5//! can never emit a malformed account lookup, environment probe, or
6//! service label.
7
8use std::fmt;
9
10/// Why a service value was rejected.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct InvalidServiceValue {
13    kind: &'static str,
14    reason: &'static str,
15    value: String,
16}
17
18impl InvalidServiceValue {
19    fn new(kind: &'static str, reason: &'static str, value: &str) -> Self {
20        Self {
21            kind,
22            reason,
23            value: value.to_owned(),
24        }
25    }
26}
27
28impl fmt::Display for InvalidServiceValue {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        write!(
31            f,
32            "invalid {}: {} ({:?})",
33            self.kind, self.reason, self.value
34        )
35    }
36}
37
38impl std::error::Error for InvalidServiceValue {}
39
40/// A Unix service-account name, as passed to `getpwnam(3)`.
41///
42/// Limits: 1–32 bytes, ASCII graphic characters only, and none of
43/// `:`, `/`, or whitespace (the passwd-database separators). macOS
44/// underscore-prefixed accounts (`_mydaemon`) are valid.
45#[derive(Debug, Clone, PartialEq, Eq, Hash)]
46pub struct ServiceAccountName(String);
47
48impl ServiceAccountName {
49    /// Validate and wrap a service-account name.
50    ///
51    /// # Errors
52    ///
53    /// Returns [`InvalidServiceValue`] when the name is empty, longer
54    /// than 32 bytes, or contains a non-graphic ASCII byte, `:`, or
55    /// `/`.
56    pub fn try_new(name: impl Into<String>) -> Result<Self, InvalidServiceValue> {
57        const KIND: &str = "service-account name";
58        let name = name.into();
59        if name.is_empty() {
60            return Err(InvalidServiceValue::new(KIND, "must not be empty", &name));
61        }
62        if name.len() > 32 {
63            return Err(InvalidServiceValue::new(
64                KIND,
65                "longer than 32 bytes",
66                &name,
67            ));
68        }
69        if !name.bytes().all(|b| b.is_ascii_graphic()) {
70            return Err(InvalidServiceValue::new(
71                KIND,
72                "must be ASCII graphic characters",
73                &name,
74            ));
75        }
76        if name.contains([':', '/']) {
77            return Err(InvalidServiceValue::new(
78                KIND,
79                "must not contain ':' or '/'",
80                &name,
81            ));
82        }
83        Ok(Self(name))
84    }
85
86    /// The validated account name.
87    #[must_use]
88    pub fn as_str(&self) -> &str {
89        &self.0
90    }
91}
92
93/// An environment-variable name, as probed with `std::env::var_os`.
94///
95/// Limits: 1–128 bytes, ASCII graphic characters only, and no `=`
96/// (the environment-block separator).
97#[derive(Debug, Clone, PartialEq, Eq, Hash)]
98pub struct EnvVarName(String);
99
100impl EnvVarName {
101    /// Validate and wrap an environment-variable name.
102    ///
103    /// # Errors
104    ///
105    /// Returns [`InvalidServiceValue`] when the name is empty, longer
106    /// than 128 bytes, contains a non-graphic ASCII byte, or contains
107    /// `=`.
108    pub fn try_new(name: impl Into<String>) -> Result<Self, InvalidServiceValue> {
109        const KIND: &str = "environment-variable name";
110        let name = name.into();
111        if name.is_empty() {
112            return Err(InvalidServiceValue::new(KIND, "must not be empty", &name));
113        }
114        if name.len() > 128 {
115            return Err(InvalidServiceValue::new(
116                KIND,
117                "longer than 128 bytes",
118                &name,
119            ));
120        }
121        if !name.bytes().all(|b| b.is_ascii_graphic()) {
122            return Err(InvalidServiceValue::new(
123                KIND,
124                "must be ASCII graphic characters",
125                &name,
126            ));
127        }
128        if name.contains('=') {
129            return Err(InvalidServiceValue::new(
130                KIND,
131                "must not contain '='",
132                &name,
133            ));
134        }
135        Ok(Self(name))
136    }
137
138    /// The validated variable name.
139    #[must_use]
140    pub fn as_str(&self) -> &str {
141        &self.0
142    }
143}
144
145/// An installed binary's file name, used in systemd template units
146/// (`{binary}@{instance}.service`) and Windows service names
147/// (`{binary}-{instance}`).
148///
149/// Limits: 1–64 bytes, ASCII graphic characters only, and none of
150/// `/`, `\`, or `@` (path and systemd-template separators). A
151/// platform suffix such as `.exe` is valid.
152#[derive(Debug, Clone, PartialEq, Eq, Hash)]
153pub struct BinaryName(String);
154
155impl BinaryName {
156    /// Validate and wrap a binary name.
157    ///
158    /// # Errors
159    ///
160    /// Returns [`InvalidServiceValue`] when the name is empty, longer
161    /// than 64 bytes, contains a non-graphic ASCII byte, or contains
162    /// `/`, `\`, or `@`.
163    pub fn try_new(name: impl Into<String>) -> Result<Self, InvalidServiceValue> {
164        const KIND: &str = "binary name";
165        let name = name.into();
166        if name.is_empty() {
167            return Err(InvalidServiceValue::new(KIND, "must not be empty", &name));
168        }
169        if name.len() > 64 {
170            return Err(InvalidServiceValue::new(
171                KIND,
172                "longer than 64 bytes",
173                &name,
174            ));
175        }
176        if !name.bytes().all(|b| b.is_ascii_graphic()) {
177            return Err(InvalidServiceValue::new(
178                KIND,
179                "must be ASCII graphic characters",
180                &name,
181            ));
182        }
183        if name.contains(['/', '\\', '@']) {
184            return Err(InvalidServiceValue::new(
185                KIND,
186                "must not contain '/', '\\', or '@'",
187                &name,
188            ));
189        }
190        Ok(Self(name))
191    }
192
193    /// The validated binary name.
194    #[must_use]
195    pub fn as_str(&self) -> &str {
196        &self.0
197    }
198}
199
200/// A reverse-DNS launchd label prefix (e.g. `com.example.my-daemon`).
201///
202/// Limits: 1–128 bytes, one or more non-empty dot-separated segments
203/// of ASCII alphanumerics, `-`, or `_`; no leading, trailing, or
204/// doubled dots.
205#[derive(Debug, Clone, PartialEq, Eq, Hash)]
206pub struct LaunchdLabelPrefix(String);
207
208impl LaunchdLabelPrefix {
209    /// Validate and wrap a launchd label prefix.
210    ///
211    /// # Errors
212    ///
213    /// Returns [`InvalidServiceValue`] when the prefix is empty,
214    /// longer than 128 bytes, or not dot-separated segments of ASCII
215    /// alphanumerics, `-`, or `_`.
216    pub fn try_new(prefix: impl Into<String>) -> Result<Self, InvalidServiceValue> {
217        const KIND: &str = "launchd label prefix";
218        let prefix = prefix.into();
219        if prefix.is_empty() {
220            return Err(InvalidServiceValue::new(KIND, "must not be empty", &prefix));
221        }
222        if prefix.len() > 128 {
223            return Err(InvalidServiceValue::new(
224                KIND,
225                "longer than 128 bytes",
226                &prefix,
227            ));
228        }
229        let valid_segments = prefix.split('.').all(|segment| {
230            !segment.is_empty()
231                && segment
232                    .bytes()
233                    .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
234        });
235        if !valid_segments {
236            return Err(InvalidServiceValue::new(
237                KIND,
238                "must be dot-separated segments of ASCII alphanumerics, '-', or '_'",
239                &prefix,
240            ));
241        }
242        Ok(Self(prefix))
243    }
244
245    /// The validated prefix.
246    #[must_use]
247    pub fn as_str(&self) -> &str {
248        &self.0
249    }
250}
251
252/// A service-instance discriminator (a port, an identity key, …),
253/// appended to every label format.
254///
255/// Limits: 1–128 bytes, ASCII graphic characters only, and none of
256/// `/`, `\`, or `@` (path and systemd-template separators).
257#[derive(Debug, Clone, PartialEq, Eq, Hash)]
258pub struct ServiceInstance(String);
259
260impl ServiceInstance {
261    /// Validate and wrap an instance discriminator.
262    ///
263    /// # Errors
264    ///
265    /// Returns [`InvalidServiceValue`] when the instance is empty,
266    /// longer than 128 bytes, contains a non-graphic ASCII byte, or
267    /// contains `/`, `\`, or `@`.
268    pub fn try_new(instance: impl Into<String>) -> Result<Self, InvalidServiceValue> {
269        const KIND: &str = "service instance";
270        let instance = instance.into();
271        if instance.is_empty() {
272            return Err(InvalidServiceValue::new(
273                KIND,
274                "must not be empty",
275                &instance,
276            ));
277        }
278        if instance.len() > 128 {
279            return Err(InvalidServiceValue::new(
280                KIND,
281                "longer than 128 bytes",
282                &instance,
283            ));
284        }
285        if !instance.bytes().all(|b| b.is_ascii_graphic()) {
286            return Err(InvalidServiceValue::new(
287                KIND,
288                "must be ASCII graphic characters",
289                &instance,
290            ));
291        }
292        if instance.contains(['/', '\\', '@']) {
293            return Err(InvalidServiceValue::new(
294                KIND,
295                "must not contain '/', '\\', or '@'",
296                &instance,
297            ));
298        }
299        Ok(Self(instance))
300    }
301
302    /// The validated instance discriminator.
303    #[must_use]
304    pub fn as_str(&self) -> &str {
305        &self.0
306    }
307}
308
309impl From<u16> for ServiceInstance {
310    /// A port number is always a valid instance discriminator.
311    fn from(port: u16) -> Self {
312        Self(port.to_string())
313    }
314}
315
316macro_rules! string_value_traits {
317    ($($ty:ident),+) => {$(
318        impl fmt::Display for $ty {
319            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320                f.write_str(&self.0)
321            }
322        }
323
324        impl std::str::FromStr for $ty {
325            type Err = InvalidServiceValue;
326
327            fn from_str(s: &str) -> Result<Self, Self::Err> {
328                Self::try_new(s)
329            }
330        }
331
332        impl AsRef<str> for $ty {
333            fn as_ref(&self) -> &str {
334                &self.0
335            }
336        }
337    )+};
338}
339
340string_value_traits!(
341    ServiceAccountName,
342    EnvVarName,
343    BinaryName,
344    LaunchdLabelPrefix,
345    ServiceInstance
346);