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]>
This commit is contained in:
parent
7ba6ae8eae
commit
7257b00b0c
15 changed files with 1271 additions and 29 deletions
6
Cargo.lock
generated
6
Cargo.lock
generated
|
|
@ -5545,6 +5545,7 @@ dependencies = [
|
|||
"toml",
|
||||
"tunal-core",
|
||||
"tunal-dirmeta",
|
||||
"tunal-elevate",
|
||||
"tunal-theme",
|
||||
"zbus",
|
||||
]
|
||||
|
|
@ -5573,6 +5574,11 @@ version = "0.1.0"
|
|||
[[package]]
|
||||
name = "tunal-elevate"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tunal-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tunal-net"
|
||||
|
|
|
|||
|
|
@ -10,14 +10,14 @@ When an operation fails with PermissionDenied, offer 'Retry as administrator': p
|
|||
docs/DECISIONS.md D-018; CLAUDE.md §3 (secrets); crates/tunal-core trait and ops job API; crates/tunal/src/jobs_bridge.rs.
|
||||
|
||||
## Steps
|
||||
- [ ] Protocol: length-prefixed serde messages over stdin/stdout: requests (copy, move, delete, mkdir, rename, write file, symlink) and replies (progress, done, error); version handshake.
|
||||
- [ ] Helper mode `tunal --elevated-helper` handled first in `main` before any UI; absolute paths only, no shell, exits on EOF.
|
||||
- [ ] Launcher: `pkexec <current_exe> --elevated-helper`; exit codes 126/127 → 'cancelled' / 'not authorized'; no polkit agent → clear error.
|
||||
- [ ] `ElevatedLocal` backend implementing `Location` through the helper, so the ops engine reruns the failed items through it.
|
||||
- [ ] UI: PermissionDenied error → 'Retry as administrator'; `.directory` writes use the same path.
|
||||
- [ ] Polkit policy `assets/polkit/<id>.policy` (exec path annotation, `auth_admin_keep`) — installed by S037; without it pkexec's generic action applies.
|
||||
- [ ] Smoke: drive the helper as the normal user (no pkexec) with a small example against the scratchpad.
|
||||
- [ ] PROGRESS entry, INDEX line, commit `S016: …`
|
||||
- [x] Protocol: length-prefixed serde messages over stdin/stdout: requests (copy, move, delete, mkdir, rename, write file, symlink) and replies (progress, done, error); version handshake.
|
||||
- [x] Helper mode `tunal --elevated-helper` handled first in `main` before any UI; absolute paths only, no shell, exits on EOF.
|
||||
- [x] Launcher: `pkexec <current_exe> --elevated-helper`; exit codes 126/127 → 'cancelled' / 'not authorized'; no polkit agent → clear error.
|
||||
- [x] `ElevatedLocal` backend implementing `Location` through the helper, so the ops engine reruns the failed items through it.
|
||||
- [x] UI: PermissionDenied error → 'Retry as administrator'; `.directory` writes use the same path.
|
||||
- [x] Polkit policy `assets/polkit/<id>.policy` (exec path annotation, `auth_admin_keep`) — installed by S037; without it pkexec's generic action applies.
|
||||
- [x] Smoke: drive the helper as the normal user (no pkexec) with a small example against the scratchpad.
|
||||
- [x] PROGRESS entry, INDEX line, commit `S016: …`
|
||||
|
||||
## End criteria
|
||||
- `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass.
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v
|
|||
|
||||
## 05 Elevation
|
||||
|
||||
- [ ] [S016 — Root operations through pkexec](05%20Elevation/S016-pkexec-elevation.md) · Opus high
|
||||
- [x] [S016 — Root operations through pkexec](05%20Elevation/S016-pkexec-elevation.md) · Opus high
|
||||
|
||||
## 06 Thumbnails
|
||||
|
||||
|
|
|
|||
20
assets/polkit/org.tunal.Tunal.elevated-helper.policy
Normal file
20
assets/polkit/org.tunal.Tunal.elevated-helper.policy
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE policyconfig PUBLIC
|
||||
"-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
|
||||
<policyconfig>
|
||||
<vendor>Tunal</vendor>
|
||||
<vendor_url>https://archlinux.tail7c4f5e.ts.net/git/astar76/Tunal</vendor_url>
|
||||
<icon_name>tunal</icon_name>
|
||||
<action id="org.tunal.Tunal.elevated-helper">
|
||||
<description>Change files as administrator</description>
|
||||
<message>Authentication is needed to change files that belong to another user or the system</message>
|
||||
<defaults>
|
||||
<allow_any>auth_admin</allow_any>
|
||||
<allow_inactive>auth_admin</allow_inactive>
|
||||
<allow_active>auth_admin_keep</allow_active>
|
||||
</defaults>
|
||||
<annotate key="org.freedesktop.policykit.exec.path">/usr/bin/tunal</annotate>
|
||||
<annotate key="org.freedesktop.policykit.exec.argv1">--elevated-helper</annotate>
|
||||
</action>
|
||||
</policyconfig>
|
||||
|
|
@ -4,3 +4,8 @@ version.workspace = true
|
|||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tunal-core = { path = "../tunal-core" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
|
|
|||
134
crates/tunal-elevate/examples/helper_smoke.rs
Normal file
134
crates/tunal-elevate/examples/helper_smoke.rs
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
//! Drives the helper as the normal user (no pkexec): `cargo run -p tunal-elevate --example
|
||||
//! helper_smoke -- <scratch dir>`. The example re-runs itself as the helper.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::ops::ControlFlow;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tunal_core::{Error, Location, Uri, WriteMode};
|
||||
use tunal_elevate::protocol::{self, Reply, Request};
|
||||
use tunal_elevate::{ElevatedLocal, Elevation, HELPER_ARG};
|
||||
|
||||
fn main() {
|
||||
let arg = std::env::args().nth(1).expect("usage: helper_smoke <dir>");
|
||||
if arg == HELPER_ARG {
|
||||
tunal_elevate::serve().expect("serve");
|
||||
return;
|
||||
}
|
||||
let dir = std::fs::canonicalize(PathBuf::from(arg)).expect("dir");
|
||||
let exe = std::env::current_exe().expect("exe");
|
||||
let at = |name: &str| Uri::from_path(&dir.join(name));
|
||||
|
||||
let helper = ElevatedLocal::spawn_unelevated(&exe).expect("launch");
|
||||
helper.mkdir(&at("sub")).expect("mkdir");
|
||||
let data: Vec<u8> = (0..700_000u32).map(|i| (i % 251) as u8).collect();
|
||||
let mut w = helper
|
||||
.open_write(&at("sub/a.bin"), WriteMode::CreateNew)
|
||||
.expect("open_write");
|
||||
w.write_all(&data).expect("write");
|
||||
drop(w);
|
||||
let mut back = Vec::new();
|
||||
helper
|
||||
.open_read(&at("sub/a.bin"))
|
||||
.expect("open_read")
|
||||
.read_to_end(&mut back)
|
||||
.expect("read");
|
||||
assert_eq!(back, data, "read back");
|
||||
let mut steps = 0;
|
||||
helper
|
||||
.copy_file(
|
||||
&at("sub/a.bin"),
|
||||
&at("sub/b.bin"),
|
||||
WriteMode::CreateNew,
|
||||
|_| steps += 1,
|
||||
)
|
||||
.expect("copy");
|
||||
assert_eq!(std::fs::read(dir.join("sub/b.bin")).expect("copied"), data);
|
||||
assert_eq!(
|
||||
helper.copy_file(
|
||||
&at("sub/a.bin"),
|
||||
&at("sub/b.bin"),
|
||||
WriteMode::CreateNew,
|
||||
|_| ()
|
||||
),
|
||||
Err(Error::Exists)
|
||||
);
|
||||
helper
|
||||
.rename(&at("sub/b.bin"), &at("sub/c.bin"))
|
||||
.expect("rename");
|
||||
helper.symlink(&at("sub/link"), b"c.bin").expect("symlink");
|
||||
let mut names = Vec::new();
|
||||
helper
|
||||
.list(&at("sub"), &mut |chunk| {
|
||||
names.extend(chunk.into_iter().map(|e| (e.display_name, e.mime, e.size)));
|
||||
ControlFlow::Continue(())
|
||||
})
|
||||
.expect("list");
|
||||
names.sort();
|
||||
println!("listed: {names:?}");
|
||||
assert_eq!(names.len(), 3);
|
||||
for name in ["sub/a.bin", "sub/c.bin", "sub/link", "sub"] {
|
||||
helper.delete(&at(name)).expect("delete");
|
||||
}
|
||||
assert_eq!(helper.stat(&at("sub")), Err(Error::NotFound));
|
||||
println!("copy, rename, link, list, delete ok ({steps} progress replies)");
|
||||
|
||||
// Relative paths are refused by the helper itself (raw request: `Uri` is always absolute).
|
||||
let mut raw = std::process::Command::new(&exe)
|
||||
.arg(HELPER_ARG)
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.expect("raw helper");
|
||||
let (mut input, mut output) = (raw.stdin.take().unwrap(), raw.stdout.take().unwrap());
|
||||
protocol::send(
|
||||
&mut input,
|
||||
&Request::Hello {
|
||||
version: protocol::VERSION,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let hello: Option<Reply> = protocol::recv(&mut output).unwrap();
|
||||
protocol::send(
|
||||
&mut input,
|
||||
&Request::Mkdir {
|
||||
path: b"relative".to_vec(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let reply: Option<Reply> = protocol::recv(&mut output).unwrap();
|
||||
println!("handshake: {hello:?}; relative mkdir: {reply:?}");
|
||||
drop(input);
|
||||
println!("raw helper after EOF: {}", raw.wait().unwrap());
|
||||
|
||||
// Elevation switches only the elevated thread to the helper.
|
||||
let elevation = Arc::new(Elevation::with_launcher(move || {
|
||||
ElevatedLocal::spawn_unelevated(&exe)
|
||||
}));
|
||||
elevation.elevate(std::thread::current().id());
|
||||
elevation.mkdir(&at("via-switch")).expect("switch mkdir");
|
||||
let other = elevation.clone();
|
||||
let dir2 = at("from-other-thread");
|
||||
std::thread::spawn(move || other.mkdir(&dir2).expect("local mkdir"))
|
||||
.join()
|
||||
.unwrap();
|
||||
elevation
|
||||
.write_file(
|
||||
&at("via-switch/.directory"),
|
||||
b"[Desktop Entry]\nIcon=folder\n",
|
||||
)
|
||||
.expect("write_file");
|
||||
elevation.release(std::thread::current().id());
|
||||
std::fs::remove_file(dir.join("via-switch/.directory")).expect("written");
|
||||
std::fs::remove_dir(dir.join("via-switch")).expect("rm");
|
||||
std::fs::remove_dir(dir.join("from-other-thread")).expect("rm");
|
||||
|
||||
// Dropping the backend closes stdin; the helper exits on EOF and is reaped.
|
||||
drop(helper);
|
||||
drop(elevation);
|
||||
println!(
|
||||
"helper exited on EOF; scratch dir empty: {}",
|
||||
std::fs::read_dir(&dir).unwrap().next().is_none()
|
||||
);
|
||||
}
|
||||
367
crates/tunal-elevate/src/elevated.rs
Normal file
367
crates/tunal-elevate/src/elevated.rs
Normal file
|
|
@ -0,0 +1,367 @@
|
|||
//! The user side: launches the helper through pkexec and serves `file://` through it.
|
||||
|
||||
use std::io::{self, BufReader, BufWriter, Read, Write};
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::path::Path;
|
||||
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use tunal_core::{Capabilities, Entry, Error, FILE, ListSink, Location, Result, Uri, WriteMode};
|
||||
|
||||
use crate::protocol::{self, CHUNK, Frame, Reply, Request, VERSION};
|
||||
|
||||
/// Argument that turns the `tunal` binary into the helper.
|
||||
pub const HELPER_ARG: &str = "--elevated-helper";
|
||||
|
||||
struct Conn {
|
||||
child: Child,
|
||||
/// `None` once closed (dropping it ends the helper).
|
||||
input: Option<BufWriter<ChildStdin>>,
|
||||
output: BufReader<ChildStdout>,
|
||||
}
|
||||
|
||||
impl Conn {
|
||||
fn send(&mut self, request: &Request) -> Result<()> {
|
||||
protocol::send(self.input()?, request).map_err(pipe_error)
|
||||
}
|
||||
|
||||
fn input(&mut self) -> Result<&mut BufWriter<ChildStdin>> {
|
||||
self.input.as_mut().ok_or_else(gone)
|
||||
}
|
||||
|
||||
fn recv(&mut self) -> Result<Reply> {
|
||||
match protocol::recv::<Reply>(&mut self.output).map_err(pipe_error)? {
|
||||
Some(Reply::Error(e)) => Err(e.into()),
|
||||
Some(reply) => Ok(reply),
|
||||
None => Err(gone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, request: &Request) -> Result<Reply> {
|
||||
self.send(request)?;
|
||||
self.recv()
|
||||
}
|
||||
|
||||
fn done(&mut self, request: &Request) -> Result<()> {
|
||||
match self.call(request)? {
|
||||
Reply::Done => Ok(()),
|
||||
_ => Err(unexpected()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Conn {
|
||||
fn drop(&mut self) {
|
||||
// Closing stdin ends the helper; reap it so no zombie stays behind.
|
||||
drop(self.input.take());
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// `file://` served by a root helper. Every call blocks; run it off the UI thread.
|
||||
pub struct ElevatedLocal {
|
||||
conn: Arc<Mutex<Conn>>,
|
||||
}
|
||||
|
||||
impl ElevatedLocal {
|
||||
/// Starts `pkexec <this exe> --elevated-helper`; polkit's agent asks for the password.
|
||||
pub fn start() -> Result<Self> {
|
||||
let exe = std::env::current_exe().map_err(|e| Error::Remote(e.to_string()))?;
|
||||
let mut command = Command::new("pkexec");
|
||||
command.arg(exe).arg(HELPER_ARG);
|
||||
Self::launch(command)
|
||||
}
|
||||
|
||||
/// Runs `program --elevated-helper` directly, without pkexec (smoke runs as the user).
|
||||
pub fn spawn_unelevated(program: &Path) -> Result<Self> {
|
||||
let mut command = Command::new(program);
|
||||
command.arg(HELPER_ARG);
|
||||
Self::launch(command)
|
||||
}
|
||||
|
||||
fn launch(mut command: Command) -> Result<Self> {
|
||||
let mut child = command
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| match e.kind() {
|
||||
io::ErrorKind::NotFound => Error::Remote(
|
||||
"pkexec is not installed, so administrator rights aren't available".into(),
|
||||
),
|
||||
_ => Error::Remote(e.to_string()),
|
||||
})?;
|
||||
let mut conn = Conn {
|
||||
input: Some(BufWriter::new(child.stdin.take().expect("piped stdin"))),
|
||||
output: BufReader::new(child.stdout.take().expect("piped stdout")),
|
||||
child,
|
||||
};
|
||||
match conn.call(&Request::Hello { version: VERSION }) {
|
||||
Ok(Reply::Hello { version }) if version == VERSION => {
|
||||
// The helper never writes to stderr; drop it so pkexec can't block on a full pipe.
|
||||
drop(conn.child.stderr.take());
|
||||
Ok(Self {
|
||||
conn: Arc::new(Mutex::new(conn)),
|
||||
})
|
||||
}
|
||||
Ok(_) => Err(Error::Remote(
|
||||
"the administrator helper is a different version".into(),
|
||||
)),
|
||||
Err(Error::Remote(m)) if m == GONE => {
|
||||
drop(conn.input.take());
|
||||
Err(launch_error(&mut conn.child))
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, Conn> {
|
||||
self.conn.lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
fn open(&self, request: Request) -> Result<u64> {
|
||||
match self.lock().call(&request)? {
|
||||
Reply::Handle(handle) => Ok(handle),
|
||||
_ => Err(unexpected()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies one file inside the helper; `progress` gets the bytes copied so far.
|
||||
pub fn copy_file(
|
||||
&self,
|
||||
from: &Uri,
|
||||
to: &Uri,
|
||||
mode: WriteMode,
|
||||
mut progress: impl FnMut(u64),
|
||||
) -> Result<()> {
|
||||
let mut conn = self.lock();
|
||||
conn.send(&Request::Copy {
|
||||
from: path(from)?,
|
||||
to: path(to)?,
|
||||
create_new: mode == WriteMode::CreateNew,
|
||||
})?;
|
||||
loop {
|
||||
match conn.recv()? {
|
||||
Reply::Progress(n) => progress(n),
|
||||
Reply::Done => return Ok(()),
|
||||
_ => return Err(unexpected()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Location for ElevatedLocal {
|
||||
fn scheme(&self) -> &str {
|
||||
FILE
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
Capabilities {
|
||||
write: true,
|
||||
symlink: true,
|
||||
permissions: true,
|
||||
..Capabilities::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn list(&self, dir: &Uri, sink: &mut ListSink<'_>) -> Result<()> {
|
||||
// Read the whole listing first so the sink never runs while the pipe is locked.
|
||||
let mut chunks = Vec::new();
|
||||
{
|
||||
let mut conn = self.lock();
|
||||
conn.send(&Request::List { path: path(dir)? })?;
|
||||
loop {
|
||||
match conn.recv()? {
|
||||
Reply::Entries(chunk) => chunks.push(chunk),
|
||||
Reply::Done => break,
|
||||
_ => return Err(unexpected()),
|
||||
}
|
||||
}
|
||||
}
|
||||
for chunk in chunks {
|
||||
if sink(chunk.into_iter().map(Entry::from).collect()).is_break() {
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stat(&self, uri: &Uri) -> Result<Entry> {
|
||||
match self.lock().call(&Request::Stat { path: path(uri)? })? {
|
||||
Reply::Entry(entry) => Ok(entry.into()),
|
||||
_ => Err(unexpected()),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_read(&self, uri: &Uri) -> Result<Box<dyn Read + Send>> {
|
||||
let handle = self.open(Request::OpenRead { path: path(uri)? })?;
|
||||
Ok(Box::new(Reader {
|
||||
file: File::new(self.conn.clone(), handle),
|
||||
buf: Vec::new(),
|
||||
pos: 0,
|
||||
}))
|
||||
}
|
||||
|
||||
fn open_write(&self, uri: &Uri, mode: WriteMode) -> Result<Box<dyn Write + Send>> {
|
||||
let handle = self.open(Request::OpenWrite {
|
||||
path: path(uri)?,
|
||||
create_new: mode == WriteMode::CreateNew,
|
||||
})?;
|
||||
Ok(Box::new(Writer(File::new(self.conn.clone(), handle))))
|
||||
}
|
||||
|
||||
fn mkdir(&self, uri: &Uri) -> Result<()> {
|
||||
self.lock().done(&Request::Mkdir { path: path(uri)? })
|
||||
}
|
||||
|
||||
fn rename(&self, from: &Uri, to: &Uri) -> Result<()> {
|
||||
self.lock().done(&Request::Rename {
|
||||
from: path(from)?,
|
||||
to: path(to)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn delete(&self, uri: &Uri) -> Result<()> {
|
||||
self.lock().done(&Request::Delete { path: path(uri)? })
|
||||
}
|
||||
|
||||
fn symlink(&self, link: &Uri, target: &[u8]) -> Result<()> {
|
||||
self.lock().done(&Request::Symlink {
|
||||
link: path(link)?,
|
||||
target: target.to_vec(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An open file in the helper; closed when dropped.
|
||||
struct File {
|
||||
conn: Arc<Mutex<Conn>>,
|
||||
handle: u64,
|
||||
}
|
||||
|
||||
impl File {
|
||||
fn new(conn: Arc<Mutex<Conn>>, handle: u64) -> Self {
|
||||
Self { conn, handle }
|
||||
}
|
||||
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, Conn> {
|
||||
self.conn.lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for File {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.lock().done(&Request::Close {
|
||||
handle: self.handle,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
struct Reader {
|
||||
file: File,
|
||||
buf: Vec<u8>,
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl Read for Reader {
|
||||
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
|
||||
if self.pos == self.buf.len() {
|
||||
let mut conn = self.file.lock();
|
||||
conn.send(&Request::Read {
|
||||
handle: self.file.handle,
|
||||
})
|
||||
.map_err(to_io)?;
|
||||
self.buf = match protocol::read_frame(&mut conn.output)? {
|
||||
Some(Frame::Data(data)) => data,
|
||||
Some(Frame::Message(m)) => {
|
||||
return Err(match serde_json::from_slice(&m) {
|
||||
Ok(Reply::Error(e)) => to_io(e.into()),
|
||||
_ => to_io(unexpected()),
|
||||
});
|
||||
}
|
||||
None => return Err(to_io(gone())),
|
||||
};
|
||||
self.pos = 0;
|
||||
}
|
||||
let n = out.len().min(self.buf.len() - self.pos);
|
||||
out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
|
||||
self.pos += n;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
struct Writer(File);
|
||||
|
||||
impl Write for Writer {
|
||||
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
|
||||
let data = &data[..data.len().min(CHUNK)];
|
||||
let mut conn = self.0.lock();
|
||||
conn.send(&Request::Write {
|
||||
handle: self.0.handle,
|
||||
})
|
||||
.map_err(to_io)?;
|
||||
protocol::send_data(conn.input().map_err(to_io)?, data)?;
|
||||
match conn.recv().map_err(to_io)? {
|
||||
Reply::Done => Ok(data.len()),
|
||||
_ => Err(to_io(unexpected())),
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
const GONE: &str = "the administrator helper stopped";
|
||||
|
||||
fn gone() -> Error {
|
||||
Error::Remote(GONE.into())
|
||||
}
|
||||
|
||||
fn unexpected() -> Error {
|
||||
Error::Remote("the administrator helper sent an unexpected reply".into())
|
||||
}
|
||||
|
||||
fn pipe_error(e: io::Error) -> Error {
|
||||
match e.kind() {
|
||||
io::ErrorKind::BrokenPipe | io::ErrorKind::UnexpectedEof => gone(),
|
||||
_ => Error::Remote(format!("administrator helper: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Why pkexec ended before the handshake (its exit code and message).
|
||||
fn launch_error(child: &mut Child) -> Error {
|
||||
let mut stderr = String::new();
|
||||
if let Some(mut pipe) = child.stderr.take() {
|
||||
let _ = pipe.read_to_string(&mut stderr);
|
||||
}
|
||||
let code = child.wait().ok().and_then(|s| s.code());
|
||||
let message = if stderr.contains("No authentication agent") {
|
||||
"no password prompt is available (no polkit authentication agent is running)"
|
||||
} else {
|
||||
match code {
|
||||
Some(126) => "administrator authentication was cancelled",
|
||||
Some(127) => "not authorized to act as administrator",
|
||||
_ => GONE,
|
||||
}
|
||||
};
|
||||
Error::Remote(message.into())
|
||||
}
|
||||
|
||||
fn to_io(e: Error) -> io::Error {
|
||||
let kind = match e {
|
||||
Error::NotFound => io::ErrorKind::NotFound,
|
||||
Error::PermissionDenied => io::ErrorKind::PermissionDenied,
|
||||
Error::Exists => io::ErrorKind::AlreadyExists,
|
||||
_ => io::ErrorKind::Other,
|
||||
};
|
||||
io::Error::new(kind, e.to_string())
|
||||
}
|
||||
|
||||
fn path(uri: &Uri) -> Result<Vec<u8>> {
|
||||
Ok(uri
|
||||
.to_path()
|
||||
.ok_or(Error::Unsupported)?
|
||||
.into_os_string()
|
||||
.into_vec())
|
||||
}
|
||||
196
crates/tunal-elevate/src/helper.rs
Normal file
196
crates/tunal-elevate/src/helper.rs
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
//! The root side: `tunal --elevated-helper` serves requests on stdin/stdout until EOF.
|
||||
//! It needs no environment or display (pkexec clears both) and runs no shell.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::ops::ControlFlow;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
|
||||
use tunal_core::{Error, LocalLocation, Location, Result, Uri};
|
||||
|
||||
use crate::protocol::{self, CHUNK, Reply, Request, VERSION, WireEntry};
|
||||
|
||||
/// Copy progress is reported every this many bytes.
|
||||
const PROGRESS_STEP: u64 = 4 << 20;
|
||||
|
||||
/// Serves one client: handshake, then requests until stdin closes.
|
||||
pub fn serve() -> io::Result<()> {
|
||||
let mut input = io::stdin().lock();
|
||||
let mut out = io::stdout().lock();
|
||||
match protocol::recv::<Request>(&mut input)? {
|
||||
Some(Request::Hello { version }) if version == VERSION => {
|
||||
protocol::send(&mut out, &Reply::Hello { version: VERSION })?
|
||||
}
|
||||
Some(_) => {
|
||||
let reply =
|
||||
Reply::Error(Error::Remote(format!("protocol version {VERSION} needed")).into());
|
||||
return protocol::send(&mut out, &reply);
|
||||
}
|
||||
None => return Ok(()),
|
||||
}
|
||||
let mut server = Server {
|
||||
files: HashMap::new(),
|
||||
next: 1,
|
||||
};
|
||||
while let Some(request) = protocol::recv::<Request>(&mut input)? {
|
||||
server.handle(request, &mut input, &mut out)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Server {
|
||||
files: HashMap<u64, File>,
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
fn handle(
|
||||
&mut self,
|
||||
request: Request,
|
||||
input: &mut impl Read,
|
||||
out: &mut impl Write,
|
||||
) -> io::Result<()> {
|
||||
let reply = match request {
|
||||
Request::List { path } => return list(&path, out),
|
||||
Request::Read { handle } => return self.read(handle, out),
|
||||
Request::Write { handle } => {
|
||||
let data = protocol::recv_data(input)?;
|
||||
self.write(handle, &data).map(|()| Reply::Done)
|
||||
}
|
||||
Request::Copy {
|
||||
from,
|
||||
to,
|
||||
create_new,
|
||||
} => copy(&from, &to, create_new, out).map(|()| Reply::Done),
|
||||
other => self.simple(other),
|
||||
};
|
||||
protocol::send(out, &reply.unwrap_or_else(|e| Reply::Error(e.into())))
|
||||
}
|
||||
|
||||
fn simple(&mut self, request: Request) -> Result<Reply> {
|
||||
let local = LocalLocation;
|
||||
match request {
|
||||
Request::Hello { .. } => Ok(Reply::Hello { version: VERSION }),
|
||||
Request::Stat { path } => Ok(Reply::Entry(local.stat(&uri(&path)?)?.into())),
|
||||
Request::OpenRead { path } => {
|
||||
let file = File::open(self::path(&path)?)?;
|
||||
Ok(self.add(file))
|
||||
}
|
||||
Request::OpenWrite { path, create_new } => {
|
||||
let file = open_write(&path, create_new)?;
|
||||
Ok(self.add(file))
|
||||
}
|
||||
Request::Close { handle } => {
|
||||
let file = self.files.remove(&handle).ok_or(Error::NotFound)?;
|
||||
file.sync_all()?;
|
||||
Ok(Reply::Done)
|
||||
}
|
||||
Request::Mkdir { path } => local.mkdir(&uri(&path)?).map(|()| Reply::Done),
|
||||
Request::Rename { from, to } => {
|
||||
local.rename(&uri(&from)?, &uri(&to)?).map(|()| Reply::Done)
|
||||
}
|
||||
Request::Delete { path } => local.delete(&uri(&path)?).map(|()| Reply::Done),
|
||||
Request::Symlink { link, target } => {
|
||||
local.symlink(&uri(&link)?, &target).map(|()| Reply::Done)
|
||||
}
|
||||
Request::List { .. }
|
||||
| Request::Read { .. }
|
||||
| Request::Write { .. }
|
||||
| Request::Copy { .. } => Err(Error::Unsupported),
|
||||
}
|
||||
}
|
||||
|
||||
fn add(&mut self, file: File) -> Reply {
|
||||
let handle = self.next;
|
||||
self.next += 1;
|
||||
self.files.insert(handle, file);
|
||||
Reply::Handle(handle)
|
||||
}
|
||||
|
||||
fn read(&mut self, handle: u64, out: &mut impl Write) -> io::Result<()> {
|
||||
let Some(file) = self.files.get_mut(&handle) else {
|
||||
return protocol::send(out, &Reply::Error(Error::NotFound.into()));
|
||||
};
|
||||
let mut buf = vec![0; CHUNK];
|
||||
match file.read(&mut buf) {
|
||||
Ok(n) => protocol::send_data(out, &buf[..n]),
|
||||
Err(e) => protocol::send(out, &Reply::Error(Error::from(e).into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&mut self, handle: u64, data: &[u8]) -> Result<()> {
|
||||
let file = self.files.get_mut(&handle).ok_or(Error::NotFound)?;
|
||||
Ok(file.write_all(data)?)
|
||||
}
|
||||
}
|
||||
|
||||
fn list(path: &[u8], out: &mut impl Write) -> io::Result<()> {
|
||||
let mut failed = None;
|
||||
let result = uri(path).and_then(|dir| {
|
||||
LocalLocation.list(&dir, &mut |chunk| {
|
||||
let chunk: Vec<WireEntry> = chunk.into_iter().map(Into::into).collect();
|
||||
match protocol::send(out, &Reply::Entries(chunk)) {
|
||||
Ok(()) => ControlFlow::Continue(()),
|
||||
Err(e) => {
|
||||
failed = Some(e);
|
||||
ControlFlow::Break(())
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
if let Some(e) = failed {
|
||||
return Err(e);
|
||||
}
|
||||
let reply = match result {
|
||||
Ok(()) => Reply::Done,
|
||||
Err(e) => Reply::Error(e.into()),
|
||||
};
|
||||
protocol::send(out, &reply)
|
||||
}
|
||||
|
||||
fn copy(from: &[u8], to: &[u8], create_new: bool, out: &mut impl Write) -> Result<()> {
|
||||
let mut source = File::open(path(from)?)?;
|
||||
let mut target = open_write(to, create_new)?;
|
||||
let mut buf = vec![0; CHUNK];
|
||||
let (mut done, mut reported) = (0u64, 0u64);
|
||||
loop {
|
||||
let n = source.read(&mut buf)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
target.write_all(&buf[..n])?;
|
||||
done += n as u64;
|
||||
if done - reported >= PROGRESS_STEP {
|
||||
reported = done;
|
||||
protocol::send(out, &Reply::Progress(done)).map_err(Error::from)?;
|
||||
}
|
||||
}
|
||||
target.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_write(path: &[u8], create_new: bool) -> Result<File> {
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true);
|
||||
if create_new {
|
||||
options.create_new(true);
|
||||
} else {
|
||||
options.create(true).truncate(true);
|
||||
}
|
||||
Ok(options.open(self::path(path)?)?)
|
||||
}
|
||||
|
||||
/// Only absolute paths are accepted.
|
||||
fn path(bytes: &[u8]) -> Result<&Path> {
|
||||
if bytes.first() != Some(&b'/') || bytes.contains(&0) {
|
||||
return Err(Error::Remote("only absolute paths are accepted".into()));
|
||||
}
|
||||
Ok(Path::new(OsStr::from_bytes(bytes)))
|
||||
}
|
||||
|
||||
fn uri(bytes: &[u8]) -> Result<Uri> {
|
||||
Ok(Uri::from_path(path(bytes)?))
|
||||
}
|
||||
|
|
@ -1 +1,158 @@
|
|||
//! Root operations behind a password prompt.
|
||||
//! Root operations behind a password prompt: polkit's agent asks for the password
|
||||
//! (Tunal never sees it) and `pkexec tunal --elevated-helper` runs the operations.
|
||||
|
||||
mod elevated;
|
||||
mod helper;
|
||||
pub mod protocol;
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread::ThreadId;
|
||||
|
||||
use tunal_core::{
|
||||
Capabilities, Entry, Error, FILE, ListSink, LocalLocation, Location, Result, Uri, Watch,
|
||||
WatchCallback, WriteMode,
|
||||
};
|
||||
|
||||
pub use elevated::{ElevatedLocal, HELPER_ARG};
|
||||
pub use helper::serve;
|
||||
|
||||
/// Polkit action of the helper (`assets/polkit/<id>.policy`).
|
||||
pub const POLICY_ID: &str = "org.tunal.Tunal.elevated-helper";
|
||||
|
||||
type Launcher = dyn Fn() -> Result<ElevatedLocal> + Send + Sync;
|
||||
|
||||
/// `file://` backend for the job engine: local, except on threads that were elevated,
|
||||
/// whose calls go through one shared root helper (started on first use).
|
||||
/// A job runs on one thread, so elevating its thread reruns the rest of that job as root.
|
||||
pub struct Elevation {
|
||||
threads: Mutex<HashSet<ThreadId>>,
|
||||
helper: Mutex<Option<Arc<ElevatedLocal>>>,
|
||||
launch: Box<Launcher>,
|
||||
}
|
||||
|
||||
impl Default for Elevation {
|
||||
fn default() -> Self {
|
||||
Self::with_launcher(ElevatedLocal::start)
|
||||
}
|
||||
}
|
||||
|
||||
impl Elevation {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn with_launcher(
|
||||
launch: impl Fn() -> Result<ElevatedLocal> + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
Self {
|
||||
threads: Mutex::default(),
|
||||
helper: Mutex::default(),
|
||||
launch: Box::new(launch),
|
||||
}
|
||||
}
|
||||
|
||||
/// Later calls from `thread` run as root.
|
||||
pub fn elevate(&self, thread: ThreadId) {
|
||||
self.threads.lock().unwrap().insert(thread);
|
||||
}
|
||||
|
||||
/// `thread` is back to local calls; the helper stops when no thread is elevated.
|
||||
pub fn release(&self, thread: ThreadId) {
|
||||
let mut threads = self.threads.lock().unwrap();
|
||||
if threads.remove(&thread) && threads.is_empty() {
|
||||
self.helper.lock().unwrap().take();
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a whole file as root (e.g. a `.directory` in a folder the user can't write).
|
||||
/// Blocks while the password prompt is open.
|
||||
pub fn write_file(&self, uri: &Uri, data: &[u8]) -> Result<()> {
|
||||
let helper = self.helper()?;
|
||||
let result = helper
|
||||
.open_write(uri, WriteMode::Overwrite)
|
||||
.and_then(|mut w| w.write_all(data).map_err(Error::from));
|
||||
if self.threads.lock().unwrap().is_empty() {
|
||||
self.helper.lock().unwrap().take();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn helper(&self) -> Result<Arc<ElevatedLocal>> {
|
||||
let mut helper = self.helper.lock().unwrap();
|
||||
if let Some(h) = helper.as_ref() {
|
||||
return Ok(h.clone());
|
||||
}
|
||||
let started = Arc::new((self.launch)()?);
|
||||
*helper = Some(started.clone());
|
||||
Ok(started)
|
||||
}
|
||||
|
||||
/// Runs `op` on the helper when this thread is elevated, else locally. A failed
|
||||
/// launch (prompt cancelled) drops the elevation so the next retry asks again.
|
||||
fn on<T>(&self, op: impl FnOnce(&dyn Location) -> Result<T>) -> Result<T> {
|
||||
let me = std::thread::current().id();
|
||||
if !self.threads.lock().unwrap().contains(&me) {
|
||||
return op(&LocalLocation);
|
||||
}
|
||||
match self.helper() {
|
||||
Ok(helper) => op(&*helper),
|
||||
Err(e) => {
|
||||
self.release(me);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Location for Elevation {
|
||||
fn scheme(&self) -> &str {
|
||||
FILE
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
LocalLocation.capabilities()
|
||||
}
|
||||
|
||||
fn list(&self, dir: &Uri, sink: &mut ListSink<'_>) -> Result<()> {
|
||||
self.on(|b| b.list(dir, sink))
|
||||
}
|
||||
|
||||
fn stat(&self, uri: &Uri) -> Result<Entry> {
|
||||
self.on(|b| b.stat(uri))
|
||||
}
|
||||
|
||||
fn open_read(&self, uri: &Uri) -> Result<Box<dyn Read + Send>> {
|
||||
self.on(|b| b.open_read(uri))
|
||||
}
|
||||
|
||||
fn open_write(&self, uri: &Uri, mode: WriteMode) -> Result<Box<dyn Write + Send>> {
|
||||
self.on(|b| b.open_write(uri, mode))
|
||||
}
|
||||
|
||||
fn mkdir(&self, uri: &Uri) -> Result<()> {
|
||||
self.on(|b| b.mkdir(uri))
|
||||
}
|
||||
|
||||
fn rename(&self, from: &Uri, to: &Uri) -> Result<()> {
|
||||
self.on(|b| b.rename(from, to))
|
||||
}
|
||||
|
||||
fn delete(&self, uri: &Uri) -> Result<()> {
|
||||
self.on(|b| b.delete(uri))
|
||||
}
|
||||
|
||||
/// Unsupported when elevated: root would trash into its own home.
|
||||
fn trash(&self, uri: &Uri) -> Result<()> {
|
||||
self.on(|b| b.trash(uri))
|
||||
}
|
||||
|
||||
fn symlink(&self, link: &Uri, target: &[u8]) -> Result<()> {
|
||||
self.on(|b| b.symlink(link, target))
|
||||
}
|
||||
|
||||
fn watch(&self, dir: &Uri, callback: WatchCallback) -> Result<Watch> {
|
||||
LocalLocation.watch(dir, callback)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
310
crates/tunal-elevate/src/protocol.rs
Normal file
310
crates/tunal-elevate/src/protocol.rs
Normal file
|
|
@ -0,0 +1,310 @@
|
|||
//! 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")),
|
||||
}
|
||||
}
|
||||
|
|
@ -10,6 +10,7 @@ slint = { workspace = true, features = ["unstable-winit-030"] }
|
|||
tunal-theme = { path = "../tunal-theme" }
|
||||
png.workspace = true
|
||||
tunal-core = { path = "../tunal-core" }
|
||||
tunal-elevate = { path = "../tunal-elevate" }
|
||||
tunal-dirmeta = { path = "../tunal-dirmeta" }
|
||||
jiff.workspace = true
|
||||
serde.workspace = true
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
//! Runs file operations for the window: progress toasts with cancel, the conflict dialog,
|
||||
//! item errors with retry/skip/abort and the list of failures after a job.
|
||||
//! item errors with retry/skip/abort (or retry as administrator) and the list of failures
|
||||
//! after a job.
|
||||
//!
|
||||
//! Jobs run on `tunal_core::ops::Jobs` threads; their events come back to the UI thread
|
||||
//! here. Dialogs are asked one at a time, in the order the jobs raised them.
|
||||
|
|
@ -7,6 +8,8 @@
|
|||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::rc::{Rc, Weak};
|
||||
use std::sync::Arc;
|
||||
use std::thread::ThreadId;
|
||||
use std::time::Duration;
|
||||
|
||||
use slint::{ComponentHandle, Model, ModelRc, Timer, VecModel};
|
||||
|
|
@ -15,6 +18,7 @@ use tunal_core::ops::{
|
|||
JobHandle, JobId, JobKind, Jobs, Phase, Progress, Report,
|
||||
};
|
||||
use tunal_core::{Locations, Uri};
|
||||
use tunal_elevate::Elevation;
|
||||
|
||||
use crate::folder::format;
|
||||
use crate::{ButtonKind, ConflictInfo, DialogAction, MainWindow, ToastData, ToastProgress};
|
||||
|
|
@ -29,7 +33,8 @@ thread_local! {
|
|||
/// What the user is asked, one at a time.
|
||||
enum Prompt {
|
||||
Conflict(Box<ConflictRequest>),
|
||||
Error(ErrorRequest),
|
||||
/// With the job's thread, which "Retry as administrator" elevates.
|
||||
Error(ErrorRequest, ThreadId),
|
||||
Failures {
|
||||
title: String,
|
||||
lines: Vec<String>,
|
||||
|
|
@ -59,6 +64,8 @@ struct State {
|
|||
pub struct Bridge {
|
||||
ui: slint::Weak<MainWindow>,
|
||||
jobs: Jobs,
|
||||
/// The jobs' `file://` backend; elevates one job's thread on request.
|
||||
elevation: Arc<Elevation>,
|
||||
toasts: Rc<VecModel<ToastData>>,
|
||||
state: RefCell<State>,
|
||||
/// Called after every finished job (panes that can't watch list again).
|
||||
|
|
@ -68,17 +75,26 @@ pub struct Bridge {
|
|||
}
|
||||
|
||||
impl Bridge {
|
||||
pub fn attach(ui: &MainWindow, locations: Locations) -> Rc<Self> {
|
||||
let jobs = Jobs::new(locations, |id, event| {
|
||||
pub fn attach(ui: &MainWindow, mut locations: Locations) -> Rc<Self> {
|
||||
let elevation = Arc::new(Elevation::new());
|
||||
locations.register(elevation.clone());
|
||||
let release = elevation.clone();
|
||||
let jobs = Jobs::new(locations, move |id, event| {
|
||||
// Events arrive on the job's thread: remember it, and end its elevation with the job.
|
||||
let thread = std::thread::current().id();
|
||||
if matches!(event, JobEvent::Finished(_)) {
|
||||
release.release(thread);
|
||||
}
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
if let Some(bridge) = BRIDGE.with(|b| b.borrow().upgrade()) {
|
||||
bridge.event(id, event);
|
||||
bridge.event(id, event, thread);
|
||||
}
|
||||
});
|
||||
});
|
||||
let bridge = Rc::new(Self {
|
||||
ui: ui.as_weak(),
|
||||
jobs,
|
||||
elevation,
|
||||
toasts: Rc::new(VecModel::default()),
|
||||
state: RefCell::new(State::default()),
|
||||
on_finished: RefCell::new(Box::new(|| {})),
|
||||
|
|
@ -90,6 +106,13 @@ impl Bridge {
|
|||
bridge
|
||||
}
|
||||
|
||||
/// Root access for writes outside jobs (`.directory` files): call
|
||||
/// `elevation().write_file(uri, bytes)` off the UI thread after a `PermissionDenied`.
|
||||
#[allow(dead_code)] // for `.directory` writes (S015)
|
||||
pub fn elevation(&self) -> Arc<Elevation> {
|
||||
self.elevation.clone()
|
||||
}
|
||||
|
||||
pub fn set_on_finished(&self, f: impl Fn() + 'static) {
|
||||
*self.on_finished.borrow_mut() = Box::new(f);
|
||||
}
|
||||
|
|
@ -220,7 +243,7 @@ impl Bridge {
|
|||
|
||||
// ---- job events ---------------------------------------------------------------------
|
||||
|
||||
fn event(&self, job: JobId, event: JobEvent) {
|
||||
fn event(&self, job: JobId, event: JobEvent, thread: ThreadId) {
|
||||
match event {
|
||||
JobEvent::Progress(progress) => {
|
||||
if let Some(i) = self.toast_of(job)
|
||||
|
|
@ -230,7 +253,7 @@ impl Bridge {
|
|||
}
|
||||
}
|
||||
JobEvent::Conflict(request) => self.prompt(Prompt::Conflict(request)),
|
||||
JobEvent::Error(request) => self.prompt(Prompt::Error(request)),
|
||||
JobEvent::Error(request) => self.prompt(Prompt::Error(request, thread)),
|
||||
JobEvent::Finished(report) => self.finished(job, report),
|
||||
}
|
||||
}
|
||||
|
|
@ -307,12 +330,15 @@ impl Bridge {
|
|||
ui.set_confirm_action(action.into());
|
||||
ui.invoke_show_confirm();
|
||||
}
|
||||
Prompt::Error(request) => {
|
||||
// S016: when `request.needs_elevation()`, offer "Try as administrator" here.
|
||||
Prompt::Error(request, _) => {
|
||||
let action = |text: &str| DialogAction {
|
||||
text: text.into(),
|
||||
kind: ButtonKind::Text,
|
||||
};
|
||||
let filled = |text: &str| DialogAction {
|
||||
text: text.into(),
|
||||
kind: ButtonKind::Filled,
|
||||
};
|
||||
let mut body = format!("{}: {}.", name_of(&request.uri), request.error);
|
||||
if request.needs_elevation() {
|
||||
body.push_str(" Administrator rights are needed.");
|
||||
|
|
@ -320,15 +346,13 @@ impl Bridge {
|
|||
ui.set_errors_title("Couldn't finish".into());
|
||||
ui.set_errors_body(body.into());
|
||||
ui.set_errors_lines(ModelRc::new(VecModel::default()));
|
||||
ui.set_errors_actions(ModelRc::new(VecModel::from(vec![
|
||||
action("Abort"),
|
||||
action("Skip all"),
|
||||
action("Skip"),
|
||||
DialogAction {
|
||||
text: "Retry".into(),
|
||||
kind: ButtonKind::Filled,
|
||||
},
|
||||
])));
|
||||
let mut actions = vec![action("Abort"), action("Skip all"), action("Skip")];
|
||||
if request.needs_elevation() {
|
||||
actions.extend([action("Retry"), filled("Retry as administrator")]);
|
||||
} else {
|
||||
actions.push(filled("Retry"));
|
||||
}
|
||||
ui.set_errors_actions(ModelRc::new(VecModel::from(actions)));
|
||||
ui.set_errors_default(2);
|
||||
ui.invoke_show_errors();
|
||||
}
|
||||
|
|
@ -392,11 +416,17 @@ impl Bridge {
|
|||
if let Some(ui) = self.ui.upgrade() {
|
||||
ui.invoke_close_errors();
|
||||
}
|
||||
if let Some(Prompt::Error(request)) = self.finish_prompt() {
|
||||
if let Some(Prompt::Error(request, thread)) = self.finish_prompt() {
|
||||
request.reply.send(match index {
|
||||
0 => ErrorAction::Abort,
|
||||
1 => ErrorAction::SkipAll,
|
||||
3 => ErrorAction::Retry,
|
||||
// The job retries on its own thread, now through the root helper; the
|
||||
// password prompt (polkit's agent) opens on the first call there.
|
||||
4 => {
|
||||
self.elevation.elevate(thread);
|
||||
ErrorAction::Retry
|
||||
}
|
||||
_ => ErrorAction::Skip,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,13 @@ const USAGE: &str = "usage: tunal [<folder>…] [--split <folder> <folder>] \
|
|||
[--gallery [--page menu|dialog]] [--screenshot <png> [--dark] [--size WxH]]";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
// Root helper (`pkexec tunal --elevated-helper`): before any UI, theme or env lookups.
|
||||
if std::env::args().nth(1).as_deref() == Some(tunal_elevate::HELPER_ARG) {
|
||||
return match tunal_elevate::serve() {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(_) => ExitCode::FAILURE,
|
||||
};
|
||||
}
|
||||
let result = parse(std::env::args().skip(1)).and_then(|args| match args.screenshot {
|
||||
None if args.gallery => gallery(args.page).and_then(run).map_err(|e| e.to_string()),
|
||||
None => window(args.tabs, false)
|
||||
|
|
|
|||
|
|
@ -39,3 +39,4 @@ D-034 — 2026-11-18 — Window shell API: MainWindow holds `panes: [PaneData {
|
|||
D-035 — 2026-11-18 — Visual direction: the user finds the current UI bland and wants it closer to their old prototype: Material 3 Expressive — shaped glyph containers (cookie/clover/scallop), pills and rounded surface cards, ripples, shape morphing, visible (token-driven) motion. New plan S038 restyles S003–S013 before S014; later UI plans build on its `Shape` component — user — S014+, S018, S021, S023, S029, S034, S035.
|
||||
D-036 — 2026-11-18 — Cost: the user saw ~50 % of a day's credits go; every session runs the `caveman:caveman` skill (short replies and reports), reads only what its plan names, and skips extra verification variants; the orchestrator keeps look-ahead at 1–2 fresh sessions, avoids reusing long sessions when it can start a fresh one, and uses one-shot wake-ups at a usage-limit reset instead of a 30-minute heartbeat — user — all plans; overrides ORCHESTRATOR.md look-ahead 3.
|
||||
D-037 — 2026-11-18 — Dates: relative stamps by default (Just now, N minutes/hours ago, Yesterday/weekday with time, then date + time), 12-hour clock by default, both configurable (date style Relative/Absolute, clock 12/24-hour) — plan S039. The user expects a lot of configuration: every UI plan exposes its user-visible choices in Settings — user — S039, all UI plans.
|
||||
D-038 — 2026-11-18 — Elevation is per job thread: `tunal_elevate::Elevation` is the jobs' `file://` backend and sends an elevated thread's calls to one shared pkexec helper (other threads and views stay local); polkit action id `org.tunal.Tunal.elevated-helper`, exec path `/usr/bin/tunal`; non-job root writes use `Elevation::write_file` — S016 — S015, S036, S037.
|
||||
|
|
|
|||
|
|
@ -170,6 +170,14 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
|
|||
- Not done: no live window (menu click, real save, polkit prompt via "Save as administrator" is a user check); previews not applied; image picker is a path field (no file chooser); grid view not looked at; sidebar/crumb names only for local folders.
|
||||
- Later: file chooser for the image; `Previews` once a setting exists; names for places other than local folders.
|
||||
|
||||
## S016 — Root operations through pkexec
|
||||
- Done: `tunal-elevate`: `protocol` (frames = u32 BE length + kind byte + JSON message or raw data; `Request` Hello/Stat/List/OpenRead/OpenWrite/Read/Write/Close/Copy/Mkdir/Rename/Delete/Symlink, `Reply` Hello/Done/Entry/Entries/Handle/Progress/Error; `VERSION` handshake). `serve()` = helper (LocalLocation as root, absolute paths only, no shell, no env, exits on EOF); `main` runs it first for `--elevated-helper`. `ElevatedLocal::start()` = `pkexec <current_exe> --elevated-helper` (126 cancelled, 127 not authorized, "no polkit authentication agent", pkexec missing → `Error::Remote` text); `spawn_unelevated(exe)` for smoke; `copy_file` with progress.
|
||||
- **How to call**: `Elevation` is the jobs' `file://` backend (registered in `jobs_bridge::Bridge::attach`): local, except threads passed to `elevate(ThreadId)`. Error dialog on PermissionDenied adds "Retry as administrator" (index 4) → elevates the job's thread (taken from the event sink) and answers Retry, so the rest of that job runs through one shared helper; `JobEvent::Finished` releases the thread, helper stops when none is elevated; a failed launch drops the elevation. Outside jobs: `Bridge::elevation().write_file(uri, bytes)` (blocking, off the UI thread) — for `.directory` saves.
|
||||
- Policy: `assets/polkit/org.tunal.Tunal.elevated-helper.policy` (`POLICY_ID`), exec.path `/usr/bin/tunal`, argv1 `--elevated-helper`, `auth_admin_keep`; S037 installs it.
|
||||
- Verified: `cargo run -p tunal-elevate --example helper_smoke -- <scratch>` (mkdir, 700 KB write/read back, copy, Exists, rename, symlink, list, delete, relative path refused, `Elevation` thread switch + write_file, helper exits on EOF, dir left empty); real `tunal --elevated-helper` under `env -i` answers the handshake and exits 0 on EOF; build + clippy -D warnings + fmt --check clean on HEAD + S016 files (scratch worktree; the shared checkout fails only on S015's in-flight files); `sh -c` grep empty.
|
||||
- Not done: no pkexec/polkit run (D-009, S036); "Retry as administrator" not clicked in a live window; `.directory` save not yet wired to `write_file` (S015's files; API sent to S015); `Bridge::elevation` has `allow(dead_code)` until then.
|
||||
- Later: remove that allow once S015 calls it; elevated trash goes to root's trash (left as is: Elevation passes trash through the helper → Unsupported).
|
||||
|
||||
## Later
|
||||
- (orchestrator) Breadcrumb: a long path is hard-clipped at the bar's left edge with no elision mark, and the root crumb elides at 960 px — for S034.
|
||||
-
|
||||
|
|
|
|||
Loading…
Reference in a new issue