//! The workbench (`docs/agent-workbench.md`): where the agent does code //! work. A program for a machine with a toolchain — Linux or macOS — that //! runs Pinnacle's p2p layer under an identity of its own, is a contact of //! the person's devices, and offers one service, `workbench`, over streams //! tagged `verbs:workbench`: typed verbs (`records::verbs`), each with its //! effect, done in one git worktree per task. It has no shell to offer: a //! job is a name from its owner's list, and runs in the operating system's //! sandbox with no network and nothing writable outside its task, or not //! at all. //! //! ```sh //! workbench # serve //! workbench card # this workbench's card, hex, for a device to add //! ``` mod config; mod sandbox; mod tasks; use pinnacle_json::Value; use pinnacle_p2p::identity::{Card, Identity, Key}; use pinnacle_p2p::{Addr, Event, Node}; use pinnacle_records::verbs::{self, Pieces}; use std::net::UdpSocket; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; /// The stream tag a device opens to use it. pub const TAG: &str = "verbs:workbench"; /// A frame on the stream: one message (as the p2p service's bridges). const MESSAGE: u8 = 0x20; /// The largest frame taken. const MAX_FRAME: usize = 1 << 20; fn main() -> std::process::ExitCode { let args: Vec = std::env::args().collect(); let result = match args.get(1) { None => Err("usage: workbench [card]".into()), Some(path) => config::Config::read(std::path::Path::new(path)).and_then(|config| { match args.get(2).map(String::as_str) { Some("card") => card(&config), _ => serve(config), } }), }; match result { Ok(()) => std::process::ExitCode::SUCCESS, Err(e) => { eprintln!("workbench: {e}"); std::process::ExitCode::FAILURE } } } /// The workbench's identity: a seed in its state, made at its first start. fn identity(config: &config::Config) -> Result { let path = config.state.join("identity"); let seed = match std::fs::read(&path) { Ok(seed) if seed.len() == 32 => seed.try_into().unwrap(), _ => { let mut seed = [0u8; 32]; random(&mut seed)?; std::fs::create_dir_all(&config.state).map_err(|e| e.to_string())?; std::fs::write(&path, seed).map_err(|e| format!("{}: {e}", path.display()))?; seed } }; Ok(Identity::from_seed(seed)) } fn random(out: &mut [u8]) -> Result<(), String> { use std::io::Read; std::fs::File::open("/dev/urandom") .and_then(|mut f| f.read_exact(out)) .map_err(|e| format!("/dev/urandom: {e}")) } fn card(config: &config::Config) -> Result<(), String> { let card = identity(config)?.card(&config.name); let hex: String = card.to_bytes().iter().map(|b| format!("{b:02x}")).collect(); println!("{hex}"); Ok(()) } pub fn hex(key: &Key) -> String { key[..8].iter().map(|b| format!("{b:02x}")).collect() } /// One device's use of the workbench: a stream, the frames on it, and a /// message being put together. struct Session { contact: Key, stream: u32, buffer: Vec, pieces: Pieces, } /// A `job` call held until its job ends or its wait is over: whose, on /// which stream, its arguments, and until when. struct Held { contact: Key, stream: u32, args: Value, until: Instant, } fn serve(config: config::Config) -> Result<(), String> { let identity = identity(&config)?; let mut seed = [0u8; 32]; random(&mut seed)?; let mut node = Node::new(identity, &config.name, seed); let start = Instant::now(); let now = || start.elapsed().as_millis() as u64; node.set_epoch( SystemTime::now() .duration_since(UNIX_EPOCH) .map_or(1, |d| d.as_secs()), ); for card in &config.contacts { node.add_contact(*card); } if let Some(addr) = config.address { node.set_public_address(addr); } let socket = UdpSocket::bind(("0.0.0.0", config.port)).map_err(|e| format!("port {}: {e}", config.port))?; socket .set_read_timeout(Some(Duration::from_millis(50))) .map_err(|e| e.to_string())?; for peer in &config.peers { node.bootstrap(*peer, now()); } // This machine's address on its network, for a device behind the same // NAT: the one the system would send to the first peer from (a UDP // socket connected sends nothing). if let Some(peer) = config.peers.first() && let Ok(probe) = UdpSocket::bind("0.0.0.0:0") && probe .connect((std::net::Ipv4Addr::from(peer.ip), peer.port)) .is_ok() && let Ok(std::net::SocketAddr::V4(local)) = probe.local_addr() { node.set_local_address(Addr { ip: local.ip().octets(), port: config.port, }); } let mut work = tasks::Tasks::new(&config)?; println!( "workbench: {} on port {}, {} contacts allowed, {} repositories, jobs {}", config.name, config.port, config.contacts.len(), config.repos.len(), match sandbox::Sandbox::find() { Some(s) => format!("in {}", s.name()), None => "off: no sandbox on this machine".into(), } ); let mut sessions: Vec = Vec::new(); let mut held: Vec = Vec::new(); let mut datagram = vec![0u8; 65536]; loop { match socket.recv_from(&mut datagram) { Ok((len, std::net::SocketAddr::V4(from))) => { let addr = Addr { ip: from.ip().octets(), port: from.port(), }; node.receive(addr, &datagram[..len], now()); } Ok(_) => {} Err(e) if matches!( e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut ) => {} Err(e) => return Err(e.to_string()), } node.poll(now()); while let Some(event) = node.event() { match event { Event::StreamOpened { contact, stream, service, } => { // Only its own service, only for contacts its owner // allowed: the node knows no others. if service == TAG && config.contacts.iter().any(|c| c.key == contact) { println!("workbench: {} connected", hex(&contact)); sessions.push(Session { contact, stream, buffer: Vec::new(), pieces: Pieces::default(), }); } else { node.stream_finish(&contact, stream, now()); } } Event::StreamData { contact, stream, data, } => { let Some(i) = sessions .iter() .position(|s| s.contact == contact && s.stream == stream) else { continue; }; sessions[i].buffer.extend_from_slice(&data); while let Some(message) = take_frame(&mut sessions[i].buffer) { let Some(message) = message else { // A frame too large: the stream is not this protocol. let s = sessions.remove(i); node.stream_reset(&s.contact, s.stream, now()); break; }; let whole = sessions[i].pieces.push(&message); // A `job` that waits for its job is held, not // waited for here: the loop goes on for everyone. let hold = match &whole { Some((verbs::CALL, call)) if call.get("verb").as_str() == Some("job") => { let args = call.get("args"); let checked = tasks::description() .verb("job") .is_some_and(|v| v.check(args).is_ok()); checked.then(|| work.waiting(&contact, args)).flatten() } _ => None, }; match (hold, whole) { (Some(until), Some((_, call))) => held.push(Held { contact, stream, args: call.get("args").clone(), until, }), (_, whole) => { for m in answer(&mut work, &contact, whole) { node.stream_write(&contact, stream, &frame(&m), now()); } } } } } Event::StreamFinished { contact, stream } | Event::StreamReset { contact, stream } => { if let Some(i) = sessions .iter() .position(|s| s.contact == contact && s.stream == stream) { sessions.remove(i); node.stream_finish(&contact, stream, now()); } } _ => {} } } work.tick(); // Held `job` calls whose job ended or whose wait is over. let mut i = 0; while i < held.len() { let h = &held[i]; let task = h.args.get("task").as_u64().unwrap_or(0); let id = h.args.get("id").as_u64().unwrap_or(0); let busy = work .task_dir(&h.contact, task) .is_some_and(|dir| work.running(&dir, task, id)); if busy && Instant::now() < h.until { i += 1; continue; } let h = held.remove(i); let result = work.run(&h.contact, "job", &h.args); for m in verbs::pieces(verbs::RESULT, &result.to_json().to_string()) { node.stream_write(&h.contact, h.stream, &frame(&m), now()); } } while let Some((to, data)) = node.transmit() { let _ = socket.send_to(&data, (std::net::Ipv4Addr::from(to.ip), to.port)); } } } fn frame(message: &[u8]) -> Vec { let mut f = Vec::with_capacity(5 + message.len()); f.push(MESSAGE); f.extend_from_slice(&(message.len() as u32).to_le_bytes()); f.extend_from_slice(message); f } /// The next whole frame's message; Some(None) for one that cannot be. fn take_frame(buffer: &mut Vec) -> Option>> { if buffer.len() < 5 { return None; } let len = u32::from_le_bytes(buffer[1..5].try_into().unwrap()) as usize; if len > MAX_FRAME { return Some(None); } if buffer.len() < 5 + len { return None; } let message = buffer[5..5 + len].to_vec(); let kind = buffer[0]; buffer.drain(..5 + len); Some((kind == MESSAGE).then_some(message)) } /// A device's whole message, answered as messages. fn answer(work: &mut tasks::Tasks, contact: &Key, whole: Option<(u8, Value)>) -> Vec> { let reply = |kind: u8, v: Value| verbs::pieces(kind, &v.to_string()); match whole { Some((verbs::DESCRIBE, _)) => { println!("workbench: {} asked what it can do", hex(contact)); reply(verbs::DESCRIPTION, tasks::description().to_json()) } Some((verbs::CALL, call)) => { let verb = call.get("verb").as_str().unwrap_or(""); let args = call.get("args"); let description = tasks::description(); let result = match description.verb(verb) { None => verbs::Result::error(&format!("the workbench has no verb “{verb}”")), Some(v) => match v.check(args) { Err(why) => verbs::Result::error(&why), Ok(()) => work.run(contact, verb, args), }, }; println!( "workbench: {} {verb} {}", hex(contact), if result.ok { "done" } else { "refused" } ); reply(verbs::RESULT, result.to_json()) } _ => Vec::new(), } } /// A card from its hex, as `workbench card` prints it. pub fn card_of_hex(text: &str) -> Option { let text = text.trim(); if text.len() != Card::SIZE * 2 { return None; } let bytes: Option> = (0..text.len()) .step_by(2) .map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok()) .collect(); Card::from_bytes(&bytes?) }