Mercurial > crates > systemd-socket
annotate src/lib.rs @ 3:0edcde404b02
Added information about MSRV
author | Martin Habovstiak <martin.habovstiak@gmail.com> |
---|---|
date | Fri, 27 Nov 2020 12:56:37 +0100 |
parents | cabc4aafdd85 |
children | 66c0e10c89fc |
rev | line source |
---|---|
0 | 1 //! A convenience crate for optionally supporting systemd socket activation. |
2 //! | |
3 //! ## About | |
4 //! | |
5 //! The goal of this crate is to make socket activation with systemd in your project trivial. | |
6 //! It provides a replacement for `std::net::SocketAddr` that allows parsing the bind address from string just like the one from `std` | |
7 //! but on top of that also allows `systemd://socket_name` format that tells it to use systemd activation with given socket name. | |
8 //! Then it provides a method to bind the address which will return the socket from systemd if available. | |
9 //! | |
10 //! The provided type supports conversions from various types of strings and also `serde` and `parse_arg` via feature flag. | |
11 //! Thanks to this the change to your code should be minimal - parsing will continue to work, it'll just allow a new format. | |
12 //! You only need to change the code to use `SocketAddr::bind()` instead of `TcpListener::bind()` for binding. | |
13 //! | |
14 //! Further, the crate also provides convenience methods for binding `tokio` 0.2, 0.3, and | |
15 //! `async_std` sockets if the appropriate features are activated. | |
16 //! | |
17 //! ## Example | |
18 //! | |
19 //! ```no_run | |
20 //! use systemd_socket::SocketAddr; | |
21 //! use std::convert::TryFrom; | |
22 //! use std::io::Write; | |
23 //! | |
24 //! let mut args = std::env::args_os(); | |
25 //! let program_name = args.next().expect("unknown program name"); | |
26 //! let socket_addr = args.next().expect("missing socket address"); | |
27 //! let socket_addr = SocketAddr::try_from(socket_addr).expect("failed to parse socket address"); | |
28 //! let socket = socket_addr.bind().expect("failed to bind socket"); | |
29 //! | |
30 //! loop { | |
31 //! let _ = socket | |
32 //! .accept() | |
33 //! .expect("failed to accept connection") | |
34 //! .0 | |
35 //! .write_all(b"Hello world!") | |
36 //! .map_err(|err| eprintln!("Failed to send {}", err)); | |
37 //! } | |
38 //! ``` | |
39 //! | |
40 //! ## Features | |
41 //! | |
42 //! * `serde` - implements `serde::Deserialize` for `SocketAddr` | |
43 //! * `parse_arg` - implements `parse_arg::ParseArg` for `SocketAddr` | |
44 //! * `tokio_0_2` - adds `bind_tokio_0_2` convenience method to `SocketAddr` | |
45 //! * `tokio_0_3` - adds `bind_tokio_0_3` convenience method to `SocketAddr` | |
46 //! * `async_std` - adds `bind_async_std` convenience method to `SocketAddr` | |
3
0edcde404b02
Added information about MSRV
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
2
diff
changeset
|
47 //! |
0edcde404b02
Added information about MSRV
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
2
diff
changeset
|
48 //! ## MSRV |
0edcde404b02
Added information about MSRV
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
2
diff
changeset
|
49 //! |
0edcde404b02
Added information about MSRV
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
2
diff
changeset
|
50 //! This crate must always compile with the latest Rust available in the latest Debian stable. |
0edcde404b02
Added information about MSRV
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
2
diff
changeset
|
51 //! That is currently Rust 1.41.1. (Debian 10 - Buster) |
0edcde404b02
Added information about MSRV
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
2
diff
changeset
|
52 |
0 | 53 |
54 #![deny(missing_docs)] | |
55 | |
56 pub mod error; | |
57 | |
58 use std::convert::{TryFrom, TryInto}; | |
59 use std::fmt; | |
60 use std::ffi::{OsStr, OsString}; | |
61 use crate::error::*; | |
62 | |
63 pub(crate) mod systemd_sockets { | |
64 use std::fmt; | |
65 use std::sync::Mutex; | |
66 use libsystemd::activation::FileDescriptor; | |
67 use libsystemd::errors::Error as LibSystemdError; | |
68 use libsystemd::errors::Result as LibSystemdResult; | |
69 | |
70 #[derive(Debug)] | |
71 pub(crate) struct Error(&'static Mutex<LibSystemdError>); | |
72 | |
73 impl fmt::Display for Error { | |
74 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
75 fmt::Display::fmt(&*self.0.lock().expect("mutex poisoned"), f) | |
76 } | |
77 } | |
78 | |
79 // No source we can't keep the mutex locked | |
80 impl std::error::Error for Error {} | |
81 | |
82 pub(crate) fn take(name: &str) -> Result<Option<FileDescriptor>, Error> { | |
83 match &*SYSTEMD_SOCKETS { | |
84 Ok(sockets) => Ok(sockets.take(name)), | |
85 Err(error) => Err(Error(error)) | |
86 } | |
87 } | |
88 | |
89 struct SystemdSockets(std::sync::Mutex<std::collections::HashMap<String, FileDescriptor>>); | |
90 | |
91 impl SystemdSockets { | |
92 fn new() -> LibSystemdResult<Self> { | |
93 // MUST BE true FOR SAFETY!!! | |
94 let map = libsystemd::activation::receive_descriptors_with_names(/*unset env = */ true)?.into_iter().map(|(fd, name)| (name, fd)).collect(); | |
95 Ok(SystemdSockets(Mutex::new(map))) | |
96 } | |
97 | |
98 fn take(&self, name: &str) -> Option<FileDescriptor> { | |
99 // MUST remove THE SOCKET FOR SAFETY!!! | |
100 self.0.lock().expect("poisoned mutex").remove(name) | |
101 } | |
102 } | |
103 | |
104 lazy_static::lazy_static! { | |
105 // We don't panic in order to let the application handle the error later | |
106 static ref SYSTEMD_SOCKETS: Result<SystemdSockets, Mutex<LibSystemdError>> = SystemdSockets::new().map_err(Mutex::new); | |
107 } | |
108 } | |
109 | |
110 /// Socket address that can be an ordinary address or a systemd socket | |
111 /// | |
112 /// This is the core type of this crate that abstracts possible addresses. | |
113 /// It can be (fallibly) converted from various types of strings or deserialized with `serde`. | |
114 /// After it's created, it can be bound as `TcpListener` from `std` or even `tokio` or `async_std` | |
115 /// if the appropriate feature is enabled. | |
116 /// | |
117 /// Optional dependencies on `parse_arg` and `serde` make it trivial to use with | |
118 /// [`configure_me`](https://crates.io/crates/configure_me). | |
119 #[derive(Debug)] | |
120 #[cfg_attr(feature = "serde", derive(serde_crate::Deserialize), serde(crate = "serde_crate", try_from = "serde_str_helpers::DeserBorrowStr"))] | |
121 pub struct SocketAddr(SocketAddrInner); | |
122 | |
123 impl SocketAddr { | |
124 /// Creates `std::net::TcpListener` | |
125 /// | |
126 /// This method either `binds` the socket, if the address was provided or uses systemd socket | |
127 /// if the socket name was provided. | |
128 pub fn bind(self) -> Result<std::net::TcpListener, BindError> { | |
129 self._bind().map(|(socket, _)| socket) | |
130 } | |
131 | |
132 /// Creates `tokio::net::TcpListener` | |
133 /// | |
134 /// To be specific, it binds the socket and converts it to `tokio` 0.2 socket. | |
135 /// | |
136 /// This method either `binds` the socket, if the address was provided or uses systemd socket | |
137 /// if the socket name was provided. | |
138 #[cfg(feature = "tokio_0_2")] | |
139 pub fn bind_tokio_0_2(self) -> Result<tokio_0_2::net::TcpListener, TokioBindError> { | |
140 let (socket, addr) = self._bind()?; | |
141 socket.try_into().map_err(|error| TokioConversionError { addr, error, }.into()) | |
142 } | |
143 | |
144 /// Creates `tokio::net::TcpListener` | |
145 /// | |
146 /// To be specific, it binds the socket and converts it to `tokio` 0.3 socket. | |
147 /// | |
148 /// This method either `binds` the socket, if the address was provided or uses systemd socket | |
149 /// if the socket name was provided. | |
150 #[cfg(feature = "tokio_0_3")] | |
151 pub fn bind_tokio_0_3(self) -> Result<tokio_0_3::net::TcpListener, TokioBindError> { | |
152 let (socket, addr) = self._bind()?; | |
153 socket.try_into().map_err(|error| TokioConversionError { addr, error, }.into()) | |
154 } | |
155 | |
156 /// Creates `async_std::net::TcpListener` | |
157 /// | |
158 /// To be specific, it binds the socket and converts it to `async_std` socket. | |
159 /// | |
160 /// This method either `binds` the socket, if the address was provided or uses systemd socket | |
161 /// if the socket name was provided. | |
162 #[cfg(feature = "async-std")] | |
163 pub fn bind_async_std(self) -> Result<async_std::net::TcpListener, BindError> { | |
164 let (socket, _) = self._bind()?; | |
165 Ok(socket.into()) | |
166 } | |
167 | |
168 // We can't impl<T: Deref<Target=str> + Into<String>> TryFrom<T> for SocketAddr because of orphan | |
169 // rules. | |
170 fn try_from_generic<'a, T>(string: T) -> Result<Self, ParseError> where T: 'a + std::ops::Deref<Target=str> + Into<String> { | |
171 if string.starts_with(SYSTEMD_PREFIX) { | |
2
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
172 let name_len = string.len() - SYSTEMD_PREFIX.len(); |
0 | 173 match string[SYSTEMD_PREFIX.len()..].chars().enumerate().find(|(_, c)| !c.is_ascii() || *c < ' ' || *c == ':') { |
2
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
174 None if name_len <= 255 => Ok(SocketAddr(SocketAddrInner::Systemd(string.into()))), |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
175 None => Err(ParseErrorInner::LongSocketName { string: string.into(), len: name_len }.into()), |
0 | 176 Some((pos, c)) => Err(ParseErrorInner::InvalidCharacter { string: string.into(), c, pos, }.into()), |
177 } | |
178 } else { | |
179 Ok(string.parse().map(SocketAddrInner::Ordinary).map(SocketAddr).map_err(ParseErrorInner::SocketAddr)?) | |
180 } | |
181 } | |
182 | |
183 fn _bind(self) -> Result<(std::net::TcpListener, SocketAddrInner), BindError> { | |
184 match self.0 { | |
185 SocketAddrInner::Ordinary(addr) => match std::net::TcpListener::bind(addr) { | |
186 Ok(socket) => Ok((socket, SocketAddrInner::Ordinary(addr))), | |
187 Err(error) => Err(BindErrorInner::BindFailed { addr, error, }.into()), | |
188 }, | |
189 SocketAddrInner::Systemd(socket_name) => { | |
190 use libsystemd::activation::IsType; | |
191 use std::os::unix::io::{FromRawFd, IntoRawFd}; | |
192 | |
193 let socket = systemd_sockets::take(&socket_name[SYSTEMD_PREFIX.len()..]).map_err(BindErrorInner::ReceiveDescriptors)?; | |
194 // Safety: The environment variable is unset, so that no other calls can get the | |
195 // descriptors. The descriptors are taken from the map, not cloned, so they can't | |
196 // be duplicated. | |
197 unsafe { | |
198 // match instead of combinators to avoid cloning socket_name | |
199 match socket { | |
200 Some(socket) if socket.is_inet() => Ok((std::net::TcpListener::from_raw_fd(socket.into_raw_fd()), SocketAddrInner::Systemd(socket_name))), | |
201 Some(_) => Err(BindErrorInner::NotInetSocket(socket_name).into()), | |
202 None => Err(BindErrorInner::MissingDescriptor(socket_name).into()) | |
203 } | |
204 } | |
205 }, | |
206 } | |
207 } | |
208 } | |
209 | |
210 /// Displays the address in format that can be parsed again. | |
211 /// | |
212 /// **Important: While I don't expect this impl to change, don't rely on it!** | |
213 /// It should be used mostly for debugging/logging. | |
214 impl fmt::Display for SocketAddr { | |
215 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
216 fmt::Display::fmt(&self.0, f) | |
217 } | |
218 } | |
219 | |
220 impl fmt::Display for SocketAddrInner { | |
221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
222 match self { | |
223 SocketAddrInner::Ordinary(addr) => fmt::Display::fmt(addr, f), | |
224 SocketAddrInner::Systemd(addr) => fmt::Display::fmt(addr, f), | |
225 } | |
226 } | |
227 } | |
228 | |
229 // PartialEq for testing, I'm not convinced it should be exposed | |
230 #[derive(Debug, PartialEq)] | |
231 enum SocketAddrInner { | |
232 Ordinary(std::net::SocketAddr), | |
233 Systemd(String), | |
234 } | |
235 | |
236 const SYSTEMD_PREFIX: &str = "systemd://"; | |
237 | |
238 impl std::str::FromStr for SocketAddr { | |
239 type Err = ParseError; | |
240 | |
241 fn from_str(s: &str) -> Result<Self, Self::Err> { | |
242 SocketAddr::try_from_generic(s) | |
243 } | |
244 } | |
245 | |
246 impl<'a> TryFrom<&'a str> for SocketAddr { | |
247 type Error = ParseError; | |
248 | |
249 fn try_from(s: &'a str) -> Result<Self, Self::Error> { | |
250 SocketAddr::try_from_generic(s) | |
251 } | |
252 } | |
253 | |
254 impl TryFrom<String> for SocketAddr { | |
255 type Error = ParseError; | |
256 | |
257 fn try_from(s: String) -> Result<Self, Self::Error> { | |
258 SocketAddr::try_from_generic(s) | |
259 } | |
260 } | |
261 | |
262 impl<'a> TryFrom<&'a OsStr> for SocketAddr { | |
263 type Error = ParseOsStrError; | |
264 | |
265 fn try_from(s: &'a OsStr) -> Result<Self, Self::Error> { | |
266 s.to_str().ok_or(ParseOsStrError::InvalidUtf8)?.try_into().map_err(Into::into) | |
267 } | |
268 } | |
269 | |
270 impl TryFrom<OsString> for SocketAddr { | |
271 type Error = ParseOsStrError; | |
272 | |
273 fn try_from(s: OsString) -> Result<Self, Self::Error> { | |
274 s.into_string().map_err(|_| ParseOsStrError::InvalidUtf8)?.try_into().map_err(Into::into) | |
275 } | |
276 } | |
277 | |
278 #[cfg(feature = "serde")] | |
279 impl<'a> TryFrom<serde_str_helpers::DeserBorrowStr<'a>> for SocketAddr { | |
280 type Error = ParseError; | |
281 | |
282 fn try_from(s: serde_str_helpers::DeserBorrowStr<'a>) -> Result<Self, Self::Error> { | |
283 SocketAddr::try_from_generic(std::borrow::Cow::from(s)) | |
284 } | |
285 } | |
286 | |
287 #[cfg(feature = "parse_arg")] | |
288 impl parse_arg::ParseArg for SocketAddr { | |
289 type Error = ParseOsStrError; | |
290 | |
291 fn describe_type<W: fmt::Write>(mut writer: W) -> fmt::Result { | |
292 std::net::SocketAddr::describe_type(&mut writer)?; | |
293 write!(writer, " or a systemd socket name prefixed with systemd://") | |
294 } | |
295 | |
296 fn parse_arg(arg: &OsStr) -> Result<Self, Self::Error> { | |
297 arg.try_into() | |
298 } | |
299 | |
300 fn parse_owned_arg(arg: OsString) -> Result<Self, Self::Error> { | |
301 arg.try_into() | |
302 } | |
303 } | |
304 | |
305 #[cfg(test)] | |
306 mod tests { | |
307 use super::{SocketAddr, SocketAddrInner}; | |
308 | |
309 #[test] | |
310 fn parse_ordinary() { | |
311 assert_eq!("127.0.0.1:42".parse::<SocketAddr>().unwrap().0, SocketAddrInner::Ordinary(([127, 0, 0, 1], 42).into())); | |
312 } | |
313 | |
314 #[test] | |
315 fn parse_systemd() { | |
316 assert_eq!("systemd://foo".parse::<SocketAddr>().unwrap().0, SocketAddrInner::Systemd("systemd://foo".to_owned())); | |
317 } | |
2
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
318 |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
319 #[test] |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
320 #[should_panic] |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
321 fn parse_systemd_fail_control() { |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
322 "systemd://foo\n".parse::<SocketAddr>().unwrap(); |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
323 } |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
324 |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
325 #[test] |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
326 #[should_panic] |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
327 fn parse_systemd_fail_colon() { |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
328 "systemd://foo:".parse::<SocketAddr>().unwrap(); |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
329 } |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
330 |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
331 #[test] |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
332 #[should_panic] |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
333 fn parse_systemd_fail_non_ascii() { |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
334 "systemd://fooĆ”".parse::<SocketAddr>().unwrap(); |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
335 } |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
336 |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
337 #[test] |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
338 #[should_panic] |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
339 fn parse_systemd_fail_too_long() { |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
340 "systemd://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".parse::<SocketAddr>().unwrap(); |
cabc4aafdd85
Added length check and a few tests
Martin Habovstiak <martin.habovstiak@gmail.com>
parents:
0
diff
changeset
|
341 } |
0 | 342 } |