2020-04-17 12:11:25 +00:00
|
|
|
use anyhow::{bail, format_err, Error};
|
2019-04-08 15:59:39 +00:00
|
|
|
|
2020-11-02 09:12:56 +00:00
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::os::unix::io::AsRawFd;
|
2022-04-06 14:55:39 +00:00
|
|
|
use std::path::{Path, PathBuf};
|
2020-11-02 09:12:56 +00:00
|
|
|
use std::sync::Arc;
|
2019-04-08 15:59:39 +00:00
|
|
|
|
2020-11-02 09:12:56 +00:00
|
|
|
use futures::*;
|
2019-04-11 08:51:59 +00:00
|
|
|
use nix::sys::socket;
|
2021-09-21 05:58:40 +00:00
|
|
|
use nix::unistd::Gid;
|
2022-04-06 14:55:39 +00:00
|
|
|
use serde::Serialize;
|
|
|
|
use serde_json::Value;
|
|
|
|
use tokio::net::UnixListener;
|
2019-04-08 15:59:39 +00:00
|
|
|
|
2021-09-21 05:58:40 +00:00
|
|
|
// Listens on a Unix Socket to handle simple command asynchronously
|
2022-04-06 14:55:39 +00:00
|
|
|
fn create_control_socket<P, F>(
|
|
|
|
path: P,
|
|
|
|
gid: Gid,
|
|
|
|
func: F,
|
|
|
|
) -> Result<impl Future<Output = ()>, Error>
|
2019-08-23 13:00:18 +00:00
|
|
|
where
|
|
|
|
P: Into<PathBuf>,
|
|
|
|
F: Fn(Value) -> Result<Value, Error> + Send + Sync + 'static,
|
2019-04-08 15:59:39 +00:00
|
|
|
{
|
|
|
|
let path: PathBuf = path.into();
|
2019-04-09 09:47:23 +00:00
|
|
|
|
2021-09-21 05:58:40 +00:00
|
|
|
let gid = gid.as_raw();
|
2020-05-07 06:24:48 +00:00
|
|
|
|
2020-12-04 10:53:34 +00:00
|
|
|
let socket = UnixListener::bind(&path)?;
|
2019-04-08 15:59:39 +00:00
|
|
|
|
2019-12-12 14:27:07 +00:00
|
|
|
let func = Arc::new(func);
|
2019-04-08 15:59:39 +00:00
|
|
|
|
2019-12-12 14:27:07 +00:00
|
|
|
let control_future = async move {
|
|
|
|
loop {
|
2020-05-07 06:24:48 +00:00
|
|
|
let (conn, _addr) = match socket.accept().await {
|
|
|
|
Ok(data) => data,
|
|
|
|
Err(err) => {
|
|
|
|
eprintln!("failed to accept on control socket {:?}: {}", path, err);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-04-11 08:51:59 +00:00
|
|
|
let opt = socket::sockopt::PeerCredentials {};
|
2020-05-07 06:24:48 +00:00
|
|
|
let cred = match socket::getsockopt(conn.as_raw_fd(), opt) {
|
|
|
|
Ok(cred) => cred,
|
|
|
|
Err(err) => {
|
|
|
|
eprintln!("no permissions - unable to read peer credential - {}", err);
|
|
|
|
continue;
|
2019-04-11 08:51:59 +00:00
|
|
|
}
|
2020-05-07 06:24:48 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
// check permissions (same gid, root user, or backup group)
|
|
|
|
let mygid = unsafe { libc::getgid() };
|
2021-09-21 05:58:40 +00:00
|
|
|
if !(cred.uid() == 0 || cred.gid() == mygid || cred.gid() == gid) {
|
2020-05-07 06:24:48 +00:00
|
|
|
eprintln!("no permissions for {:?}", cred);
|
|
|
|
continue;
|
2019-04-11 08:51:59 +00:00
|
|
|
}
|
2019-04-08 15:59:39 +00:00
|
|
|
|
2019-12-12 14:27:07 +00:00
|
|
|
let (rx, mut tx) = tokio::io::split(conn);
|
2019-04-08 15:59:39 +00:00
|
|
|
|
2019-08-23 13:00:18 +00:00
|
|
|
let abort_future = super::last_worker_future().map(|_| ());
|
|
|
|
|
|
|
|
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
2019-12-12 14:27:07 +00:00
|
|
|
let func = Arc::clone(&func);
|
|
|
|
let path = path.clone();
|
2022-04-06 14:55:39 +00:00
|
|
|
tokio::spawn(
|
|
|
|
futures::future::select(
|
|
|
|
async move {
|
|
|
|
let mut rx = tokio::io::BufReader::new(rx);
|
|
|
|
let mut line = String::new();
|
|
|
|
loop {
|
|
|
|
line.clear();
|
|
|
|
match rx
|
|
|
|
.read_line({
|
|
|
|
line.clear();
|
|
|
|
&mut line
|
|
|
|
})
|
|
|
|
.await
|
|
|
|
{
|
|
|
|
Ok(0) => break,
|
|
|
|
Ok(_) => (),
|
|
|
|
Err(err) => {
|
|
|
|
eprintln!("control socket {:?} read error: {}", path, err);
|
|
|
|
return;
|
|
|
|
}
|
2019-08-23 13:00:18 +00:00
|
|
|
}
|
2019-04-08 15:59:39 +00:00
|
|
|
|
2022-04-06 14:55:39 +00:00
|
|
|
let response = match line.parse::<Value>() {
|
|
|
|
Ok(param) => match func(param) {
|
|
|
|
Ok(res) => format!("OK: {}\n", res),
|
|
|
|
Err(err) => format!("ERROR: {}\n", err),
|
|
|
|
},
|
2019-08-23 13:00:18 +00:00
|
|
|
Err(err) => format!("ERROR: {}\n", err),
|
2022-04-06 14:55:39 +00:00
|
|
|
};
|
2019-08-23 13:00:18 +00:00
|
|
|
|
2022-04-06 14:55:39 +00:00
|
|
|
if let Err(err) = tx.write_all(response.as_bytes()).await {
|
|
|
|
eprintln!(
|
|
|
|
"control socket {:?} write response error: {}",
|
|
|
|
path, err
|
|
|
|
);
|
|
|
|
return;
|
|
|
|
}
|
2019-08-23 13:00:18 +00:00
|
|
|
}
|
|
|
|
}
|
2022-04-06 14:55:39 +00:00
|
|
|
.boxed(),
|
|
|
|
abort_future,
|
|
|
|
)
|
|
|
|
.map(|_| ()),
|
|
|
|
);
|
2019-12-12 14:27:07 +00:00
|
|
|
}
|
2022-04-06 14:55:39 +00:00
|
|
|
}
|
|
|
|
.boxed();
|
2019-04-08 15:59:39 +00:00
|
|
|
|
2021-09-21 05:58:40 +00:00
|
|
|
let abort_future = crate::last_worker_future().map_err(|_| {});
|
2022-04-06 14:55:39 +00:00
|
|
|
let task = futures::future::select(control_future, abort_future)
|
|
|
|
.map(|_: futures::future::Either<(Result<(), Error>, _), _>| ());
|
2019-04-08 15:59:39 +00:00
|
|
|
|
|
|
|
Ok(task)
|
|
|
|
}
|
2019-04-10 10:42:24 +00:00
|
|
|
|
2021-09-30 08:33:57 +00:00
|
|
|
/// Send a command to the specified socket
|
2021-05-11 13:53:59 +00:00
|
|
|
pub async fn send_command<P, T>(path: P, params: &T) -> Result<Value, Error>
|
|
|
|
where
|
|
|
|
P: AsRef<Path>,
|
|
|
|
T: ?Sized + Serialize,
|
2019-04-10 10:42:24 +00:00
|
|
|
{
|
2021-05-11 13:53:59 +00:00
|
|
|
let mut command_string = serde_json::to_string(params)?;
|
|
|
|
command_string.push('\n');
|
|
|
|
send_raw_command(path.as_ref(), &command_string).await
|
|
|
|
}
|
2019-04-10 10:42:24 +00:00
|
|
|
|
2021-09-30 08:33:57 +00:00
|
|
|
/// Send a raw command (string) to the specified socket
|
2021-05-11 13:53:59 +00:00
|
|
|
pub async fn send_raw_command<P>(path: P, command_string: &str) -> Result<Value, Error>
|
|
|
|
where
|
|
|
|
P: AsRef<Path>,
|
|
|
|
{
|
|
|
|
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
2019-08-23 13:00:18 +00:00
|
|
|
|
2021-05-11 13:53:59 +00:00
|
|
|
let mut conn = tokio::net::UnixStream::connect(path)
|
|
|
|
.map_err(move |err| format_err!("control socket connect failed - {}", err))
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
conn.write_all(command_string.as_bytes()).await?;
|
|
|
|
if !command_string.as_bytes().ends_with(b"\n") {
|
|
|
|
conn.write_all(b"\n").await?;
|
|
|
|
}
|
|
|
|
|
|
|
|
AsyncWriteExt::shutdown(&mut conn).await?;
|
|
|
|
let mut rx = tokio::io::BufReader::new(conn);
|
|
|
|
let mut data = String::new();
|
|
|
|
if rx.read_line(&mut data).await? == 0 {
|
|
|
|
bail!("no response");
|
|
|
|
}
|
|
|
|
if let Some(res) = data.strip_prefix("OK: ") {
|
|
|
|
match res.parse::<Value>() {
|
|
|
|
Ok(v) => Ok(v),
|
|
|
|
Err(err) => bail!("unable to parse json response - {}", err),
|
|
|
|
}
|
|
|
|
} else if let Some(err) = data.strip_prefix("ERROR: ") {
|
|
|
|
bail!("{}", err);
|
|
|
|
} else {
|
|
|
|
bail!("unable to parse response: {}", data);
|
|
|
|
}
|
2019-04-10 10:42:24 +00:00
|
|
|
}
|
2020-11-02 09:12:56 +00:00
|
|
|
|
2021-09-30 08:33:57 +00:00
|
|
|
// A callback for a specific commando socket.
|
2022-04-06 14:55:39 +00:00
|
|
|
type CommandSocketFn =
|
|
|
|
Box<(dyn Fn(Option<&Value>) -> Result<Value, Error> + Send + Sync + 'static)>;
|
2020-11-02 09:12:56 +00:00
|
|
|
|
2021-09-30 08:33:57 +00:00
|
|
|
/// Tooling to get a single control command socket where one can
|
|
|
|
/// register multiple commands dynamically.
|
|
|
|
///
|
2021-09-30 10:31:38 +00:00
|
|
|
/// The socket is activated by calling [spawn](CommandSocket::spawn),
|
|
|
|
/// which spawns an async tokio task to process the commands.
|
|
|
|
pub struct CommandSocket {
|
2020-11-02 09:12:56 +00:00
|
|
|
socket: PathBuf,
|
2021-09-21 05:58:40 +00:00
|
|
|
gid: Gid,
|
2021-09-30 10:31:38 +00:00
|
|
|
commands: HashMap<String, CommandSocketFn>,
|
2020-11-02 09:12:56 +00:00
|
|
|
}
|
|
|
|
|
2021-09-30 10:31:38 +00:00
|
|
|
impl CommandSocket {
|
|
|
|
/// Creates a new instance.
|
2021-09-21 05:58:40 +00:00
|
|
|
pub fn new<P>(path: P, gid: Gid) -> Self
|
2022-04-06 14:55:39 +00:00
|
|
|
where
|
|
|
|
P: Into<PathBuf>,
|
2020-11-02 09:12:56 +00:00
|
|
|
{
|
2021-09-30 10:31:38 +00:00
|
|
|
CommandSocket {
|
2020-11-02 09:12:56 +00:00
|
|
|
socket: path.into(),
|
2021-09-21 05:58:40 +00:00
|
|
|
gid,
|
2020-11-02 09:12:56 +00:00
|
|
|
commands: HashMap::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Spawn the socket and consume self, meaning you cannot register commands anymore after
|
|
|
|
/// calling this.
|
|
|
|
pub fn spawn(self) -> Result<(), Error> {
|
2022-04-06 14:55:39 +00:00
|
|
|
let control_future =
|
|
|
|
create_control_socket(self.socket.to_owned(), self.gid, move |param| {
|
|
|
|
let param = param.as_object().ok_or_else(|| {
|
|
|
|
format_err!("unable to parse parameters (expected json object)")
|
|
|
|
})?;
|
|
|
|
|
|
|
|
let command = match param.get("command") {
|
|
|
|
Some(Value::String(command)) => command.as_str(),
|
|
|
|
None => bail!("no command"),
|
|
|
|
_ => bail!("unable to parse command"),
|
|
|
|
};
|
|
|
|
|
|
|
|
if !self.commands.contains_key(command) {
|
|
|
|
bail!("got unknown command '{}'", command);
|
|
|
|
}
|
2020-11-02 09:12:56 +00:00
|
|
|
|
2022-04-06 14:55:39 +00:00
|
|
|
match self.commands.get(command) {
|
|
|
|
None => bail!("got unknown command '{}'", command),
|
|
|
|
Some(handler) => {
|
|
|
|
let args = param.get("args"); //.unwrap_or(&Value::Null);
|
|
|
|
(handler)(args)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})?;
|
2020-11-02 09:12:56 +00:00
|
|
|
|
|
|
|
tokio::spawn(control_future);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Register a new command with a callback.
|
2022-04-06 14:55:39 +00:00
|
|
|
pub fn register_command<F>(&mut self, command: String, handler: F) -> Result<(), Error>
|
2020-11-02 09:12:56 +00:00
|
|
|
where
|
|
|
|
F: Fn(Option<&Value>) -> Result<Value, Error> + Send + Sync + 'static,
|
|
|
|
{
|
|
|
|
if self.commands.contains_key(&command) {
|
|
|
|
bail!("command '{}' already exists!", command);
|
|
|
|
}
|
|
|
|
|
|
|
|
self.commands.insert(command, Box::new(handler));
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|