1
//! pi-env: a small daemon that gives a Pi Durable host an execution environment on this machine over stdin/stdout2
//! (docs/protocol.md). Started as `pi-env serve --token <hex>`, usually through `ssh`.4
mod decode;5
mod errors;6
mod exec;7
mod frame;8
mod fs;9
mod list;10
mod output;11
mod pty;12
mod scan;13
mod sys;14
mod watch;15
mod window;17
use errors::Failure;18
use exec::Control;19
use frame::{CANCEL, ERROR, Frame, PING, REQUEST, RESULT};20
use output::Output;21
use serde_json::{Value, json};22
use std::collections::{HashMap, VecDeque};23
use std::env;24
use std::fs::{File, ReadDir};25
use std::io::{self, BufReader, BufWriter, Read, Write};26
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};27
use std::sync::mpsc::{self, Receiver, Sender};28
use std::sync::{Arc, Mutex};29
use std::thread;30
use std::time::{Duration, SystemTime, UNIX_EPOCH};32
const PROTOCOL: u64 = 1;33
/// Operations added after protocol 1's first release; clients check `hello.features` before using them.34
const FEATURES: &[&str] = &["listFiles"];35
/// The npm package version this daemon ships with (build.rs).36
const VERSION: &str = env!("PI_ENV_VERSION");37
const PING_INTERVAL: Duration = Duration::from_secs(5);38
const SILENCE_LIMIT_MS: u64 = 30_000;39
const SCAN_CHUNK: usize = 64 * 1024;40
/// Threads for file operations; commands run on their own threads.41
const WORKERS: usize = 16;42
/// Open handles per connection, beyond which opening fails with `EMFILE`.43
const MAX_HANDLES: usize = 4096;44
/// Replies with larger payloads queue behind command output instead of going first.45
const CONTROL_PAYLOAD: usize = 64 * 1024;47
struct FileHandle {48
file: File,49
path: String,50
/// A failed chunk write poisons a write handle, so later chunks cannot leave a gap.51
failed: AtomicBool,52
/// Chunk writes run one at a time in arrival order, though the client sends several at once.53
serial: Mutex<Serial>,54
}56
#[derive(Default)]57
struct Serial {58
jobs: VecDeque<Job>,59
running: bool,60
}62
struct DirHandle {63
entries: ReadDir,64
path: String,65
}67
enum Handle {68
File(Arc<FileHandle>),69
Dir(Arc<Mutex<DirHandle>>),70
}72
type Job = Box<dyn FnOnce() + Send>;74
struct Server {75
output: Arc<Output>,76
tmpdir: String,77
handles: Mutex<HashMap<u64, Handle>>,78
next_handle: AtomicU64,79
controls: Mutex<HashMap<u32, Arc<Control>>>,80
groups: exec::Groups,81
terminals: pty::Terminals,82
}84
fn now_ms() -> u64 {85
SystemTime::now()86
.duration_since(UNIX_EPOCH)87
.map(|elapsed| elapsed.as_millis() as u64)88
.unwrap_or(0)89
}91
fn field<'a>(json: &'a Value, key: &str) -> Result<&'a str, Failure> {92
json[key]93
.as_str()94
.ok_or_else(|| Failure::new("EINVAL", format!("missing field {key}")))95
}97
fn number(json: &Value, key: &str) -> Result<u64, Failure> {98
json[key]99
.as_u64()100
.ok_or_else(|| Failure::new("EINVAL", format!("missing or invalid field {key}")))101
}103
fn flag(json: &Value, key: &str) -> bool {104
json[key].as_bool().unwrap_or(false)105
}107
impl Server {108
fn file(&self, json: &Value) -> Result<Arc<FileHandle>, Failure> {109
match self.handles.lock().unwrap().get(&number(json, "handle")?) {110
Some(Handle::File(file)) => Ok(file.clone()),111
Some(Handle::Dir(_)) => Err(Failure::new("EBADF", "not a file handle")),112
None => Err(Failure::new("EBADF", "unknown handle")),113
}114
}116
fn insert(&self, handle: Handle) -> Result<u64, Failure> {117
let mut handles = self.handles.lock().unwrap();118
if handles.len() >= MAX_HANDLES {119
return Err(Failure::new("EMFILE", "EMFILE: too many open files"));120
}121
let id = self.next_handle.fetch_add(1, Ordering::Relaxed);122
handles.insert(id, handle);123
Ok(id)124
}126
fn insert_file(&self, file: File, path: &str) -> Result<u64, Failure> {127
self.insert(Handle::File(Arc::new(FileHandle {128
file,129
path: path.to_string(),130
failed: AtomicBool::new(false),131
serial: Mutex::new(Serial::default()),132
})))133
}135
fn dispatch(136
&self,137
id: u32,138
json: &Value,139
payload: Vec<u8>,140
control: &Control,141
) -> Result<(Value, Vec<u8>), Failure> {142
if json.is_null() {143
return Err(Failure::new("EINVAL", "invalid JSON"));144
}145
let op = json["op"].as_str().unwrap_or_default();146
let plain = |value: Result<Value, Failure>| value.map(|value| (value, Vec::new()));147
match op {148
"hello" => plain(Ok(json!({149
"protocol": PROTOCOL,150
"version": VERSION,151
"os": env::consts::OS,152
"arch": env::consts::ARCH,153
"home": sys::home(),154
"separator": sys::PATH_SEPARATOR,155
"tmpdir": self.tmpdir,156
"cwd": sys::cwd(),157
"driveCwds": sys::drive_cwds(),158
"pid": std::process::id(),159
"features": FEATURES,160
}))),161
"lstat" => plain(fs::lstat(field(json, "path")?)),162
"realpath" => plain(fs::realpath(field(json, "path")?)),163
"write" => {164
let path = field(json, "path")?;165
let parents = json["parents"].as_bool().unwrap_or(true);166
let file = fs::write(path, flag(json, "append"), parents, &payload)?;167
if !flag(json, "keep") {168
return plain(Ok(json!({})));169
}170
plain(Ok(json!({ "handle": self.insert_file(file, path)? })))171
}172
"writeChunk" => {173
let handle = self.file(json)?;174
if handle.failed.load(Ordering::SeqCst) {175
return Err(Failure::new("EBADF", "an earlier write failed"));176
}177
(&handle.file).write_all(&payload).map_err(|error| {178
handle.failed.store(true, Ordering::SeqCst);179
Failure::io(&error, "write", &handle.path)180
})?;181
plain(Ok(json!({})))182
}183
"truncate" => plain(fs::truncate(field(json, "path")?, number(json, "size")?)),184
"fsync" => plain(fs::fsync(field(json, "path")?)),185
"rename" => plain(fs::rename(field(json, "path")?, field(json, "to")?)),186
"mkdir" => plain(fs::mkdir(field(json, "path")?, flag(json, "recursive"))),187
"rm" => plain(fs::rm(188
field(json, "path")?,189
flag(json, "recursive"),190
flag(json, "force"),191
)),192
"mkdtemp" => plain(fs::mkdtemp(field(json, "path")?)),193
"open" => {194
let path = field(json, "path")?;195
if json["mode"].as_str() == Some("read") {196
// Node's `open(path, "r")`: any kind of file, blocking; reads report what the file is.197
let file = sys::open(path, sys::OpenMode::Read)198
.map_err(|error| Failure::io(&error, "open", path))?;199
let stat = match file.metadata() {200
Ok(metadata) => json!({ "stat": fs::info(path, &metadata) }),201
Err(error) => {202
json!({ "statError": Failure::io(&error, "fstat", path).to_json() })203
}204
};205
let mut result = stat;206
result["handle"] = json!(self.insert_file(file, path)?);207
return plain(Ok(result));208
}209
let (file, info) = fs::open_reader(path, flag(json, "noFollow"))?;210
plain(Ok(211
json!({ "handle": self.insert_file(file, path)?, "info": info }),212
))213
}214
"pread" => {215
let handle = self.file(json)?;216
let length = (number(json, "length")? as usize).min(frame::MAX_PAYLOAD);217
let bytes = match json["offset"].as_u64() {218
Some(offset) => fs::pread(&handle.file, &handle.path, offset, length)?,219
None => fs::read(&handle.file, &handle.path, length)?,220
};221
Ok((json!({}), bytes))222
}223
"fstat" => {224
let handle = self.file(json)?;225
let metadata = handle226
.file227
.metadata()228
.map_err(|error| Failure::io(&error, "fstat", &handle.path))?;229
plain(Ok(fs::info(&handle.path, &metadata)))230
}231
"scanLines" => {232
let handle = self.file(json)?;233
plain(scan_lines(&handle.file, &handle.path, json, control))234
}235
"opendir" => {236
let path = field(json, "path")?;237
let entries =238
sys::read_dir(path).map_err(|error| Failure::io(&error, "opendir", path))?;239
let handle = self.insert(Handle::Dir(Arc::new(Mutex::new(DirHandle {240
entries,241
path: path.to_string(),242
}))))?;243
plain(Ok(json!({ "handle": handle })))244
}245
"readdir" => plain(self.read_dir(json)),246
"listFiles" => list::run(json, &|| control.aborted.load(Ordering::SeqCst)),247
"close" => {248
self.handles249
.lock()250
.unwrap()251
.remove(&number(json, "handle")?);252
plain(Ok(json!({})))253
}254
"exec" => plain(exec::run(255
id,256
exec::ExecRequest::from_json(json)?,257
&self.tmpdir,258
&self.output,259
control,260
&self.groups,261
)),262
"watch" => plain(watch::run(id, json, &self.output, control)),263
"pty" => plain(pty::run(264
id,265
pty::PtyRequest::from_json(json)?,266
&self.output,267
control,268
&self.groups,269
&self.terminals,270
)),271
_ => Err(Failure::new("EINVAL", format!("unknown operation {op}"))),272
}273
}275
fn read_dir(&self, json: &Value) -> Result<Value, Failure> {276
let max = number(json, "max")?.max(1) as usize;277
// Lock only this directory, so other requests are not held up by a slow listing.278
let dir = match self.handles.lock().unwrap().get(&number(json, "handle")?) {279
Some(Handle::Dir(dir)) => dir.clone(),280
_ => return Err(Failure::new("EBADF", "not a directory handle")),281
};282
let mut dir = dir.lock().unwrap();283
let mut entries = Vec::new();284
let mut done = false;285
while entries.len() < max {286
match dir.entries.next() {287
None => {288
done = true;289
break;290
}291
Some(Err(error)) => return Err(Failure::io(&error, "readdir", &dir.path)),292
Some(Ok(entry)) => entries.push(fs::dir_entry(&dir.path, &entry.file_name())),293
}294
}295
Ok(json!({ "entries": entries, "done": done }))296
}297
}299
fn scan_lines(file: &File, path: &str, json: &Value, control: &Control) -> Result<Value, Failure> {300
let start_line = number(json, "startLine")?;301
let end_line = json["endLine"].as_u64();302
if end_line.is_some_and(|end| end <= start_line) {303
return Err(Failure::new("EINVAL", "Invalid line range"));304
}305
let mut scanner = scan::LineScanner::new(start_line, end_line);306
let mut buffer = vec![0u8; SCAN_CHUNK];307
let mut position = 0u64;308
loop {309
if control.aborted.load(Ordering::SeqCst) {310
return Err(Failure::new("aborted", "aborted"));311
}312
let read = sys::read_at(file, &mut buffer, position)313
.map_err(|error| Failure::io(&error, "read", path))?;314
if read == 0 {315
return Ok(scanner.finish());316
}317
scanner.push(&buffer[..read]);318
position += read as u64;319
}320
}322
fn kill_all(groups: &exec::Groups) {323
for pid in groups.lock().unwrap().iter() {324
exec::kill_group(*pid);325
}326
}328
/// Stdin that records when bytes last arrived, so a large frame arriving slowly counts as a live client.329
struct Seen<R> {330
inner: R,331
last_seen: Arc<AtomicU64>,332
}334
impl<R: Read> Read for Seen<R> {335
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {336
let read = self.inner.read(buffer)?;337
if read > 0 {338
self.last_seen.store(now_ms(), Ordering::Relaxed);339
}340
Ok(read)341
}342
}344
fn start_workers() -> Sender<Job> {345
let (jobs, queue) = mpsc::channel::<Job>();346
let queue = Arc::new(Mutex::new(queue));347
for _ in 0..WORKERS {348
let queue: Arc<Mutex<Receiver<Job>>> = queue.clone();349
thread::spawn(move || {350
loop {351
let job = queue.lock().unwrap().recv();352
match job {353
Ok(job) => job(),354
Err(_) => return,355
}356
}357
});358
}359
jobs360
}362
fn respond(server: &Server, id: u32, request: Frame, control: Arc<Control>) {363
let is_exec = matches!(request.json["op"].as_str(), Some("exec" | "pty"));364
let reply = match server.dispatch(id, &request.json, request.payload, &control) {365
Ok((json, payload)) => Frame::with_payload(RESULT, id, json, payload),366
Err(failure) => Frame::new(ERROR, id, failure.to_json()),367
};368
server.controls.lock().unwrap().remove(&id);369
// A command's result follows its output; large payloads do not hold up pings and small replies.370
if is_exec || reply.payload.len() > CONTROL_PAYLOAD {371
server.output.bulk(reply, None);372
} else {373
server.output.control(reply);374
}375
}377
/// Queue `job` behind the handle's earlier chunk writes; one pool job drains the queue.378
fn run_in_order(jobs: &Sender<Job>, handle: Arc<FileHandle>, job: Job) {379
let mut serial = handle.serial.lock().unwrap();380
serial.jobs.push_back(job);381
if serial.running {382
return;383
}384
serial.running = true;385
drop(serial);386
let _ = jobs.send(Box::new(move || {387
loop {388
let next = {389
let mut serial = handle.serial.lock().unwrap();390
let next = serial.jobs.pop_front();391
if next.is_none() {392
serial.running = false;393
}394
next395
};396
match next {397
Some(job) => job(),398
None => return,399
}400
}401
}));402
}404
fn serve_frames(server: &Arc<Server>, input: &mut impl Read) -> io::Result<()> {405
let jobs = start_workers();406
while let Some(request) = frame::read_frame(input)? {407
match request.kind {408
REQUEST409
if matches!(410
request.json["op"].as_str(),411
Some("ptyWrite" | "ptyResize" | "ptyForeground")412
) =>413
{414
// Answered here, in arrival order: through the worker pool, two writes could swap.415
let reply = match request.json["op"].as_str() {416
Some("ptyWrite") => {417
pty::write(&server.terminals, &request.json, request.payload)418
}419
Some("ptyResize") => pty::resize(&server.terminals, &request.json),420
_ => pty::foreground(&server.terminals, &request.json),421
};422
server.output.control(match reply {423
Ok(json) => Frame::new(RESULT, request.id, json),424
Err(failure) => Frame::new(ERROR, request.id, failure.to_json()),425
});426
}427
REQUEST => {428
let id = request.id;429
// Registered before the request runs, so a cancel right behind it is not lost.430
let control = Arc::new(Control::default());431
server.controls.lock().unwrap().insert(id, control.clone());432
// Commands and watchers last; they get their own threads (watchers recurse through trees).433
if matches!(request.json["op"].as_str(), Some("exec" | "watch" | "pty")) {434
let worker = server.clone();435
let spawned = thread::Builder::new()436
.stack_size(16 * 1024 * 1024)437
.spawn(move || respond(&worker, id, request, control));438
if let Err(error) = spawned {439
server.controls.lock().unwrap().remove(&id);440
let failure = Failure::new("spawn_error", error.to_string());441
server442
.output443
.bulk(Frame::new(ERROR, id, failure.to_json()), None);444
}445
} else {446
let worker = server.clone();447
let serial = match request.json["op"].as_str() {448
Some("writeChunk") => server.file(&request.json).ok(),449
_ => None,450
};451
let job: Job = Box::new(move || respond(&worker, id, request, control));452
match serial {453
Some(handle) => run_in_order(&jobs, handle, job),454
None => {455
let _ = jobs.send(job);456
}457
}458
}459
}460
CANCEL => {461
let control = server.controls.lock().unwrap().get(&request.id).cloned();462
if let Some(control) = control {463
control.cancel(request.json["mode"].as_str() == Some("kill"));464
}465
}466
_ => {}467
}468
}469
Ok(())470
}472
fn serve(token: &str) -> io::Result<()> {473
{474
let mut stdout = io::stdout().lock();475
writeln!(stdout, "PI-ENV {token}")?;476
stdout.flush()?;477
}478
let output = Arc::new(Output::default());479
let writer = {480
let output = output.clone();481
thread::spawn(move || {482
output.run(&mut BufWriter::with_capacity(1 << 20, io::stdout().lock()))483
})484
};485
let server = Arc::new(Server {486
output: output.clone(),487
tmpdir: sys::tmpdir(),488
handles: Mutex::new(HashMap::new()),489
next_handle: AtomicU64::new(1),490
controls: Mutex::new(HashMap::new()),491
groups: Arc::new(Mutex::new(Default::default())),492
terminals: Arc::new(Mutex::new(HashMap::new())),493
});494
let last_seen = Arc::new(AtomicU64::new(now_ms()));495
{496
let output = output.clone();497
let last_seen = last_seen.clone();498
let groups = server.groups.clone();499
thread::spawn(move || {500
loop {501
thread::sleep(PING_INTERVAL);502
output.control(Frame::new(PING, 0, json!({})));503
// A client that went silent (a phone that lost its network) leaves nothing running.504
if now_ms().saturating_sub(last_seen.load(Ordering::Relaxed)) > SILENCE_LIMIT_MS {505
kill_all(&groups);506
std::process::exit(0);507
}508
}509
});510
}511
let mut input = BufReader::with_capacity(512
1 << 20,513
Seen {514
inner: io::stdin().lock(),515
last_seen,516
},517
);518
let result = serve_frames(&server, &mut input);519
// However input ended, the client is gone: stop everything it started.520
kill_all(&server.groups);521
output.close();522
let _ = writer.join();523
result524
}526
fn main() {527
let args: Vec<String> = env::args().collect();528
match args.get(1).map(String::as_str) {529
Some("serve") => {530
let token = args531
.iter()532
.position(|arg| arg == "--token")533
.and_then(|index| args.get(index + 1));534
let Some(token) = token else {535
eprintln!("usage: pi-env serve --token <hex>");536
std::process::exit(2);537
};538
if let Err(error) = serve(token) {539
eprintln!("pi-env: {error}");540
std::process::exit(1);541
}542
// Request threads may still be blocked (a FIFO open); nothing is left to answer them.543
std::process::exit(0);544
}545
Some("--version") => println!("pi-env {VERSION}"),546
_ => {547
eprintln!("usage: pi-env serve --token <hex>");548
std::process::exit(2);549
}550
}551
}