Tunal/crates/tunal-elevate/src/protocol.rs
astar76 4920193095 S016: root operations through a pkexec helper
Helper mode tunal --elevated-helper over a framed stdin/stdout protocol,
pkexec launcher, ElevatedLocal backend, per-job-thread Elevation for the
job engine, Retry as administrator in the error dialog, polkit policy and
a helper smoke example.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 20:29:25 -06:00

310 lines
8.1 KiB
Rust

//! Wire format between Tunal and its root helper: frames of `u32` big-endian length,
//! one kind byte, then either a JSON message or raw file data.
use std::io::{self, Read, Write};
use std::time::{Duration, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use tunal_core::{Entry, Error, FileType, Kind, display_name, mime};
/// Bumped on any incompatible change; both sides must agree in the handshake.
pub const VERSION: u32 = 1;
/// Largest frame either side accepts.
const MAX_FRAME: usize = 16 << 20;
/// Bytes per data frame.
pub const CHUNK: usize = 256 << 10;
const MESSAGE: u8 = 0;
const DATA: u8 = 1;
/// Paths are raw absolute path bytes.
#[derive(Debug, Serialize, Deserialize)]
pub enum Request {
Hello {
version: u32,
},
Stat {
path: Vec<u8>,
},
List {
path: Vec<u8>,
},
OpenRead {
path: Vec<u8>,
},
OpenWrite {
path: Vec<u8>,
create_new: bool,
},
/// Reply: one data frame, empty at end of file.
Read {
handle: u64,
},
/// Followed by one data frame.
Write {
handle: u64,
},
Close {
handle: u64,
},
/// Copies one file inside the helper, with `Progress` replies.
Copy {
from: Vec<u8>,
to: Vec<u8>,
create_new: bool,
},
Mkdir {
path: Vec<u8>,
},
/// Also moves within one filesystem.
Rename {
from: Vec<u8>,
to: Vec<u8>,
},
Delete {
path: Vec<u8>,
},
Symlink {
link: Vec<u8>,
target: Vec<u8>,
},
}
#[derive(Debug, Serialize, Deserialize)]
pub enum Reply {
Hello {
version: u32,
},
Done,
Entry(WireEntry),
/// One chunk of a listing; `Done` ends it.
Entries(Vec<WireEntry>),
Handle(u64),
/// Bytes copied so far.
Progress(u64),
Error(WireError),
}
/// `tunal_core::Error` on the wire.
#[derive(Debug, Serialize, Deserialize)]
pub enum WireError {
NotFound,
PermissionDenied,
Exists,
NotEmpty,
Unsupported,
Cancelled,
Io(String),
Remote(String),
}
impl From<Error> for WireError {
fn from(e: Error) -> Self {
match e {
Error::NotFound => Self::NotFound,
Error::PermissionDenied => Self::PermissionDenied,
Error::Exists => Self::Exists,
Error::NotEmpty => Self::NotEmpty,
Error::Unsupported => Self::Unsupported,
Error::Cancelled => Self::Cancelled,
Error::Io(m) => Self::Io(m),
Error::Remote(m) => Self::Remote(m),
}
}
}
impl From<WireError> for Error {
fn from(e: WireError) -> Self {
match e {
WireError::NotFound => Self::NotFound,
WireError::PermissionDenied => Self::PermissionDenied,
WireError::Exists => Self::Exists,
WireError::NotEmpty => Self::NotEmpty,
WireError::Unsupported => Self::Unsupported,
WireError::Cancelled => Self::Cancelled,
WireError::Io(m) => Self::Io(m),
WireError::Remote(m) => Self::Remote(m),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum WireKind {
File,
Dir,
Special,
Symlink {
target: Vec<u8>,
/// 0 file, 1 dir, 2 special; `None` for a broken link.
target_type: Option<u8>,
},
}
/// `tunal_core::Entry` on the wire; the MIME type is sent only for `inode/*` specials.
#[derive(Debug, Serialize, Deserialize)]
pub struct WireEntry {
name: Vec<u8>,
kind: WireKind,
size: u64,
/// Nanoseconds since the epoch.
mtime: Option<u128>,
mode: u32,
uid: u32,
gid: u32,
mime: Option<String>,
}
const SPECIAL_MIMES: [&str; 4] = [
"inode/fifo",
"inode/socket",
"inode/blockdevice",
"inode/chardevice",
];
fn type_code(t: FileType) -> u8 {
match t {
FileType::File => 0,
FileType::Dir => 1,
FileType::Special => 2,
}
}
fn code_type(c: u8) -> FileType {
match c {
0 => FileType::File,
1 => FileType::Dir,
_ => FileType::Special,
}
}
impl From<Entry> for WireEntry {
fn from(e: Entry) -> Self {
let kind = match e.kind {
Kind::File => WireKind::File,
Kind::Dir => WireKind::Dir,
Kind::Special => WireKind::Special,
Kind::Symlink {
target,
target_type,
} => WireKind::Symlink {
target,
target_type: target_type.map(type_code),
},
};
Self {
name: e.name,
kind,
size: e.size,
mtime: e
.mtime
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map(|d| d.as_nanos()),
mode: e.mode,
uid: e.uid,
gid: e.gid,
mime: SPECIAL_MIMES.contains(&e.mime).then(|| e.mime.to_owned()),
}
}
}
impl From<WireEntry> for Entry {
fn from(w: WireEntry) -> Self {
let kind = match w.kind {
WireKind::File => Kind::File,
WireKind::Dir => Kind::Dir,
WireKind::Special => Kind::Special,
WireKind::Symlink {
target,
target_type,
} => Kind::Symlink {
target,
target_type: target_type.map(code_type),
},
};
let mime = w
.mime
.and_then(|m| SPECIAL_MIMES.into_iter().find(|s| *s == m))
.unwrap_or_else(|| mime::mime_type(&w.name, &kind));
Entry {
display_name: display_name(&w.name),
hidden: w.name.first() == Some(&b'.'),
kind,
size: w.size,
mtime: w.mtime.map(|n| {
UNIX_EPOCH + Duration::new((n / 1_000_000_000) as u64, (n % 1_000_000_000) as u32)
}),
mode: w.mode,
uid: w.uid,
gid: w.gid,
mime,
name: w.name,
}
}
}
/// One frame read from the pipe.
pub enum Frame {
Message(Vec<u8>),
Data(Vec<u8>),
}
fn write_frame(out: &mut impl Write, kind: u8, payload: &[u8]) -> io::Result<()> {
let len = u32::try_from(payload.len() + 1).map_err(|_| io::ErrorKind::InvalidInput)?;
out.write_all(&len.to_be_bytes())?;
out.write_all(&[kind])?;
out.write_all(payload)?;
out.flush()
}
pub fn send(out: &mut impl Write, message: &impl Serialize) -> io::Result<()> {
write_frame(out, MESSAGE, &serde_json::to_vec(message)?)
}
pub fn send_data(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
write_frame(out, DATA, data)
}
/// Next frame; `Ok(None)` on a clean end of stream.
pub fn read_frame(input: &mut impl Read) -> io::Result<Option<Frame>> {
let mut len = [0; 4];
match input.read_exact(&mut len) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
Err(e) => return Err(e),
}
let len = u32::from_be_bytes(len) as usize;
if len == 0 || len > MAX_FRAME {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"bad frame length",
));
}
let mut buf = vec![0; len];
input.read_exact(&mut buf)?;
let payload = buf.split_off(1);
match buf[0] {
MESSAGE => Ok(Some(Frame::Message(payload))),
DATA => Ok(Some(Frame::Data(payload))),
_ => Err(io::Error::new(io::ErrorKind::InvalidData, "bad frame kind")),
}
}
/// Next frame, which must be a message of type `T`.
pub fn recv<T: for<'de> Deserialize<'de>>(input: &mut impl Read) -> io::Result<Option<T>> {
match read_frame(input)? {
None => Ok(None),
Some(Frame::Message(m)) => Ok(Some(serde_json::from_slice(&m)?)),
Some(Frame::Data(_)) => Err(io::Error::new(
io::ErrorKind::InvalidData,
"expected a message",
)),
}
}
/// Next frame, which must be data.
pub fn recv_data(input: &mut impl Read) -> io::Result<Vec<u8>> {
match read_frame(input)? {
Some(Frame::Data(d)) => Ok(d),
_ => Err(io::Error::new(io::ErrorKind::InvalidData, "expected data")),
}
}