Mercurial > crates > systemd-socket
comparison src/lib.rs @ 28:cfef4593e207
Run `cargo fmt`.
| author | Paul Fisher <paul@pfish.zone> |
|---|---|
| date | Sat, 19 Apr 2025 01:33:50 -0400 |
| parents | 0feab4f4c2ce |
| children | efc69e99db70 |
comparison
equal
deleted
inserted
replaced
| 27:85b0f4a7303d | 28:cfef4593e207 |
|---|---|
| 1 //! A convenience crate for optionally supporting systemd socket activation. | 1 //! A convenience crate for optionally supporting systemd socket activation. |
| 2 //! | 2 //! |
| 3 //! ## About | 3 //! ## About |
| 4 //! | 4 //! |
| 5 //! **Important:** because of various reasons it is recommended to call the [`init`] function at | 5 //! **Important:** because of various reasons it is recommended to call the [`init`] function at |
| 6 //! the start of your program! | 6 //! the start of your program! |
| 7 //! | 7 //! |
| 8 //! The goal of this crate is to make socket activation with systemd in your project trivial. | 8 //! The goal of this crate is to make socket activation with systemd in your project trivial. |
| 9 //! It provides a replacement for `std::net::SocketAddr` that allows parsing the bind address from string just like the one from `std` | 9 //! It provides a replacement for `std::net::SocketAddr` that allows parsing the bind address from string just like the one from `std` |
| 10 //! but on top of that also allows `systemd://socket_name` format that tells it to use systemd activation with given socket name. | 10 //! but on top of that also allows `systemd://socket_name` format that tells it to use systemd activation with given socket name. |
| 11 //! Then it provides a method to bind the address which will return the socket from systemd if available. | 11 //! Then it provides a method to bind the address which will return the socket from systemd if available. |
| 12 //! | 12 //! |
| 17 //! You also don't need to worry about conditional compilation to ensure OS compatibility. | 17 //! You also don't need to worry about conditional compilation to ensure OS compatibility. |
| 18 //! This crate handles that for you by disabling systemd on non-linux systems. | 18 //! This crate handles that for you by disabling systemd on non-linux systems. |
| 19 //! | 19 //! |
| 20 //! Further, the crate also provides methods for binding `tokio` 1.0, 0.2, 0.3, and `async_std` sockets if the appropriate features are | 20 //! Further, the crate also provides methods for binding `tokio` 1.0, 0.2, 0.3, and `async_std` sockets if the appropriate features are |
| 21 //! activated. | 21 //! activated. |
| 22 //! | 22 //! |
| 23 //! ## Example | 23 //! ## Example |
| 24 //! | 24 //! |
| 25 //! ```no_run | 25 //! ```no_run |
| 26 //! use systemd_socket::SocketAddr; | 26 //! use systemd_socket::SocketAddr; |
| 27 //! use std::convert::TryFrom; | 27 //! use std::convert::TryFrom; |
| 28 //! use std::io::Write; | 28 //! use std::io::Write; |
| 29 //! | 29 //! |
| 30 //! systemd_socket::init().expect("Failed to initialize systemd sockets"); | 30 //! systemd_socket::init().expect("Failed to initialize systemd sockets"); |
| 31 //! let mut args = std::env::args_os(); | 31 //! let mut args = std::env::args_os(); |
| 32 //! let program_name = args.next().expect("unknown program name"); | 32 //! let program_name = args.next().expect("unknown program name"); |
| 33 //! let socket_addr = args.next().expect("missing socket address"); | 33 //! let socket_addr = args.next().expect("missing socket address"); |
| 34 //! let socket_addr = SocketAddr::try_from(socket_addr).expect("failed to parse socket address"); | 34 //! let socket_addr = SocketAddr::try_from(socket_addr).expect("failed to parse socket address"); |
| 74 //! | 74 //! |
| 75 //! This crate must always compile with the latest Rust available in the latest Debian stable. | 75 //! This crate must always compile with the latest Rust available in the latest Debian stable. |
| 76 //! That is currently Rust 1.48.0. (Debian 11 - Bullseye) | 76 //! That is currently Rust 1.48.0. (Debian 11 - Bullseye) |
| 77 | 77 |
| 78 #![cfg_attr(docsrs, feature(doc_auto_cfg))] | 78 #![cfg_attr(docsrs, feature(doc_auto_cfg))] |
| 79 | |
| 80 #![deny(missing_docs)] | 79 #![deny(missing_docs)] |
| 81 | 80 |
| 82 pub mod error; | 81 pub mod error; |
| 83 mod resolv_addr; | 82 mod resolv_addr; |
| 84 | 83 |
| 85 use std::convert::{TryFrom, TryInto}; | |
| 86 use std::fmt; | |
| 87 use std::ffi::{OsStr, OsString}; | |
| 88 use crate::error::*; | 84 use crate::error::*; |
| 89 use crate::resolv_addr::ResolvAddr; | 85 use crate::resolv_addr::ResolvAddr; |
| 86 use std::convert::{TryFrom, TryInto}; | |
| 87 use std::ffi::{OsStr, OsString}; | |
| 88 use std::fmt; | |
| 90 | 89 |
| 91 #[cfg(not(all(target_os = "linux", feature = "enable_systemd")))] | 90 #[cfg(not(all(target_os = "linux", feature = "enable_systemd")))] |
| 92 use std::convert::Infallible as Never; | 91 use std::convert::Infallible as Never; |
| 93 | 92 |
| 94 #[cfg(all(target_os = "linux", feature = "enable_systemd"))] | 93 #[cfg(all(target_os = "linux", feature = "enable_systemd"))] |
| 95 pub(crate) mod systemd_sockets { | 94 pub(crate) mod systemd_sockets { |
| 95 use libsystemd::activation::FileDescriptor; | |
| 96 use libsystemd::errors::SdError as LibSystemdError; | |
| 96 use std::fmt; | 97 use std::fmt; |
| 97 use std::sync::Mutex; | 98 use std::sync::Mutex; |
| 98 use libsystemd::activation::FileDescriptor; | |
| 99 use libsystemd::errors::SdError as LibSystemdError; | |
| 100 | 99 |
| 101 #[derive(Debug)] | 100 #[derive(Debug)] |
| 102 pub(crate) struct Error(&'static Mutex<InitError>); | 101 pub(crate) struct Error(&'static Mutex<InitError>); |
| 103 | 102 |
| 104 impl fmt::Display for Error { | 103 impl fmt::Display for Error { |
| 120 | 119 |
| 121 // No source we can't keep the mutex locked | 120 // No source we can't keep the mutex locked |
| 122 impl std::error::Error for Error {} | 121 impl std::error::Error for Error {} |
| 123 | 122 |
| 124 pub(crate) unsafe fn init(protected: bool) -> Result<(), InitError> { | 123 pub(crate) unsafe fn init(protected: bool) -> Result<(), InitError> { |
| 125 SYSTEMD_SOCKETS.get_or_try_init(|| SystemdSockets::new(protected, true).map(Ok)).map(drop) | 124 SYSTEMD_SOCKETS |
| 125 .get_or_try_init(|| SystemdSockets::new(protected, true).map(Ok)) | |
| 126 .map(drop) | |
| 126 } | 127 } |
| 127 | 128 |
| 128 pub(crate) fn take(name: &str) -> Result<Option<StoredSocket>, Error> { | 129 pub(crate) fn take(name: &str) -> Result<Option<StoredSocket>, Error> { |
| 129 let sockets = SYSTEMD_SOCKETS.get_or_init(|| SystemdSockets::new_protected(false).map_err(Mutex::new)); | 130 let sockets = SYSTEMD_SOCKETS |
| 131 .get_or_init(|| SystemdSockets::new_protected(false).map_err(Mutex::new)); | |
| 130 match sockets { | 132 match sockets { |
| 131 Ok(sockets) => Ok(sockets.take(name)), | 133 Ok(sockets) => Ok(sockets.take(name)), |
| 132 Err(error) => Err(Error(error)) | 134 Err(error) => Err(Error(error)), |
| 133 } | 135 } |
| 134 } | 136 } |
| 135 | 137 |
| 136 #[derive(Debug)] | 138 #[derive(Debug)] |
| 137 pub(crate) enum InitError { | 139 pub(crate) enum InitError { |
| 151 impl fmt::Display for InitError { | 153 impl fmt::Display for InitError { |
| 152 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | 154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 153 match self { | 155 match self { |
| 154 Self::OpenStatus(_) => write!(f, "failed to open /proc/self/status"), | 156 Self::OpenStatus(_) => write!(f, "failed to open /proc/self/status"), |
| 155 Self::ReadStatus(_) => write!(f, "failed to read /proc/self/status"), | 157 Self::ReadStatus(_) => write!(f, "failed to read /proc/self/status"), |
| 156 Self::ThreadCountNotFound => write!(f, "/proc/self/status doesn't contain Threads entry"), | 158 Self::ThreadCountNotFound => { |
| 159 write!(f, "/proc/self/status doesn't contain Threads entry") | |
| 160 } | |
| 157 Self::MultipleThreads => write!(f, "there is more than one thread running"), | 161 Self::MultipleThreads => write!(f, "there is more than one thread running"), |
| 158 // We have nothing to say about the error, let's flatten it | 162 // We have nothing to say about the error, let's flatten it |
| 159 Self::LibSystemd(error) => fmt::Display::fmt(error, f), | 163 Self::LibSystemd(error) => fmt::Display::fmt(error, f), |
| 160 } | 164 } |
| 161 } | 165 } |
| 181 impl std::convert::TryFrom<FileDescriptor> for Socket { | 185 impl std::convert::TryFrom<FileDescriptor> for Socket { |
| 182 type Error = (); | 186 type Error = (); |
| 183 | 187 |
| 184 fn try_from(value: FileDescriptor) -> Result<Self, Self::Error> { | 188 fn try_from(value: FileDescriptor) -> Result<Self, Self::Error> { |
| 185 use libsystemd::activation::IsType; | 189 use libsystemd::activation::IsType; |
| 186 use std::os::unix::io::{FromRawFd, IntoRawFd, AsRawFd}; | 190 use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd}; |
| 187 | 191 |
| 188 fn set_cloexec(fd: std::os::unix::io::RawFd) { | 192 fn set_cloexec(fd: std::os::unix::io::RawFd) { |
| 189 // SAFETY: The function is a harmless syscall | 193 // SAFETY: The function is a harmless syscall |
| 190 let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; | 194 let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; |
| 191 if flags != -1 && flags & libc::FD_CLOEXEC == 0 { | 195 if flags != -1 && flags & libc::FD_CLOEXEC == 0 { |
| 220 | 224 |
| 221 unsafe fn new(protected: bool, explicit: bool) -> Result<Self, InitError> { | 225 unsafe fn new(protected: bool, explicit: bool) -> Result<Self, InitError> { |
| 222 use std::convert::TryFrom; | 226 use std::convert::TryFrom; |
| 223 | 227 |
| 224 if explicit { | 228 if explicit { |
| 225 if std::env::var_os("LISTEN_PID").is_none() && std::env::var_os("LISTEN_FDS").is_none() && std::env::var_os("LISTEN_FDNAMES").is_none() { | 229 if std::env::var_os("LISTEN_PID").is_none() |
| 230 && std::env::var_os("LISTEN_FDS").is_none() | |
| 231 && std::env::var_os("LISTEN_FDNAMES").is_none() | |
| 232 { | |
| 226 // Systemd is not used - make the map empty | 233 // Systemd is not used - make the map empty |
| 227 return Ok(SystemdSockets(Mutex::new(Default::default()))); | 234 return Ok(SystemdSockets(Mutex::new(Default::default()))); |
| 228 } | 235 } |
| 229 } | 236 } |
| 230 | 237 |
| 231 if protected { Self::check_single_thread()? } | 238 if protected { |
| 232 // MUST BE true FOR SAFETY!!! | 239 Self::check_single_thread()? |
| 233 let map = libsystemd::activation::receive_descriptors_with_names(/*unset env = */ protected)?.into_iter().map(|(fd, name)| { | 240 } |
| 234 (name, Socket::try_from(fd)) | 241 // MUST BE true FOR SAFETY!!! |
| 235 }).collect(); | 242 let map = libsystemd::activation::receive_descriptors_with_names( |
| 243 /*unset env = */ protected, | |
| 244 )? | |
| 245 .into_iter() | |
| 246 .map(|(fd, name)| (name, Socket::try_from(fd))) | |
| 247 .collect(); | |
| 236 Ok(SystemdSockets(Mutex::new(map))) | 248 Ok(SystemdSockets(Mutex::new(map))) |
| 237 } | 249 } |
| 238 | 250 |
| 239 fn check_single_thread() -> Result<(), InitError> { | 251 fn check_single_thread() -> Result<(), InitError> { |
| 240 use std::io::BufRead; | 252 use std::io::BufRead; |
| 262 // MUST remove THE SOCKET FOR SAFETY!!! | 274 // MUST remove THE SOCKET FOR SAFETY!!! |
| 263 self.0.lock().expect("poisoned mutex").remove(name) | 275 self.0.lock().expect("poisoned mutex").remove(name) |
| 264 } | 276 } |
| 265 } | 277 } |
| 266 | 278 |
| 267 static SYSTEMD_SOCKETS: once_cell::sync::OnceCell<Result<SystemdSockets, Mutex<InitError>>> = once_cell::sync::OnceCell::new(); | 279 static SYSTEMD_SOCKETS: once_cell::sync::OnceCell<Result<SystemdSockets, Mutex<InitError>>> = |
| 280 once_cell::sync::OnceCell::new(); | |
| 268 } | 281 } |
| 269 | 282 |
| 270 /// Socket address that can be an ordinary address or a systemd socket | 283 /// Socket address that can be an ordinary address or a systemd socket |
| 271 /// | 284 /// |
| 272 /// This is the core type of this crate that abstracts possible addresses. | 285 /// This is the core type of this crate that abstracts possible addresses. |
| 275 /// if the appropriate feature is enabled. | 288 /// if the appropriate feature is enabled. |
| 276 /// | 289 /// |
| 277 /// Optional dependencies on `parse_arg` and `serde` make it trivial to use with | 290 /// Optional dependencies on `parse_arg` and `serde` make it trivial to use with |
| 278 /// [`configure_me`](https://crates.io/crates/configure_me). | 291 /// [`configure_me`](https://crates.io/crates/configure_me). |
| 279 #[derive(Debug)] | 292 #[derive(Debug)] |
| 280 #[cfg_attr(feature = "serde", derive(serde_crate::Deserialize), serde(crate = "serde_crate", try_from = "serde_str_helpers::DeserBorrowStr"))] | 293 #[cfg_attr( |
| 294 feature = "serde", | |
| 295 derive(serde_crate::Deserialize), | |
| 296 serde(crate = "serde_crate", try_from = "serde_str_helpers::DeserBorrowStr") | |
| 297 )] | |
| 281 pub struct SocketAddr(SocketAddrInner); | 298 pub struct SocketAddr(SocketAddrInner); |
| 282 | 299 |
| 283 impl SocketAddr { | 300 impl SocketAddr { |
| 284 /// Creates SocketAddr from systemd name directly, without requiring `systemd://` prefix. | 301 /// Creates SocketAddr from systemd name directly, without requiring `systemd://` prefix. |
| 285 /// | 302 /// |
| 295 } else { | 312 } else { |
| 296 &name | 313 &name |
| 297 }; | 314 }; |
| 298 | 315 |
| 299 let name_len = real_systemd_name.len(); | 316 let name_len = real_systemd_name.len(); |
| 300 match real_systemd_name.chars().enumerate().find(|(_, c)| !c.is_ascii() || *c < ' ' || *c == ':') { | 317 match real_systemd_name |
| 318 .chars() | |
| 319 .enumerate() | |
| 320 .find(|(_, c)| !c.is_ascii() || *c < ' ' || *c == ':') | |
| 321 { | |
| 301 None if name_len <= 255 && prefixed => Ok(SocketAddr(SocketAddrInner::Systemd(name))), | 322 None if name_len <= 255 && prefixed => Ok(SocketAddr(SocketAddrInner::Systemd(name))), |
| 302 None if name_len <= 255 && !prefixed => Ok(SocketAddr(SocketAddrInner::SystemdNoPrefix(name))), | 323 None if name_len <= 255 && !prefixed => { |
| 303 None => Err(ParseErrorInner::LongSocketName { string: name, len: name_len }.into()), | 324 Ok(SocketAddr(SocketAddrInner::SystemdNoPrefix(name))) |
| 304 Some((pos, c)) => Err(ParseErrorInner::InvalidCharacter { string: name, c, pos, }.into()), | 325 } |
| 305 } | 326 None => Err(ParseErrorInner::LongSocketName { |
| 306 } | 327 string: name, |
| 307 | 328 len: name_len, |
| 329 } | |
| 330 .into()), | |
| 331 Some((pos, c)) => Err(ParseErrorInner::InvalidCharacter { | |
| 332 string: name, | |
| 333 c, | |
| 334 pos, | |
| 335 } | |
| 336 .into()), | |
| 337 } | |
| 338 } | |
| 308 | 339 |
| 309 #[cfg(not(all(target_os = "linux", feature = "enable_systemd")))] | 340 #[cfg(not(all(target_os = "linux", feature = "enable_systemd")))] |
| 310 fn inner_from_systemd_name(name: String, _prefixed: bool) -> Result<Self, ParseError> { | 341 fn inner_from_systemd_name(name: String, _prefixed: bool) -> Result<Self, ParseError> { |
| 311 Err(ParseError(ParseErrorInner::SystemdUnsupported(name))) | 342 Err(ParseError(ParseErrorInner::SystemdUnsupported(name))) |
| 312 } | 343 } |
| 317 /// if the socket name was provided. | 348 /// if the socket name was provided. |
| 318 pub fn bind(self) -> Result<std::net::TcpListener, BindError> { | 349 pub fn bind(self) -> Result<std::net::TcpListener, BindError> { |
| 319 match self.0 { | 350 match self.0 { |
| 320 SocketAddrInner::Ordinary(addr) => match std::net::TcpListener::bind(addr) { | 351 SocketAddrInner::Ordinary(addr) => match std::net::TcpListener::bind(addr) { |
| 321 Ok(socket) => Ok(socket), | 352 Ok(socket) => Ok(socket), |
| 322 Err(error) => Err(BindErrorInner::BindFailed { addr, error, }.into()), | 353 Err(error) => Err(BindErrorInner::BindFailed { addr, error }.into()), |
| 323 }, | 354 }, |
| 324 SocketAddrInner::WithHostname(addr) => match std::net::TcpListener::bind(addr.as_str()) { | 355 SocketAddrInner::WithHostname(addr) => match std::net::TcpListener::bind(addr.as_str()) |
| 356 { | |
| 325 Ok(socket) => Ok(socket), | 357 Ok(socket) => Ok(socket), |
| 326 Err(error) => Err(BindErrorInner::BindOrResolvFailed { addr, error, }.into()), | 358 Err(error) => Err(BindErrorInner::BindOrResolvFailed { addr, error }.into()), |
| 327 }, | 359 }, |
| 328 SocketAddrInner::Systemd(socket_name) => Self::get_systemd(socket_name, true).map(|(socket, _)| socket), | 360 SocketAddrInner::Systemd(socket_name) => { |
| 329 SocketAddrInner::SystemdNoPrefix(socket_name) => Self::get_systemd(socket_name, false).map(|(socket, _)| socket), | 361 Self::get_systemd(socket_name, true).map(|(socket, _)| socket) |
| 362 } | |
| 363 SocketAddrInner::SystemdNoPrefix(socket_name) => { | |
| 364 Self::get_systemd(socket_name, false).map(|(socket, _)| socket) | |
| 365 } | |
| 330 } | 366 } |
| 331 } | 367 } |
| 332 | 368 |
| 333 /// Creates `tokio::net::TcpListener` | 369 /// Creates `tokio::net::TcpListener` |
| 334 /// | 370 /// |
| 339 #[cfg(feature = "tokio")] | 375 #[cfg(feature = "tokio")] |
| 340 pub async fn bind_tokio(self) -> Result<tokio::net::TcpListener, TokioBindError> { | 376 pub async fn bind_tokio(self) -> Result<tokio::net::TcpListener, TokioBindError> { |
| 341 match self.0 { | 377 match self.0 { |
| 342 SocketAddrInner::Ordinary(addr) => match tokio::net::TcpListener::bind(addr).await { | 378 SocketAddrInner::Ordinary(addr) => match tokio::net::TcpListener::bind(addr).await { |
| 343 Ok(socket) => Ok(socket), | 379 Ok(socket) => Ok(socket), |
| 344 Err(error) => Err(TokioBindError::Bind(BindErrorInner::BindFailed { addr, error, }.into())), | 380 Err(error) => Err(TokioBindError::Bind( |
| 381 BindErrorInner::BindFailed { addr, error }.into(), | |
| 382 )), | |
| 345 }, | 383 }, |
| 346 SocketAddrInner::WithHostname(addr) => match tokio::net::TcpListener::bind(addr.as_str()).await { | 384 SocketAddrInner::WithHostname(addr) => { |
| 347 Ok(socket) => Ok(socket), | 385 match tokio::net::TcpListener::bind(addr.as_str()).await { |
| 348 Err(error) => Err(TokioBindError::Bind(BindErrorInner::BindOrResolvFailed { addr, error, }.into())), | 386 Ok(socket) => Ok(socket), |
| 349 }, | 387 Err(error) => Err(TokioBindError::Bind( |
| 388 BindErrorInner::BindOrResolvFailed { addr, error }.into(), | |
| 389 )), | |
| 390 } | |
| 391 } | |
| 350 SocketAddrInner::Systemd(socket_name) => { | 392 SocketAddrInner::Systemd(socket_name) => { |
| 351 let (socket, addr) = Self::get_systemd(socket_name, true)?; | 393 let (socket, addr) = Self::get_systemd(socket_name, true)?; |
| 352 socket.try_into().map_err(|error| TokioConversionError { addr, error, }.into()) | 394 socket |
| 353 }, | 395 .try_into() |
| 396 .map_err(|error| TokioConversionError { addr, error }.into()) | |
| 397 } | |
| 354 SocketAddrInner::SystemdNoPrefix(socket_name) => { | 398 SocketAddrInner::SystemdNoPrefix(socket_name) => { |
| 355 let (socket, addr) = Self::get_systemd(socket_name, false)?; | 399 let (socket, addr) = Self::get_systemd(socket_name, false)?; |
| 356 socket.try_into().map_err(|error| TokioConversionError { addr, error, }.into()) | 400 socket |
| 357 }, | 401 .try_into() |
| 402 .map_err(|error| TokioConversionError { addr, error }.into()) | |
| 403 } | |
| 358 } | 404 } |
| 359 } | 405 } |
| 360 | 406 |
| 361 /// Creates `tokio::net::TcpListener` | 407 /// Creates `tokio::net::TcpListener` |
| 362 /// | 408 /// |
| 365 /// This method either `binds` the socket, if the address was provided or uses systemd socket | 411 /// This method either `binds` the socket, if the address was provided or uses systemd socket |
| 366 /// if the socket name was provided. | 412 /// if the socket name was provided. |
| 367 #[cfg(feature = "tokio_0_2")] | 413 #[cfg(feature = "tokio_0_2")] |
| 368 pub async fn bind_tokio_0_2(self) -> Result<tokio_0_2::net::TcpListener, TokioBindError> { | 414 pub async fn bind_tokio_0_2(self) -> Result<tokio_0_2::net::TcpListener, TokioBindError> { |
| 369 match self.0 { | 415 match self.0 { |
| 370 SocketAddrInner::Ordinary(addr) => match tokio_0_2::net::TcpListener::bind(addr).await { | 416 SocketAddrInner::Ordinary(addr) => { |
| 371 Ok(socket) => Ok(socket), | 417 match tokio_0_2::net::TcpListener::bind(addr).await { |
| 372 Err(error) => Err(TokioBindError::Bind(BindErrorInner::BindFailed { addr, error, }.into())), | 418 Ok(socket) => Ok(socket), |
| 373 }, | 419 Err(error) => Err(TokioBindError::Bind( |
| 374 SocketAddrInner::WithHostname(addr) => match tokio_0_2::net::TcpListener::bind(addr.as_str()).await { | 420 BindErrorInner::BindFailed { addr, error }.into(), |
| 375 Ok(socket) => Ok(socket), | 421 )), |
| 376 Err(error) => Err(TokioBindError::Bind(BindErrorInner::BindOrResolvFailed { addr, error, }.into())), | 422 } |
| 377 }, | 423 } |
| 424 SocketAddrInner::WithHostname(addr) => { | |
| 425 match tokio_0_2::net::TcpListener::bind(addr.as_str()).await { | |
| 426 Ok(socket) => Ok(socket), | |
| 427 Err(error) => Err(TokioBindError::Bind( | |
| 428 BindErrorInner::BindOrResolvFailed { addr, error }.into(), | |
| 429 )), | |
| 430 } | |
| 431 } | |
| 378 SocketAddrInner::Systemd(socket_name) => { | 432 SocketAddrInner::Systemd(socket_name) => { |
| 379 let (socket, addr) = Self::get_systemd(socket_name, true)?; | 433 let (socket, addr) = Self::get_systemd(socket_name, true)?; |
| 380 socket.try_into().map_err(|error| TokioConversionError { addr, error, }.into()) | 434 socket |
| 381 }, | 435 .try_into() |
| 436 .map_err(|error| TokioConversionError { addr, error }.into()) | |
| 437 } | |
| 382 SocketAddrInner::SystemdNoPrefix(socket_name) => { | 438 SocketAddrInner::SystemdNoPrefix(socket_name) => { |
| 383 let (socket, addr) = Self::get_systemd(socket_name, false)?; | 439 let (socket, addr) = Self::get_systemd(socket_name, false)?; |
| 384 socket.try_into().map_err(|error| TokioConversionError { addr, error, }.into()) | 440 socket |
| 385 }, | 441 .try_into() |
| 442 .map_err(|error| TokioConversionError { addr, error }.into()) | |
| 443 } | |
| 386 } | 444 } |
| 387 } | 445 } |
| 388 | 446 |
| 389 /// Creates `tokio::net::TcpListener` | 447 /// Creates `tokio::net::TcpListener` |
| 390 /// | 448 /// |
| 393 /// This method either `binds` the socket, if the address was provided or uses systemd socket | 451 /// This method either `binds` the socket, if the address was provided or uses systemd socket |
| 394 /// if the socket name was provided. | 452 /// if the socket name was provided. |
| 395 #[cfg(feature = "tokio_0_3")] | 453 #[cfg(feature = "tokio_0_3")] |
| 396 pub async fn bind_tokio_0_3(self) -> Result<tokio_0_3::net::TcpListener, TokioBindError> { | 454 pub async fn bind_tokio_0_3(self) -> Result<tokio_0_3::net::TcpListener, TokioBindError> { |
| 397 match self.0 { | 455 match self.0 { |
| 398 SocketAddrInner::Ordinary(addr) => match tokio_0_3::net::TcpListener::bind(addr).await { | 456 SocketAddrInner::Ordinary(addr) => { |
| 399 Ok(socket) => Ok(socket), | 457 match tokio_0_3::net::TcpListener::bind(addr).await { |
| 400 Err(error) => Err(TokioBindError::Bind(BindErrorInner::BindFailed { addr, error, }.into())), | 458 Ok(socket) => Ok(socket), |
| 401 }, | 459 Err(error) => Err(TokioBindError::Bind( |
| 402 SocketAddrInner::WithHostname(addr) => match tokio_0_3::net::TcpListener::bind(addr.as_str()).await { | 460 BindErrorInner::BindFailed { addr, error }.into(), |
| 403 Ok(socket) => Ok(socket), | 461 )), |
| 404 Err(error) => Err(TokioBindError::Bind(BindErrorInner::BindOrResolvFailed { addr, error, }.into())), | 462 } |
| 405 }, | 463 } |
| 464 SocketAddrInner::WithHostname(addr) => { | |
| 465 match tokio_0_3::net::TcpListener::bind(addr.as_str()).await { | |
| 466 Ok(socket) => Ok(socket), | |
| 467 Err(error) => Err(TokioBindError::Bind( | |
| 468 BindErrorInner::BindOrResolvFailed { addr, error }.into(), | |
| 469 )), | |
| 470 } | |
| 471 } | |
| 406 SocketAddrInner::Systemd(socket_name) => { | 472 SocketAddrInner::Systemd(socket_name) => { |
| 407 let (socket, addr) = Self::get_systemd(socket_name, true)?; | 473 let (socket, addr) = Self::get_systemd(socket_name, true)?; |
| 408 socket.try_into().map_err(|error| TokioConversionError { addr, error, }.into()) | 474 socket |
| 409 }, | 475 .try_into() |
| 476 .map_err(|error| TokioConversionError { addr, error }.into()) | |
| 477 } | |
| 410 SocketAddrInner::SystemdNoPrefix(socket_name) => { | 478 SocketAddrInner::SystemdNoPrefix(socket_name) => { |
| 411 let (socket, addr) = Self::get_systemd(socket_name, false)?; | 479 let (socket, addr) = Self::get_systemd(socket_name, false)?; |
| 412 socket.try_into().map_err(|error| TokioConversionError { addr, error, }.into()) | 480 socket |
| 413 }, | 481 .try_into() |
| 482 .map_err(|error| TokioConversionError { addr, error }.into()) | |
| 483 } | |
| 414 } | 484 } |
| 415 } | 485 } |
| 416 | 486 |
| 417 /// Creates `async_std::net::TcpListener` | 487 /// Creates `async_std::net::TcpListener` |
| 418 /// | 488 /// |
| 421 /// This method either `binds` the socket, if the address was provided or uses systemd socket | 491 /// This method either `binds` the socket, if the address was provided or uses systemd socket |
| 422 /// if the socket name was provided. | 492 /// if the socket name was provided. |
| 423 #[cfg(feature = "async-std")] | 493 #[cfg(feature = "async-std")] |
| 424 pub async fn bind_async_std(self) -> Result<async_std::net::TcpListener, BindError> { | 494 pub async fn bind_async_std(self) -> Result<async_std::net::TcpListener, BindError> { |
| 425 match self.0 { | 495 match self.0 { |
| 426 SocketAddrInner::Ordinary(addr) => match async_std::net::TcpListener::bind(addr).await { | 496 SocketAddrInner::Ordinary(addr) => { |
| 427 Ok(socket) => Ok(socket), | 497 match async_std::net::TcpListener::bind(addr).await { |
| 428 Err(error) => Err(BindErrorInner::BindFailed { addr, error, }.into()), | 498 Ok(socket) => Ok(socket), |
| 429 }, | 499 Err(error) => Err(BindErrorInner::BindFailed { addr, error }.into()), |
| 430 SocketAddrInner::WithHostname(addr) => match async_std::net::TcpListener::bind(addr.as_str()).await { | 500 } |
| 431 Ok(socket) => Ok(socket), | 501 } |
| 432 Err(error) => Err(BindErrorInner::BindOrResolvFailed { addr, error, }.into()), | 502 SocketAddrInner::WithHostname(addr) => { |
| 433 }, | 503 match async_std::net::TcpListener::bind(addr.as_str()).await { |
| 504 Ok(socket) => Ok(socket), | |
| 505 Err(error) => Err(BindErrorInner::BindOrResolvFailed { addr, error }.into()), | |
| 506 } | |
| 507 } | |
| 434 SocketAddrInner::Systemd(socket_name) => { | 508 SocketAddrInner::Systemd(socket_name) => { |
| 435 let (socket, _) = Self::get_systemd(socket_name, true)?; | 509 let (socket, _) = Self::get_systemd(socket_name, true)?; |
| 436 Ok(socket.into()) | 510 Ok(socket.into()) |
| 437 }, | 511 } |
| 438 SocketAddrInner::SystemdNoPrefix(socket_name) => { | 512 SocketAddrInner::SystemdNoPrefix(socket_name) => { |
| 439 let (socket, _) = Self::get_systemd(socket_name, false)?; | 513 let (socket, _) = Self::get_systemd(socket_name, false)?; |
| 440 Ok(socket.into()) | 514 Ok(socket.into()) |
| 441 }, | 515 } |
| 442 } | 516 } |
| 443 } | 517 } |
| 444 | 518 |
| 445 // We can't impl<T: Deref<Target=str> + Into<String>> TryFrom<T> for SocketAddr because of orphan | 519 // We can't impl<T: Deref<Target=str> + Into<String>> TryFrom<T> for SocketAddr because of orphan |
| 446 // rules. | 520 // rules. |
| 447 fn try_from_generic<'a, T>(string: T) -> Result<Self, ParseError> where T: 'a + std::ops::Deref<Target=str> + Into<String> { | 521 fn try_from_generic<'a, T>(string: T) -> Result<Self, ParseError> |
| 522 where | |
| 523 T: 'a + std::ops::Deref<Target = str> + Into<String>, | |
| 524 { | |
| 448 if string.starts_with(SYSTEMD_PREFIX) { | 525 if string.starts_with(SYSTEMD_PREFIX) { |
| 449 Self::inner_from_systemd_name(string.into(), true) | 526 Self::inner_from_systemd_name(string.into(), true) |
| 450 } else { | 527 } else { |
| 451 match string.parse() { | 528 match string.parse() { |
| 452 Ok(addr) => Ok(SocketAddr(SocketAddrInner::Ordinary(addr))), | 529 Ok(addr) => Ok(SocketAddr(SocketAddrInner::Ordinary(addr))), |
| 453 Err(_) => Ok(SocketAddr(SocketAddrInner::WithHostname(ResolvAddr::try_from_generic(string).map_err(ParseErrorInner::ResolvAddr)?))), | 530 Err(_) => Ok(SocketAddr(SocketAddrInner::WithHostname( |
| 531 ResolvAddr::try_from_generic(string).map_err(ParseErrorInner::ResolvAddr)?, | |
| 532 ))), | |
| 454 } | 533 } |
| 455 } | 534 } |
| 456 } | 535 } |
| 457 | 536 |
| 458 #[cfg(all(target_os = "linux", feature = "enable_systemd"))] | 537 #[cfg(all(target_os = "linux", feature = "enable_systemd"))] |
| 459 fn get_systemd(socket_name: String, prefixed: bool) -> Result<(std::net::TcpListener, SocketAddrInner), BindError> { | 538 fn get_systemd( |
| 539 socket_name: String, | |
| 540 prefixed: bool, | |
| 541 ) -> Result<(std::net::TcpListener, SocketAddrInner), BindError> { | |
| 460 use systemd_sockets::Socket; | 542 use systemd_sockets::Socket; |
| 461 | 543 |
| 462 let real_systemd_name = if prefixed { | 544 let real_systemd_name = if prefixed { |
| 463 &socket_name[SYSTEMD_PREFIX.len()..] | 545 &socket_name[SYSTEMD_PREFIX.len()..] |
| 464 } else { | 546 } else { |
| 465 &socket_name | 547 &socket_name |
| 466 }; | 548 }; |
| 467 | 549 |
| 468 let socket = systemd_sockets::take(real_systemd_name).map_err(BindErrorInner::ReceiveDescriptors)?; | 550 let socket = |
| 551 systemd_sockets::take(real_systemd_name).map_err(BindErrorInner::ReceiveDescriptors)?; | |
| 469 // match instead of combinators to avoid cloning socket_name | 552 // match instead of combinators to avoid cloning socket_name |
| 470 match socket { | 553 match socket { |
| 471 Some(Ok(Socket::TcpListener(socket))) => Ok((socket, SocketAddrInner::Systemd(socket_name))), | 554 Some(Ok(Socket::TcpListener(socket))) => { |
| 555 Ok((socket, SocketAddrInner::Systemd(socket_name))) | |
| 556 } | |
| 472 Some(_) => Err(BindErrorInner::NotInetSocket(socket_name).into()), | 557 Some(_) => Err(BindErrorInner::NotInetSocket(socket_name).into()), |
| 473 None => Err(BindErrorInner::MissingDescriptor(socket_name).into()) | 558 None => Err(BindErrorInner::MissingDescriptor(socket_name).into()), |
| 474 } | 559 } |
| 475 } | 560 } |
| 476 | 561 |
| 477 // This approach makes the rest of the code much simpler as it doesn't require sprinkling it | 562 // This approach makes the rest of the code much simpler as it doesn't require sprinkling it |
| 478 // with #[cfg(all(target_os = "linux", feature = "enable_systemd"))] yet still statically guarantees it won't execute. | 563 // with #[cfg(all(target_os = "linux", feature = "enable_systemd"))] yet still statically guarantees it won't execute. |
| 479 #[cfg(not(all(target_os = "linux", feature = "enable_systemd")))] | 564 #[cfg(not(all(target_os = "linux", feature = "enable_systemd")))] |
| 480 fn get_systemd(socket_name: Never, _prefixed: bool) -> Result<(std::net::TcpListener, SocketAddrInner), BindError> { | 565 fn get_systemd( |
| 566 socket_name: Never, | |
| 567 _prefixed: bool, | |
| 568 ) -> Result<(std::net::TcpListener, SocketAddrInner), BindError> { | |
| 481 match socket_name {} | 569 match socket_name {} |
| 482 } | 570 } |
| 483 } | 571 } |
| 484 | 572 |
| 485 /// Initializes the library while there's only a single thread. | 573 /// Initializes the library while there's only a single thread. |
| 513 /// is unsound, the library has some protections against double close. However these protections | 601 /// is unsound, the library has some protections against double close. However these protections |
| 514 /// come with the limitation that the library must be initailized with a single thread. | 602 /// come with the limitation that the library must be initailized with a single thread. |
| 515 /// | 603 /// |
| 516 /// If for any reason you're unable to call `init` in a single thread at around the top of `main` | 604 /// If for any reason you're unable to call `init` in a single thread at around the top of `main` |
| 517 /// (and this should be almost never) you may call this method if you've ensured that no other part | 605 /// (and this should be almost never) you may call this method if you've ensured that no other part |
| 518 /// of your codebase is operating on systemd-provided file descriptors stored in the environment | 606 /// of your codebase is operating on systemd-provided file descriptors stored in the environment |
| 519 /// variables. | 607 /// variables. |
| 520 /// | 608 /// |
| 521 /// Note however that doing so uncovers another problem: if another thread forks and execs the | 609 /// Note however that doing so uncovers another problem: if another thread forks and execs the |
| 522 /// systemd file descriptors will get passed into that program! In such case you somehow need to | 610 /// systemd file descriptors will get passed into that program! In such case you somehow need to |
| 523 /// clean up the file descriptors yourself. | 611 /// clean up the file descriptors yourself. |
| 623 | 711 |
| 624 impl<'a> TryFrom<&'a OsStr> for SocketAddr { | 712 impl<'a> TryFrom<&'a OsStr> for SocketAddr { |
| 625 type Error = ParseOsStrError; | 713 type Error = ParseOsStrError; |
| 626 | 714 |
| 627 fn try_from(s: &'a OsStr) -> Result<Self, Self::Error> { | 715 fn try_from(s: &'a OsStr) -> Result<Self, Self::Error> { |
| 628 s.to_str().ok_or(ParseOsStrError::InvalidUtf8)?.try_into().map_err(Into::into) | 716 s.to_str() |
| 717 .ok_or(ParseOsStrError::InvalidUtf8)? | |
| 718 .try_into() | |
| 719 .map_err(Into::into) | |
| 629 } | 720 } |
| 630 } | 721 } |
| 631 | 722 |
| 632 impl TryFrom<OsString> for SocketAddr { | 723 impl TryFrom<OsString> for SocketAddr { |
| 633 type Error = ParseOsStrError; | 724 type Error = ParseOsStrError; |
| 634 | 725 |
| 635 fn try_from(s: OsString) -> Result<Self, Self::Error> { | 726 fn try_from(s: OsString) -> Result<Self, Self::Error> { |
| 636 s.into_string().map_err(|_| ParseOsStrError::InvalidUtf8)?.try_into().map_err(Into::into) | 727 s.into_string() |
| 728 .map_err(|_| ParseOsStrError::InvalidUtf8)? | |
| 729 .try_into() | |
| 730 .map_err(Into::into) | |
| 637 } | 731 } |
| 638 } | 732 } |
| 639 | 733 |
| 640 #[cfg(feature = "serde")] | 734 #[cfg(feature = "serde")] |
| 641 impl<'a> TryFrom<serde_str_helpers::DeserBorrowStr<'a>> for SocketAddr { | 735 impl<'a> TryFrom<serde_str_helpers::DeserBorrowStr<'a>> for SocketAddr { |
| 668 mod tests { | 762 mod tests { |
| 669 use super::{SocketAddr, SocketAddrInner}; | 763 use super::{SocketAddr, SocketAddrInner}; |
| 670 | 764 |
| 671 #[test] | 765 #[test] |
| 672 fn parse_ordinary() { | 766 fn parse_ordinary() { |
| 673 assert_eq!("127.0.0.1:42".parse::<SocketAddr>().unwrap().0, SocketAddrInner::Ordinary(([127, 0, 0, 1], 42).into())); | 767 assert_eq!( |
| 768 "127.0.0.1:42".parse::<SocketAddr>().unwrap().0, | |
| 769 SocketAddrInner::Ordinary(([127, 0, 0, 1], 42).into()) | |
| 770 ); | |
| 674 } | 771 } |
| 675 | 772 |
| 676 #[test] | 773 #[test] |
| 677 #[cfg(all(target_os = "linux", feature = "enable_systemd"))] | 774 #[cfg(all(target_os = "linux", feature = "enable_systemd"))] |
| 678 fn parse_systemd() { | 775 fn parse_systemd() { |
| 679 assert_eq!("systemd://foo".parse::<SocketAddr>().unwrap().0, SocketAddrInner::Systemd("systemd://foo".to_owned())); | 776 assert_eq!( |
| 777 "systemd://foo".parse::<SocketAddr>().unwrap().0, | |
| 778 SocketAddrInner::Systemd("systemd://foo".to_owned()) | |
| 779 ); | |
| 680 } | 780 } |
| 681 | 781 |
| 682 #[test] | 782 #[test] |
| 683 #[cfg(not(all(target_os = "linux", feature = "enable_systemd")))] | 783 #[cfg(not(all(target_os = "linux", feature = "enable_systemd")))] |
| 684 #[should_panic] | 784 #[should_panic] |
| 709 fn parse_systemd_fail_too_long() { | 809 fn parse_systemd_fail_too_long() { |
| 710 "systemd://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".parse::<SocketAddr>().unwrap(); | 810 "systemd://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".parse::<SocketAddr>().unwrap(); |
| 711 } | 811 } |
| 712 | 812 |
| 713 #[test] | 813 #[test] |
| 714 #[cfg_attr(not(all(target_os = "linux", feature = "enable_systemd")), should_panic)] | 814 #[cfg_attr( |
| 815 not(all(target_os = "linux", feature = "enable_systemd")), | |
| 816 should_panic | |
| 817 )] | |
| 715 fn no_prefix_parse_systemd() { | 818 fn no_prefix_parse_systemd() { |
| 716 SocketAddr::from_systemd_name("foo").unwrap(); | 819 SocketAddr::from_systemd_name("foo").unwrap(); |
| 717 } | 820 } |
| 718 | 821 |
| 719 #[test] | 822 #[test] |
