Self-hosted, sharable kanban for humans and agents. One 4.7 MB binary, 5 MB of RAM, 10 to 60 tokens per agent reply, starts in 3 ms, zero setup.
Rust ai-agentsclaude-codeclicodexcoding-agentskanbanlocal-firstmcpmcp-servermodel-context-protocolproductivityproject-managementraspberry-pirustself-hostedsqlitetask-manager
Share the board on the network with kanzo share, join and leave
emanuele-emd21d816d4dbe
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex 15101f7..4b218c6 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -46,6 +46,7 @@ Where things are:| `src/web.rs` | The board's HTTP API, and `/mcp` || `src/index.html`, `src/app.js`, `src/logo.png` | The board UI: plain HTML, CSS and JavaScript, built into the binary || `src/sync.rs` | `kanzo sync` |+| `src/share.rs` | `kanzo share`, `join` and `leave`: sharing the board on the network || `src/export.rs` | `kanzo export` || `src/service.rs` | `kanzo service` |diff --git a/Cargo.lock b/Cargo.lockindex b6ae1df..7b24ff6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -613,6 +613,16 @@ version = "1.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"+[[package]]+name = "if-addrs"+version = "0.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0a05c691e1fae256cf7013d99dad472dc52d5543322761f83ec8d47eab40d2b"+dependencies = [+ "libc",+ "windows-sys",+]+[[package]]name = "indexmap"version = "2.14.2"@@ -656,6 +666,7 @@ dependencies = ["axum","clap","dirs",+ "if-addrs","libc","rmcp","rusqlite",diff --git a/Cargo.toml b/Cargo.tomlindex 2b0ce66..d08f7b9 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -19,6 +19,8 @@ anyhow = "1.0.104"axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio"] }clap = { version = "4.6.7", features = ["derive"] }dirs = "7.0.0"+# Lists this computer's addresses for `kanzo share`; uses only libc and windows-sys, already built in.+if-addrs = "0.15.0"# Already built in by other crates; tells which lock errors mean "no locks here".libc = "0.2.191"rmcp = { version = "=3.7.0", features = ["server", "transport-io", "transport-streamable-http-server", "macros"] }@@ -27,7 +29,7 @@ schemars = "1.2.3"serde = { version = "1.0.229", features = ["derive"] }serde_json = "1.0.154"tokio = { version = "1.54.1", features = ["rt", "macros", "net", "signal", "io-util", "time"] }-tokio-util = "0.7.20"+tokio-util = { version = "0.7.20", features = ["io"] }# Kanzo reads config.toml and never writes TOML.toml = { version = "1.1.8", default-features = false, features = ["std", "parse", "serde"] }diff --git a/src/home.rs b/src/home.rsindex 6bf2c57..d878729 100644--- a/src/home.rs+++ b/src/home.rs@@ -11,7 +11,7 @@ use serde::Deserialize;use crate::store::{self, ImagesOf, Store};-const DEFAULT_PORT: u16 = 4242;+pub const DEFAULT_PORT: u16 = 4242;const CONFIG_TEMPLATE: &str = r#"# Kanzo settings.diff --git a/src/main.rs b/src/main.rsindex 8eb4bf2..9c26100 100644--- a/src/main.rs+++ b/src/main.rs@@ -2,6 +2,7 @@ mod export;mod home;mod mcp;mod service;+mod share;mod store;mod sync;mod update;@@ -10,7 +11,7 @@ mod web;use std::path::PathBuf;use std::process::ExitCode;-use clap::{Parser, Subcommand};+use clap::{Parser, Subcommand, ValueEnum};use crate::home::Home;@@ -69,6 +70,18 @@ enum Command {#[arg(long, short, value_name = "FILE")]output: Option<PathBuf>,},+ /// Share the board with other computers on your network, or stop; without on or off, show whether it is+ Share {+ #[arg(value_enum)]+ state: Option<OnOff>,+ },+ /// Use the board another computer shares, from this computer's board and agents+ Join {+ /// The address `kanzo share on` printed there, like 192.168.0.12+ host: String,+ },+ /// Stop using the shared board, and go back to this computer's own+ Leave,/// Install the latest release over this Kanzo, and restart the board's serviceUpdate,/// Start the board automatically at login@@ -78,6 +91,12 @@ enum Command {},}+#[derive(Clone, Copy, ValueEnum)]+enum OnOff {+ On,+ Off,+}+#[derive(Subcommand)]enum ServiceAction {/// Install and start a service that runs the board at login (LaunchAgent on macOS, systemd on Linux, Task Scheduler on Windows)@@ -120,7 +139,11 @@ async fn run(cli: Cli) -> anyhow::Result<()> {Some(Command::Init { folder: Some(folder) }) => folder.clone(),_ => Home::resolve(cli.home)?,};- let home = Home::open(dir)?;+ let mut home = Home::open(dir)?;+ // `--port` reaches the board on that port, for `kanzo share` and the others too.+ if let Some(port) = cli.port {+ home.config.port = port;+ }match cli.command {None => web::serve(home, cli.port, !cli.no_open).await,Some(Command::Mcp) => mcp::serve(home).await,@@ -143,6 +166,27 @@ async fn run(cli: Cli) -> anyhow::Result<()> {Some(Command::Export { format, project, output }) => {export::export(&home, format, project.as_deref(), output.as_deref())}+ Some(Command::Share { state }) => {+ let change = state.map(|s| match s {+ OnOff::On => share::Change::On,+ OnOff::Off => share::Change::Off,+ });+ let (status, running) = share::request(&home, change).await?;+ // Sharing with no board running starts one, already shared.+ if matches!(state, Some(OnOff::On)) && !running {+ return web::serve(home, cli.port, !cli.no_open).await;+ }+ println!("{}", status.message());+ Ok(())+ }+ Some(Command::Join { host }) => {+ println!("{}", share::request(&home, Some(share::Change::Join(host))).await?.0.message());+ Ok(())+ }+ Some(Command::Leave) => {+ println!("{}", share::request(&home, Some(share::Change::Leave)).await?.0.message());+ Ok(())+ }Some(Command::Service { action: ServiceAction::Install }) => service::install(&home),Some(Command::Service { action: ServiceAction::Uninstall }) => service::uninstall(),Some(Command::Update) => unreachable!("handled above"),diff --git a/src/share.rs b/src/share.rsnew file mode 100644index 0000000..0ce903a--- /dev/null+++ b/src/share.rs@@ -0,0 +1,381 @@+//! Sharing the board on your network: `kanzo share on|off`, `kanzo join <host>` and `kanzo leave`.+//!+//! A shared board listens on the network as well as on this computer. A computer that+//! joined one keeps its own board as a window onto it: the board hands the page's+//! requests to the host (`forward`).++use std::fmt::Write as _;+use std::io;+use std::net::{IpAddr, SocketAddr};+use std::sync::OnceLock;+use std::time::Duration;++use anyhow::{Context, Result, bail};+use axum::Json;+use axum::body::Body;+use axum::extract::Request;+use axum::http::{HeaderName, HeaderValue, StatusCode};+use axum::response::{IntoResponse, Response};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};+use tokio::net::TcpStream;+use tokio_util::io::ReaderStream;++use crate::home::{DEFAULT_PORT, Home};++/// The file in the data folder that says what this computer does on the network:+/// `share`, or `join <host:port>`; none for neither. `kanzo sync` leaves it out.+pub const FILE: &str = "network";++/// Sent by a guest's board, so the host can list who's using it.+pub const COMPUTER_HEADER: &str = "x-kanzo-computer";++/// Larger than any image the board takes.+const BODY_LIMIT: usize = 32 * 1024 * 1024;++#[derive(Debug, Clone, PartialEq)]+pub enum Net {+ Private,+ Sharing,+ /// Using another computer's board, at `host:port`.+ Joined(String),+}++impl Net {+ pub fn load(home: &Home) -> Self {+ let text = std::fs::read_to_string(home.dir.join(FILE)).unwrap_or_default();+ match text.trim() {+ "share" => Net::Sharing,+ line => match line.strip_prefix("join ") {+ Some(host) => Net::Joined(host.trim().to_string()),+ // config.toml can keep the board on the network for good, as before `kanzo share`.+ None if !home.config.listen.is_loopback() => Net::Sharing,+ None => Net::Private,+ },+ }+ }++ fn save(&self, home: &Home) -> io::Result<()> {+ let path = home.dir.join(FILE);+ match self {+ Net::Private => std::fs::remove_file(path)+ .or_else(|e| if e.kind() == io::ErrorKind::NotFound { Ok(()) } else { Err(e) }),+ Net::Sharing => std::fs::write(path, "share\n"),+ Net::Joined(host) => std::fs::write(path, format!("join {host}\n")),+ }+ }+}++/// What the board's settings, `kanzo share`, `kanzo join` and `kanzo leave` ask for,+/// as the board's `/api/network` takes it: `{"action": "join", "host": "192.168.0.12"}`.+#[derive(Debug, Serialize, Deserialize)]+#[serde(tag = "action", content = "host", rename_all = "lowercase")]+pub enum Change {+ On,+ Off,+ Join(String),+ Leave,+}++/// Checks `change` against what this computer does now, and saves the outcome. The+/// running board calls this, then listens as it says; without one, the next board does.+pub async fn change(home: &Home, change: Change) -> Result<Net, String> {+ let now = Net::load(home);+ let next = match (change, &now) {+ (Change::On, Net::Joined(host)) => {+ return Err(format!("This computer uses the board at {host}: run kanzo leave first."));+ }+ (Change::On, _) => Net::Sharing,+ (Change::Off, _) if !home.config.listen.is_loopback() => {+ return Err(format!(+ "config.toml sets listen = \"{}\", which keeps the board on the network: change it there.",+ home.config.listen+ ));+ }+ (Change::Off, Net::Sharing) | (Change::Leave, Net::Joined(_)) => Net::Private,+ (Change::Off | Change::Leave, _) => now.clone(),+ (Change::Join(_), Net::Sharing) => return Err("This board is shared: run kanzo share off first.".into()),+ (Change::Join(host), _) => {+ let host = address(&host)?;+ if !is_kanzo(&host).await {+ return Err(format!(+ "No shared board at {host}: share it on that computer first, on the same network."+ ));+ }+ Net::Joined(host)+ }+ };+ if next != now {+ next.save(home).map_err(|e| format!("cannot save {FILE}: {e}"))?;+ }+ Ok(next)+}++/// `192.168.0.12` or `mac-mini.local` as `host:port`, with Kanzo's port unless one is given.+fn address(host: &str) -> Result<String, String> {+ let host = host.trim().trim_start_matches("http://").trim_end_matches('/');+ if host.is_empty() || !host.chars().all(|c| c.is_ascii_alphanumeric() || ".-:[]".contains(c)) {+ return Err(format!("{host:?} isn't an address: pass the one `kanzo share on` printed, like 192.168.0.12."));+ }+ let full = match host.parse::<IpAddr>() {+ Ok(ip) => SocketAddr::new(ip, DEFAULT_PORT).to_string(),+ Err(_) if host.rsplit_once(':').is_some_and(|(_, p)| p.parse::<u16>().is_ok()) => host.to_string(),+ Err(_) => format!("{host}:{DEFAULT_PORT}"),+ };+ let local = full.parse::<SocketAddr>().is_ok_and(|a| a.ip().is_loopback() || a.ip().is_unspecified())+ || full.to_ascii_lowercase().starts_with("localhost:");+ if local {+ return Err("That's this computer: pass the address of the one sharing its board.".into());+ }+ Ok(full)+}++/// What this computer does on the network, as `/api/network` answers.+#[derive(Debug, Serialize, Deserialize)]+pub struct Status {+ state: State,+ /// Once joined, the host's address.+ host: Option<String>,+ /// While sharing, this computer's addresses for `kanzo join`, one per network it is on.+ addresses: Vec<String>,+ /// While sharing, the other computers using the board now.+ guests: Vec<Guest>,+}++/// Another computer using this board.+#[derive(Debug, Serialize, Deserialize)]+pub struct Guest {+ /// Like "Ada's MacBook Air"; `None` for a browser opened straight at this board.+ pub name: Option<String>,+ pub address: IpAddr,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+enum State {+ Private,+ Sharing,+ Joined,+}++impl Status {+ pub fn new(net: &Net, port: u16, guests: Vec<Guest>) -> Self {+ let (state, host, addresses) = match net {+ Net::Private => (State::Private, None, vec![]),+ Net::Sharing => (State::Sharing, None, addresses(port)),+ Net::Joined(host) => (State::Joined, Some(host.clone()), vec![]),+ };+ Self { state, host, addresses, guests }+ }++ pub fn message(&self) -> String {+ match self.state {+ State::Sharing => {+ let mut out = String::from("Shared on your network. On another computer, run");+ out += if self.addresses.len() > 1 { " the line for its network:" } else { ":" };+ if self.addresses.is_empty() {+ out += "\n kanzo join <this computer's IP address>";+ }+ for address in &self.addresses {+ let _ = write!(out, "\n kanzo join {address}");+ }+ if !self.guests.is_empty() {+ let guests: Vec<String> = self+ .guests+ .iter()+ .map(|g| g.name.as_ref().map_or(g.address.to_string(), |n| format!("{n} ({})", g.address)))+ .collect();+ let _ = write!(out, "\nUsing it now: {}", guests.join(", "));+ }+ out+ }+ State::Joined => format!(+ "Using the board at {}. Your agents use it too, from their next call.",+ self.host.as_deref().unwrap_or_default()+ ),+ State::Private => "Not shared: the board is on this computer only.".into(),+ }+ }+}++/// This computer's addresses, as others pass them to `kanzo join`: one per network it is+/// on, like the home network and a VPN. Which one works depends on where the other computer is.+fn addresses(port: u16) -> Vec<String> {+ let interfaces = if_addrs::get_if_addrs().unwrap_or_default();+ interfaces+ .iter()+ .filter(|i| i.is_oper_up() && !i.is_loopback() && i.ip().is_ipv4())+ .map(|i| if port == DEFAULT_PORT { i.ip().to_string() } else { format!("{}:{port}", i.ip()) })+ .collect()+}++/// Asks the running board for `change`, which then takes effect at once, or only for its+/// state; with no board running, saves the change for the next one. Also says whether a+/// board is running.+pub async fn request(home: &Home, change: Option<Change>) -> Result<(Status, bool)> {+ let port = home.config.port;+ let (method, body) = match &change {+ Some(c) => ("POST", serde_json::to_vec(c)?),+ None => ("GET", Vec::new()),+ };+ let json = [("content-type", "application/json")];+ match send(&format!("127.0.0.1:{port}"), method, "/api/network", &json, &body).await {+ Ok(mut reply) => {+ let mut text = String::new();+ reply.body.read_to_string(&mut text).await?;+ if reply.status == 200 {+ return Ok((serde_json::from_str(&text).context("unexpected answer from the board")?, true));+ }+ match serde_json::from_str::<Value>(&text).ok().and_then(|v| Some(v["error"].as_str()?.to_string())) {+ Some(error) => bail!(error),+ None => bail!("the board on port {port} answered {}: restart it so it runs this version", reply.status),+ }+ }+ Err(e) if e.kind() == io::ErrorKind::ConnectionRefused => {+ let net = match change {+ Some(c) => self::change(home, c).await.map_err(anyhow::Error::msg)?,+ None => Net::load(home),+ };+ Ok((Status::new(&net, port, Vec::new()), false))+ }+ Err(e) => Err(e).with_context(|| format!("cannot reach the board on port {port}")),+ }+}++/// One HTTP reply. Requests are HTTP/1.0, so the body is all that comes until the host+/// closes the connection, with no chunks to decode.+struct Reply {+ status: u16,+ headers: Vec<(String, String)>,+ body: BufReader<TcpStream>,+}++async fn send(host: &str, method: &str, path: &str, headers: &[(&str, &str)], body: &[u8]) -> io::Result<Reply> {+ let connect = tokio::time::timeout(Duration::from_secs(3), TcpStream::connect(host));+ let mut conn = connect.await.map_err(|_| io::Error::from(io::ErrorKind::TimedOut))??;+ let mut head = format!("{method} {path} HTTP/1.0\r\nHost: {host}\r\nContent-Length: {}\r\n", body.len());+ for (name, value) in headers {+ let _ = write!(head, "{name}: {value}\r\n");+ }+ head.push_str("\r\n");+ // One write: a separate one for the body can wait on a delayed ACK.+ let mut request = head.into_bytes();+ request.extend_from_slice(body);+ conn.write_all(&request).await?;+ let mut reader = BufReader::new(conn);+ let mut line = String::new();+ reader.read_line(&mut line).await?;+ let status = line.split_whitespace().nth(1).and_then(|s| s.parse().ok());+ let status = status.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "not an HTTP reply"))?;+ let mut headers = Vec::new();+ loop {+ line.clear();+ reader.read_line(&mut line).await?;+ let Some((name, value)) = line.trim_end().split_once(':') else { break };+ headers.push((name.trim().to_ascii_lowercase(), value.trim().to_string()));+ }+ Ok(Reply { status, headers, body: reader })+}++/// True when `host` answers like a Kanzo board.+pub async fn is_kanzo(host: &str) -> bool {+ let probe = async {+ let mut reply = send(host, "GET", "/api/ping", &[], b"").await.ok()?;+ let mut body = String::new();+ reply.body.read_to_string(&mut body).await.ok()?;+ Some(reply.status == 200 && body == "kanzo")+ };+ tokio::time::timeout(Duration::from_secs(2), probe).await.ok().flatten().unwrap_or(false)+}++/// This computer's name, as guests send it.+fn computer() -> &'static str {+ static NAME: OnceLock<String> = OnceLock::new();+ NAME.get_or_init(crate::sync::hostname)+}++fn unreachable(host: &str) -> String {+ format!("The shared board at {host} isn't reachable; run kanzo leave to use this computer's board.")+}++/// Hands one of the page's requests to the board this computer joined, and streams back its reply.+pub async fn forward(host: &str, req: Request) -> Response {+ let (parts, body) = req.into_parts();+ let Ok(body) = axum::body::to_bytes(body, BODY_LIMIT).await else {+ return StatusCode::PAYLOAD_TOO_LARGE.into_response();+ };+ // The host checks its own Host; the page's Origin is this board's, checked already.+ let skip = ["host", "origin", "referer", "connection", "content-length", "transfer-encoding", "keep-alive"];+ let mut headers: Vec<(&str, &str)> = parts+ .headers+ .iter()+ .filter(|(name, _)| !skip.contains(&name.as_str()))+ .filter_map(|(name, value)| Some((name.as_str(), value.to_str().ok()?)))+ .collect();+ headers.push((COMPUTER_HEADER, computer()));+ let path = parts.uri.path_and_query().map_or("/", |p| p.as_str());+ let Ok(reply) = send(host, parts.method.as_str(), path, &headers, &body).await else {+ return (StatusCode::BAD_GATEWAY, Json(json!({ "error": unreachable(host) }))).into_response();+ };+ let mut res = Response::new(Body::from_stream(ReaderStream::new(reply.body)));+ *res.status_mut() = StatusCode::from_u16(reply.status).unwrap_or(StatusCode::BAD_GATEWAY);+ for (name, value) in &reply.headers {+ if let (Ok(name), Ok(value)) = (HeaderName::from_bytes(name.as_bytes()), HeaderValue::from_str(value))+ && name != "connection"+ {+ res.headers_mut().append(name, value);+ }+ }+ res+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn addresses() {+ assert_eq!(address("192.168.0.12").unwrap(), "192.168.0.12:4242");+ assert_eq!(address(" http://192.168.0.12:4300/ ").unwrap(), "192.168.0.12:4300");+ assert_eq!(address("mac-mini.local").unwrap(), "mac-mini.local:4242");+ assert_eq!(address("fe80::1").unwrap(), "[fe80::1]:4242");+ for bad in ["", "127.0.0.1", "localhost", "localhost:4300", "0.0.0.0", "a b", "evil.com/x", "u@host"] {+ assert!(address(bad).is_err(), "{bad}");+ }+ }++ #[test]+ fn changes_follow_the_rules() {+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ let tmp = tempfile::tempdir().unwrap();+ let home = Home::open(tmp.path().to_path_buf()).unwrap();+ let apply = |c| rt.block_on(change(&home, c));++ assert_eq!(apply(Change::On).unwrap(), Net::Sharing);+ assert_eq!(Net::load(&home), Net::Sharing);+ assert!(apply(Change::Join("192.168.0.12".into())).unwrap_err().contains("share off"));+ assert_eq!(apply(Change::Leave).unwrap(), Net::Sharing);+ assert_eq!(apply(Change::Off).unwrap(), Net::Private);+ assert!(!tmp.path().join(FILE).exists());++ std::fs::write(tmp.path().join(FILE), "join 192.168.0.12:4242\n").unwrap();+ assert!(apply(Change::On).unwrap_err().contains("kanzo leave"));+ assert_eq!(apply(Change::Off).unwrap(), Net::Joined("192.168.0.12:4242".into()));+ assert_eq!(apply(Change::Leave).unwrap(), Net::Private);++ // A board config.toml opens to the network is shared, and can't join another.+ std::fs::write(tmp.path().join("config.toml"), "listen = \"0.0.0.0\"\n").unwrap();+ let home = Home::open(tmp.path().to_path_buf()).unwrap();+ assert_eq!(Net::load(&home), Net::Sharing);+ assert!(rt.block_on(change(&home, Change::Join("192.168.0.12".into()))).unwrap_err().contains("share off"));+ assert!(rt.block_on(change(&home, Change::Off)).unwrap_err().contains("config.toml"));+ }++ #[test]+ fn change_json() {+ assert_eq!(serde_json::to_string(&Change::On).unwrap(), r#"{"action":"on"}"#);+ let join: Change = serde_json::from_str(r#"{"action":"join","host":"pi.local"}"#).unwrap();+ assert!(matches!(join, Change::Join(h) if h == "pi.local"));+ }+}diff --git a/src/sync.rs b/src/sync.rsindex 942088d..822016d 100644--- a/src/sync.rs+++ b/src/sync.rs@@ -155,7 +155,8 @@ pub fn sync(home: &Home, keep: Option<Keep>, prompt: bool) -> Result<String> {let note = {let lock = home.lock_exclusive()?;Store::open(&home.db_path(), None)?.settle()?;- git(&["add", "--all"])?;+ // What this machine does on the network stays here.+ git(&["add", "--all", "--", ".", &format!(":(exclude){}", crate::share::FILE)])?;if lock.is_some() { String::new() } else { format!("\n{NO_LOCKS}") }};if !git_ok(&["diff", "--cached", "--quiet"]) {@@ -287,7 +288,7 @@ fn git_ok(dir: &Path, prompt: bool, args: &[&str]) -> bool {}/// The machine's name for commit messages, like "Ada's MacBook Air".-fn hostname() -> String {+pub fn hostname() -> String {let run = |cmd: &str, args: &[&str]| {Command::new(cmd).args(args)diff --git a/src/web.rs b/src/web.rsindex 8fed010..b94a668 100644--- a/src/web.rs+++ b/src/web.rs@@ -1,22 +1,25 @@//! `kanzo`: the board page, the small JSON API behind it, and MCP over HTTP at `/mcp`.-use std::net::{IpAddr, Ipv6Addr, SocketAddr};-use std::sync::Arc;+use std::collections::HashMap;+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};+use std::sync::{Arc, Mutex, OnceLock};+use std::time::{Duration, Instant};use anyhow::{Context, Result, bail};use axum::body::Bytes;-use axum::extract::{DefaultBodyLimit, Path, Query, Request, State};+use axum::extract::{ConnectInfo, DefaultBodyLimit, Path, Query, Request, State};use axum::http::{HeaderMap, HeaderValue, StatusCode, header};use axum::middleware::{self, Next};use axum::response::{Html, IntoResponse, Response};use axum::routing::{delete, get, patch, post};-use axum::{Json, Router};+use axum::{Extension, Json, Router};use serde::{Deserialize, Serialize};use serde_json::json;-use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::TcpListener;use tokio_util::sync::CancellationToken;use crate::home::Home;+use crate::share::{self, Change, Net};use crate::store::{self, Error, ImagesOf, Store, TaskPatch};use crate::{sync, update};@@ -33,12 +36,12 @@ const CSP: &str = "default-src 'none'; script-src 'self'; style-src 'self' 'unsapub async fn serve(home: Home, port: Option<u16>, open: bool) -> Result<()> {let port = port.unwrap_or(home.config.port);- let listen = home.config.listen;+ let guard = Arc::new(Guard::new(port, home.config.listen, Net::load(&home)));let url = format!("http://localhost:{port}");- let listener = match tokio::net::TcpListener::bind(SocketAddr::new(listen, port)).await {+ let listener = match TcpListener::bind(SocketAddr::new(guard.address(), port)).await {Ok(l) => l,Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => {- if is_kanzo(port).await {+ if share::is_kanzo(&format!("127.0.0.1:{port}")).await {println!("Kanzo is already running at {url}");if open {open_browser(&url);@@ -47,17 +50,18 @@ pub async fn serve(home: Home, port: Option<u16>, open: bool) -> Result<()> {}bail!("port {port} is used by another program; choose another with --port or in config.toml");}- Err(e) => return Err(e).context(format!("cannot listen on {listen} port {port}")),+ Err(e) => return Err(e).context(format!("cannot listen on {} port {port}", guard.address())),};#[cfg(windows)]exit_with_console();- let guard = Guard::new(port, !listen.is_loopback());println!("Kanzo board at {url}, data in {}", home.dir.display());- if guard.lan {- if let Some(name) = guard.names.iter().find(|n| n.ends_with(".local")) {- println!("On your network: http://{name}:{port} (or this machine's IP address)");+ match guard.net() {+ Net::Private => {}+ Net::Joined(host) => println!("It shows the board at {host}."),+ _ => {+ println!("{}", guard.status().message());+ println!("Anyone who can reach port {port} can read and change this board.");}- println!("Anyone who can reach port {port} can read and change this board.");}if home.config.mcp_http {println!("MCP over HTTP at {url}/mcp");@@ -67,34 +71,63 @@ pub async fn serve(home: Home, port: Option<u16>, open: bool) -> Result<()> {}// Cancelling this also ends open MCP streams, which would otherwise hold up shutdown.let shutdown = CancellationToken::new();- let app = router(home, guard, shutdown.clone());- let serve = |listener| {- let stop = shutdown.clone();- axum::serve(listener, app.clone()).with_graceful_shutdown(async move { stop.cancelled().await }).into_future()+ let app = router(home.clone(), guard.clone(), shutdown.clone());+ let serve = |listener, stop: CancellationToken| {+ let app = app.clone().into_make_service_with_connect_info::<SocketAddr>();+ tokio::spawn(+ axum::serve(listener, app).with_graceful_shutdown(async move { stop.cancelled().await }).into_future(),+ )};+ let mut running = Vec::new();// `localhost` is ::1 before 127.0.0.1 on many Linux systems, and not every// client (busybox wget, older Node) falls back, so listen on ::1 as well.- let v6 = match listen {- IpAddr::V4(ip) if ip.is_loopback() || ip.is_unspecified() => {- tokio::net::TcpListener::bind(SocketAddr::new(Ipv6Addr::LOCALHOST.into(), port)).await.ok()- }- _ => None,- };+ if let IpAddr::V4(ip) = home.config.listen+ && (ip.is_loopback() || ip.is_unspecified())+ && let Ok(v6) = TcpListener::bind(SocketAddr::new(Ipv6Addr::LOCALHOST.into(), port)).await+ {+ running.push(serve(v6, shutdown.clone()));+ }let stopper = shutdown.clone();tokio::spawn(async move {stop_signal().await;stopper.cancel();});- match v6 {- Some(v6) => {- let (a, b) = tokio::join!(serve(listener), serve(v6));- a.and(b)?;+ // Sharing turns on and off while the board runs: it stops taking connections on one+ // address and listens on the other. Connections already open finish as usual.+ let mut listener = listener;+ loop {+ let rebind = shutdown.child_token();+ *guard.rebind.lock().unwrap() = rebind.clone();+ running.push(serve(listener, rebind.clone()));+ rebind.cancelled().await;+ if shutdown.is_cancelled() {+ break;}- None => serve(listener).await?,+ listener = match listen_again(guard.address(), port).await {+ Ok(l) => l,+ Err(e) => {+ eprintln!("kanzo: cannot listen on {}: {e}", guard.address());+ listen_again(home.config.listen, port).await?+ }+ };+ }+ for task in running {+ task.await??;}Ok(())}+/// Binds once the old listener has let go of the port, which takes a moment.+async fn listen_again(ip: IpAddr, port: u16) -> std::io::Result<TcpListener> {+ for _ in 0..100 {+ match TcpListener::bind(SocketAddr::new(ip, port)).await {+ Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => tokio::time::sleep(Duration::from_millis(20)).await,+ bound => return bound,+ }+ }+ TcpListener::bind(SocketAddr::new(ip, port)).await+}+/// Ctrl-C, or SIGTERM from launchd or systemd stopping the service.async fn stop_signal() {#[cfg(unix)]@@ -116,16 +149,14 @@ async fn stop_signal() {}}-fn router(home: Home, guard: Guard, shutdown: CancellationToken) -> Router {- let mut app = Router::new();+fn router(home: Home, guard: Arc<Guard>, shutdown: CancellationToken) -> Router {+ // The board itself: on a computer that joined another's board, it comes from there.+ let mut shared = Router::new();if home.config.mcp_http {- app = app.nest_service("/mcp", crate::mcp::http_service(home.clone(), shutdown));+ shared = shared.nest_service("/mcp", crate::mcp::http_service(home.clone(), shutdown));}- app.route("/", get(|| async { Html(INDEX) }))- .route("/app.js", get(|| async { ([(header::CONTENT_TYPE, "text/javascript; charset=utf-8")], APP_JS) }))- .route("/logo.png", get(|| async { ([(header::CONTENT_TYPE, "image/png")], LOGO) }))+ let shared = shared.route("/images/{file}", get(image_file))- .route("/api/ping", get(|| async { "kanzo" })).route("/api/changes", get(changes)).route("/api/board", get(board)).route("/api/search", get(search))@@ -140,29 +171,99 @@ fn router(home: Home, guard: Guard, shutdown: CancellationToken) -> Router {.route("/api/images", post(save_image).layer(DefaultBodyLimit::max(IMAGE_LIMIT))).route("/api/images/{id}", delete(delete_image)).route("/api/tasks/{id}/images", post(attach_image))- .route("/api/update", get(update_status).post(update_now)).route("/api/sync", get(sync_status).post(sync_now).put(sync_repo)).route("/api/settings", patch(update_settings))- .layer(middleware::from_fn_with_state(Arc::new(guard), protect))+ .route_layer(middleware::from_fn_with_state(guard.clone(), forward));+ // This computer's own: the page, its version, and what it does on the network.+ Router::new()+ .route("/", get(|| async { Html(INDEX) }))+ .route("/app.js", get(|| async { ([(header::CONTENT_TYPE, "text/javascript; charset=utf-8")], APP_JS) }))+ .route("/logo.png", get(|| async { ([(header::CONTENT_TYPE, "image/png")], LOGO) }))+ .route("/api/ping", get(|| async { "kanzo" }))+ .route("/api/update", get(update_status).post(update_now))+ .route("/api/network", get(network).post(change_network).route_layer(middleware::from_fn(this_computer)))+ .merge(shared)+ .layer(Extension(guard.clone()))+ .layer(middleware::from_fn_with_state(guard, protect)).with_state(Arc::new(home))}-/// Which Host headers the board answers to.+/// Who may use the board: which Host headers it answers to, and whether other+/// computers may reach it. Also what this computer does on the network.////// DNS rebinding needs a domain name the attacker controls, so the board only/// accepts `localhost`, IP addresses and, when it listens on the network, this/// machine's own names. It never accepts other domain names.struct Guard {port: u16,- lan: bool,- /// This machine's names, like `pi` and `pi.local`; filled only when `lan`.- names: Vec<String>,-}+ /// `listen` from config.toml: where the board listens unless shared.+ listen: IpAddr,+ /// Changed while the board runs, by its settings and `kanzo share`, `join` and `leave`.+ net: Mutex<Net>,+ /// Other computers using the board: when each last asked for something, and its name.+ guests: Mutex<HashMap<IpAddr, (Instant, Option<String>)>>,+ /// This machine's names, like `pi` and `pi.local`, found the first time they're needed.+ names: OnceLock<Vec<String>>,+ /// Cancelled to listen on the address `net` now asks for.+ rebind: Mutex<CancellationToken>,+}++/// How long after its last request a guest still counts: its board asks every 2 seconds+/// while it's on screen.+const GUEST_GONE: Duration = Duration::from_secs(30);impl Guard {- fn new(port: u16, lan: bool) -> Self {- let mut names = Vec::new();- if lan {+ fn new(port: u16, listen: IpAddr, net: Net) -> Self {+ Self {+ port,+ listen,+ net: Mutex::new(net),+ guests: Mutex::default(),+ names: OnceLock::new(),+ rebind: Mutex::default(),+ }+ }++ fn net(&self) -> Net {+ self.net.lock().unwrap().clone()+ }++ /// Whether other computers may use the board.+ fn lan(&self) -> bool {+ self.net() == Net::Sharing+ }++ fn address(&self) -> IpAddr {+ if self.lan() && self.listen.is_loopback() { Ipv4Addr::UNSPECIFIED.into() } else { self.listen }+ }++ /// Takes on a change saved by `share::change`, and listens elsewhere if it asks to.+ fn set(&self, net: Net) {+ let before = self.address();+ *self.net.lock().unwrap() = net;+ if self.address() != before {+ self.rebind.lock().unwrap().cancel();+ }+ if !self.lan() {+ self.guests.lock().unwrap().clear();+ }+ }++ fn guests(&self) -> Vec<share::Guest> {+ let mut guests = self.guests.lock().unwrap();+ guests.retain(|_, (seen, _)| seen.elapsed() < GUEST_GONE);+ let mut list: Vec<share::Guest> =+ guests.iter().map(|(ip, (_, name))| share::Guest { name: name.clone(), address: *ip }).collect();+ list.sort_by_key(|g| g.address);+ list+ }++ fn status(&self) -> share::Status {+ share::Status::new(&self.net(), self.port, self.guests())+ }++ fn names(&self) -> &[String] {+ self.names.get_or_init(|| {let run = |cmd: &str, args: &[&str]| {std::process::Command::new(cmd).args(args)@@ -173,6 +274,7 @@ impl Guard {};// macOS keeps its Bonjour name apart; `hostname` there can be a DHCP address.let found = [run("scutil", &["--get", "LocalHostName"]), run("hostname", &[])];+ let mut names = Vec::new();for full in found.into_iter().flatten().filter(|n| !n.is_empty() && n.parse::<IpAddr>().is_err()) {let short = full.split('.').next().unwrap_or_default().to_string();for name in [format!("{short}.local"), full, short] {@@ -181,8 +283,8 @@ impl Guard {}}}- }- Self { port, lan, names }+ names+ })}fn allows(&self, host: &str) -> bool {@@ -198,14 +300,36 @@ impl Guard {if name.eq_ignore_ascii_case("localhost") || ip.is_some_and(|ip| ip.is_loopback()) {return true;}- self.lan && (ip.is_some() || self.names.iter().any(|n| n.eq_ignore_ascii_case(name)))+ self.lan() && (ip.is_some() || self.names().iter().any(|n| n.eq_ignore_ascii_case(name)))+ }+}++/// The other computer a request comes from, if not this one.+fn guest(req: &Request) -> Option<IpAddr> {+ req.extensions().get::<ConnectInfo<SocketAddr>>().map(|c| c.0.ip()).filter(|ip| !ip.is_loopback())+}++/// Hands the board's requests to the board this computer joined, if it did.+async fn forward(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> Response {+ match guard.net() {+ Net::Joined(host) => share::forward(&host, req).await,+ _ => next.run(req).await,}}-/// Refuses requests for a Host this board does not answer to, and browser-/// requests sent from any page other than the board itself. Adds security-/// headers to every reply.+/// What this computer does on the network is only for this computer to change.+async fn this_computer(req: Request, next: Next) -> Response {+ match guest(&req) {+ Some(_) => (StatusCode::FORBIDDEN, "only the computer with the board can change its network").into_response(),+ None => next.run(req).await,+ }+}++/// Refuses requests for a Host this board does not answer to, browser requests sent+/// from any page other than the board itself, and other computers unless the board is+/// shared. Adds security headers to every reply.async fn protect(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> Response {+ let guest = guest(&req);let ok = {let header = |name| req.headers().get(name).and_then(|h: &HeaderValue| h.to_str().ok());let host = header(header::HOST).unwrap_or("");@@ -215,8 +339,18 @@ async fn protect(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> R&& o.as_bytes()[..7].eq_ignore_ascii_case(b"http://")&& o.as_bytes()[7..].eq_ignore_ascii_case(host.as_bytes())};- guard.allows(host) && header(header::ORIGIN).is_none_or(same_origin)+ guard.allows(host) && header(header::ORIGIN).is_none_or(same_origin) && (guest.is_none() || guard.lan())};+ if let Some(ip) = guest.filter(|_| ok) {+ let name =+ req.headers().get(share::COMPUTER_HEADER).map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned());+ let mut guests = guard.guests.lock().unwrap();+ let guest = guests.entry(ip).or_insert((Instant::now(), None));+ guest.0 = Instant::now();+ if name.is_some() {+ guest.1 = name;+ }+ }let mut res = if ok {next.run(req).await} else {@@ -265,10 +399,13 @@ fn change_token(home: &Home, s: &Store) -> store::Result<String> {#[derive(Serialize)]struct Changes {changes: String,+ /// Other computers using the board, while it's shared.+ guests: Option<usize>,}-async fn changes(State(home): Shared) -> Response {- with_store(home, |h, s| Ok(Changes { changes: change_token(h, s)? })).await+async fn changes(State(home): Shared, Extension(guard): Extension<Arc<Guard>>) -> Response {+ let guests = guard.lan().then(|| guard.guests().len());+ with_store(home, move |h, s| Ok(Changes { changes: change_token(h, s)?, guests })).await}/// Done tasks the board gets unless it asks for all: the newest, which are all it shows.@@ -577,6 +714,27 @@ async fn save_image(State(home): Shared, headers: HeaderMap, body: Bytes) -> Res}}+/// What this computer does on the network: shares its board, uses another's, or neither.+async fn network(Extension(guard): Extension<Arc<Guard>>) -> Response {+ Json(guard.status()).into_response()+}++/// Shares the board or stops, or joins another computer's board or leaves it: the+/// settings window, `kanzo share`, `join` and `leave` all come here while the board runs.+async fn change_network(+ State(home): Shared,+ Extension(guard): Extension<Arc<Guard>>,+ Json(change): Json<Change>,+) -> Response {+ match share::change(&home, change).await {+ Ok(net) => {+ guard.set(net);+ Json(guard.status()).into_response()+ }+ Err(e) => (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response(),+ }+}+#[derive(Deserialize)]struct SyncRequest {/// "local" or "remote", once the board has asked which side to keep.@@ -661,18 +819,6 @@ async fn update_now(State(home): Shared) -> Response {}}-/// True when the program on `port` answers like a Kanzo board.-async fn is_kanzo(port: u16) -> bool {- let probe = async {- let mut conn = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.ok()?;- conn.write_all(b"GET /api/ping HTTP/1.0\r\nHost: localhost\r\n\r\n").await.ok()?;- let mut reply = String::new();- conn.read_to_string(&mut reply).await.ok()?;- Some(reply.ends_with("kanzo"))- };- tokio::time::timeout(std::time::Duration::from_secs(2), probe).await.ok().flatten().unwrap_or(false)-}-/// Exits when the console goes away: the service's conhost when the task is stopped, or/// the window the board was started in. Windows doesn't stop the program by itself.#[cfg(windows)]@@ -716,7 +862,7 @@ mod tests {#[test]fn hosts() {- let local = Guard { port: 4242, lan: false, names: vec![] };+ let local = Guard::new(4242, Ipv4Addr::LOCALHOST.into(), Net::Private);for ok in ["localhost", "localhost:4242", "127.0.0.1:4242", "[::1]:4242", "LOCALHOST:4242"] {assert!(local.allows(ok), "{ok}");}@@ -724,12 +870,18 @@ mod tests {assert!(!local.allows(bad), "{bad}");}- let lan = Guard { port: 4242, lan: true, names: vec!["pi".into(), "pi.local".into()] };+ let lan = Guard::new(4242, Ipv4Addr::LOCALHOST.into(), Net::Sharing);+ lan.names.set(vec!["pi".into(), "pi.local".into()]).unwrap();for ok in ["localhost:4242", "192.168.1.5:4242", "[fe80::1]:4242", "pi.local:4242", "pi:4242", "PI.LOCAL."] {assert!(lan.allows(ok), "{ok}");}for bad in ["evil.com:4242", "pi.evil.com:4242", "192.168.1.5:80"] {assert!(!lan.allows(bad), "{bad}");}++ // Stopping sharing closes the board to other computers again.+ lan.set(Net::Private);+ assert!(!lan.allows("192.168.1.5:4242"));+ assert_eq!(lan.address(), IpAddr::from(Ipv4Addr::LOCALHOST));}}