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
//! Inter process signalling library used by `kvarnctl` to communicate with Kvarn.
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(clippy::all, clippy::pedantic)]
#![allow(clippy::missing_panics_doc)]
#[cfg(unix)]
pub mod unix {
use futures_util::FutureExt;
use log::{error, warn};
use std::future::Future;
use std::io;
use std::ops::Deref;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{UnixListener, UnixStream};
pub enum Response<T> {
/// The socket wasn't found, or had no listener.
NotFound,
/// An error occurred in reading or writing.
Error,
/// Successful transmission.
Data(T),
}
impl<D: ?Sized, T: Deref<Target = D>> Response<T> {
/// Turns `&UnixResponse<T>` to `UnixResponse<&D>`
/// where `T: Deref<Target = D>`.
/// For example, `UnixResponse<Vec<u8>>.as_deref() == &UnixResponse<&[u8]>`
pub fn as_deref(&self) -> Response<&D> {
match self {
Self::NotFound => Response::NotFound,
Self::Error => Response::Error,
Self::Data(t) => Response::Data(&**t),
}
}
}
pub struct HandlerResponse {
/// The response body.
pub data: Vec<u8>,
/// If the communication should be closed.
pub close: bool,
/// A function to run after sending the response.
pub post_send: Option<Box<dyn FnOnce() + Send + Sync>>,
}
/// Sends `data` to a [`UnixListener`] at `path`.
pub async fn send_to(data: &[u8], path: impl AsRef<Path>) -> Response<Vec<u8>> {
let path = path.as_ref();
match UnixStream::connect(path).await {
Err(err) => match err.kind() {
io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused => Response::NotFound,
_ => {
error!("Got error when trying to shut down previous instance of Kvarn: {:?}\nTrying to start server anyway.", err);
Response::Error
}
},
Ok(mut connection) => {
if let Err(err) = connection.write_all(data).await {
error!("Failed to send message! {:?}", err);
Response::Error
} else {
// Flushes the data.
connection.shutdown().await.unwrap();
let mut buf = Vec::new();
if let Err(err) = connection.read_to_end(&mut buf).await {
error!("Failed to receive message. {:?}", err);
Response::Error
} else {
Response::Data(buf)
}
}
}
}
}
/// Starts an [`UnixListener`] at `path` with `handler` receiving messages.
///
/// This starts a new task, and so the future resolves quickly.
///
/// The `handler` gets the data from the request, and should return whether to close the
/// listener and the data to send back.
///
/// `handler` is guaranteed to be inside an async Tokio context - you can use e.g. [`tokio::spawn`].
///
/// # Return value
///
/// Returns `true` if we removed an existing socket, `false` otherwise.
/// The removed socket might be live or a leftover from a previous call to this (or any other
/// UNIX socket creation).
pub async fn start_at(
handler: impl Fn(Vec<u8>) -> Pin<Box<dyn Future<Output = HandlerResponse> + Send + Sync>>
+ Send
+ Sync
+ 'static,
path: impl AsRef<Path>,
) -> bool {
let path = path.as_ref();
let overridden = tokio::fs::remove_file(path).await.is_ok();
match UnixListener::bind(path) {
Err(_err) => {}
Ok(listener) => {
tokio::spawn(async move {
let handler = Arc::new(handler);
// use a sender to poll both the listen loop and the receiver, which receives
// when the listen loop wants to break.
let (sender, mut receiver) = tokio::sync::mpsc::channel(1);
let listen_loop = Box::pin(async move {
while let Ok((mut connection, _addr)) = listener.accept().await {
let handler = Arc::clone(&handler);
let sender = sender.clone();
// spawn here so the listening isn't blocked.
tokio::spawn(async move {
let mut data = Vec::new();
if let Err(err) = connection.read_to_end(&mut data).await {
warn!("Failed on reading request: {err:?}");
return;
}
let handler = Arc::clone(&handler);
let HandlerResponse {
data,
close,
post_send,
} = handler(data).await;
if let Err(err) = connection.write_all(&data).await {
warn!("Failed to write response: {err:?}");
return;
}
if let Err(err) = connection.shutdown().await {
warn!("Failed to flush content. {:?}", err);
}
if let Some(post_send) = post_send {
(post_send)();
}
if close {
sender.send(()).await.unwrap();
}
});
}
});
let mut break_recv = Box::pin(receiver.recv().fuse());
futures_util::select! {
_ = listen_loop.fuse() => (),
_ = break_recv => (),
};
});
}
}
overridden
}
}