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
#![doc(html_root_url = "https://docs.rs/sd-notify/0.1.0")]
#![deny(missing_docs)]
use std::convert::TryFrom;
use std::env;
use std::fmt::{self, Display, Formatter, Write};
use std::fs;
use std::io::{self, ErrorKind};
use std::os::unix::io::RawFd;
use std::os::unix::net::UnixDatagram;
use std::process;
mod ffi;
#[derive(Clone, Debug)]
pub enum NotifyState {
Ready,
Reloading,
Stopping,
Status(String),
Errno(u32),
BusError(String),
MainPid(u32),
Watchdog,
WatchdogTrigger,
WatchdogUsec(u32),
ExtendTimeoutUsec(u32),
Custom(String),
}
impl Display for NotifyState {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
NotifyState::Ready => write!(f, "READY=1"),
NotifyState::Reloading => write!(f, "RELOADING=1"),
NotifyState::Stopping => write!(f, "STOPPING=1"),
NotifyState::Status(msg) => write!(f, "STATUS={}", msg),
NotifyState::Errno(err) => write!(f, "ERRNO={}", err),
NotifyState::BusError(addr) => write!(f, "BUSERROR={}", addr),
NotifyState::MainPid(pid) => write!(f, "MAINPID={}", pid),
NotifyState::Watchdog => write!(f, "WATCHDOG=1"),
NotifyState::WatchdogTrigger => write!(f, "WATCHDOG=trigger"),
NotifyState::WatchdogUsec(usec) => write!(f, "WATCHDOG_USEC={}", usec),
NotifyState::ExtendTimeoutUsec(usec) => write!(f, "EXTEND_TIMEOUT_USEC={}", usec),
NotifyState::Custom(state) => write!(f, "{}", state),
}
}
}
pub fn booted() -> io::Result<bool> {
let m = fs::symlink_metadata("/run/systemd/system")?;
Ok(m.is_dir())
}
pub fn notify(unset_env: bool, state: &[NotifyState]) -> io::Result<()> {
let socket_path = match env::var_os("NOTIFY_SOCKET") {
Some(path) => path,
None => return Ok(()),
};
if unset_env {
env::remove_var("NOTIFY_SOCKET");
}
let mut msg = String::new();
let sock = UnixDatagram::unbound()?;
for s in state {
let _ = writeln!(msg, "{}", s);
}
let len = sock.send_to(msg.as_bytes(), socket_path)?;
if len != msg.len() {
Err(io::Error::new(ErrorKind::WriteZero, "incomplete write"))
} else {
Ok(())
}
}
pub fn listen_fds() -> io::Result<impl Iterator<Item = RawFd>> {
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
env::remove_var("LISTEN_PID");
env::remove_var("LISTEN_FDS");
}
}
let _guard = Guard;
let listen_pid = if let Ok(pid) = env::var("LISTEN_PID") {
pid
} else {
return Ok(0..0);
}
.parse::<u32>()
.map_err(|_| io::Error::new(ErrorKind::InvalidInput, "invalid LISTEN_PID"))?;
if listen_pid != process::id() {
return Ok(0..0);
}
let listen_fds = if let Ok(fds) = env::var("LISTEN_FDS") {
fds
} else {
return Ok(0..0);
}
.parse::<u32>()
.map_err(|_| io::Error::new(ErrorKind::InvalidInput, "invalid LISTEN_FDS"))?;
let overflow = || io::Error::new(ErrorKind::InvalidInput, "fd count overflowed");
const SD_LISTEN_FDS_START: u32 = 3;
let last = SD_LISTEN_FDS_START
.checked_add(listen_fds)
.ok_or_else(overflow)?;
for fd in SD_LISTEN_FDS_START..last {
fd_cloexec(fd)?
}
let last = RawFd::try_from(last).map_err(|_| overflow())?;
let listen_fds = SD_LISTEN_FDS_START as RawFd..last;
Ok(listen_fds)
}
fn fd_cloexec(fd: u32) -> io::Result<()> {
let fd = RawFd::try_from(fd).map_err(|_| io::Error::from_raw_os_error(ffi::EBADF))?;
let flags = unsafe { ffi::fcntl(fd, ffi::F_GETFD, 0) };
if flags < 0 {
return Err(io::Error::last_os_error());
}
let new_flags = flags | ffi::FD_CLOEXEC;
if new_flags != flags {
let r = unsafe { ffi::fcntl(fd, ffi::F_SETFD, new_flags) };
if r < 0 {
return Err(io::Error::last_os_error());
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::NotifyState;
use std::env;
use std::fs;
use std::os::unix::net::UnixDatagram;
use std::path::PathBuf;
struct SocketHelper(PathBuf, UnixDatagram);
impl SocketHelper {
pub fn recv_string(&self) -> String {
let mut buf = [0; 1024];
let len = self.1.recv(&mut buf).unwrap();
String::from_utf8(Vec::from(&buf[0..len])).unwrap()
}
}
impl Drop for SocketHelper {
fn drop(&mut self) {
let _ = fs::remove_file(&self.0);
}
}
fn bind_socket() -> SocketHelper {
let path = env::temp_dir().join("sd-notify-test-sock");
let _ = fs::remove_file(&path);
env::set_var("NOTIFY_SOCKET", &path);
let sock = UnixDatagram::bind(&path).unwrap();
SocketHelper(path, sock)
}
#[test]
fn notify() {
let s = bind_socket();
super::notify(false, &[NotifyState::Ready]).unwrap();
assert_eq!(s.recv_string(), "READY=1\n");
assert!(env::var_os("NOTIFY_SOCKET").is_some());
super::notify(
true,
&[
NotifyState::Status(String::from("Reticulating splines")),
NotifyState::Watchdog,
NotifyState::Custom(String::from("X_WORKS=1")),
],
)
.unwrap();
assert_eq!(
s.recv_string(),
"STATUS=Reticulating splines\nWATCHDOG=1\nX_WORKS=1\n"
);
assert!(env::var_os("NOTIFY_SOCKET").is_none());
}
#[test]
fn listen_fds() {
assert!(super::listen_fds().unwrap().next().is_none());
env::set_var("LISTEN_PID", "1");
env::set_var("LISTEN_FDS", "1");
assert!(super::listen_fds().unwrap().next().is_none());
assert!(env::var_os("LISTEN_PID").is_none());
assert!(env::var_os("LISTEN_FDS").is_none());
env::set_var("LISTEN_PID", "no way");
env::set_var("LISTEN_FDS", "1");
assert!(super::listen_fds().is_err());
assert!(env::var_os("LISTEN_PID").is_none());
assert!(env::var_os("LISTEN_FDS").is_none());
}
}