Skip to main content

litz_cli/
editor_link.rs

1//! `litz connect-editor`: the link between a build and the editor page.
2//!
3//! The editor cannot run a firmware toolchain, and `litz build` cannot draw a
4//! circuit. This module is the smallest bridge between the two: one process,
5//! one loopback port, a pairing token, WebSocket text messages for commands
6//! and build output, and an in-memory artifact store the editor fetches over
7//! plain HTTP.
8//!
9//! Nothing leaves the machine. The token is the only way in: a page that was
10//! not handed the URL printed by `connect-editor` gets 403 on every route.
11//! The socket accepts two commands — build this project's own recipe, and
12//! accept bytes a `litz build --push` already produced — and never a command
13//! string, so the link is not a shell.
14
15use crate::build;
16use sha2::{Digest, Sha256};
17use std::collections::HashMap;
18use std::io::{Read, Write};
19use std::net::{TcpListener, TcpStream};
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
22use std::sync::{Arc, Mutex, RwLock, mpsc};
23use std::time::Duration;
24
25pub const DEFAULT_PORT: u16 = 4317;
26
27/// A connection that sends nothing for this long is dropped. The editor pings
28/// every 25 seconds, so this only ends links whose page is gone.
29const IDLE: Duration = Duration::from_secs(90);
30/// JSON messages are tiny; only a pushed image is large.
31const MAX_FRAME: usize = 64 * 1024 * 1024;
32const MAX_ARTIFACTS: usize = 8;
33const LOCK_FILE: &str = ".litz/editor.json";
34const GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
35
36/// One image the editor can fetch, keyed by its SHA-256.
37struct Artifact {
38    board: Option<String>,
39    name: String,
40    bytes: Arc<Vec<u8>>,
41}
42
43/// A connected page (or a `--push` client) and the channel its writer drains.
44struct Session {
45    id: u64,
46    out: mpsc::Sender<Message>,
47}
48
49enum Message {
50    Text(String),
51    /// A WebSocket control frame. The server never sends a binary data frame:
52    /// images leave through the artifact route, which the page fetches itself.
53    Pong(Vec<u8>),
54    Close,
55}
56
57struct State {
58    dir: PathBuf,
59    token: String,
60    sessions: RwLock<Vec<Session>>,
61    artifacts: Mutex<Vec<(String, Artifact)>>,
62    next_id: AtomicU64,
63    /// One build at a time: two recipes writing the same output directory
64    /// would interleave their files and produce an image neither intended.
65    building: AtomicBool,
66}
67
68impl State {
69    fn keep(&self, sha: String, artifact: Artifact) {
70        let mut artifacts = self.artifacts.lock().unwrap();
71        artifacts.retain(|(key, _)| key != &sha);
72        artifacts.push((sha, artifact));
73        if artifacts.len() > MAX_ARTIFACTS {
74            artifacts.remove(0);
75        }
76    }
77
78    fn artifact(&self, sha: &str) -> Option<(Option<String>, String, Arc<Vec<u8>>)> {
79        let artifacts = self.artifacts.lock().unwrap();
80        artifacts
81            .iter()
82            .find(|(key, _)| key == sha)
83            .map(|(_, artifact)| {
84                (
85                    artifact.board.clone(),
86                    artifact.name.clone(),
87                    artifact.bytes.clone(),
88                )
89            })
90    }
91}
92
93/// Serve a project to an editor page until the process is interrupted.
94///
95/// `port` 0 asks the system for one, which is what the tests use.
96pub fn serve(dir: &Path, port: u16) -> Result<(), String> {
97    let (listener, token) = listen(dir, port)?;
98    let port = listener
99        .local_addr()
100        .map_err(|e| format!("editor link: {e}"))?
101        .port();
102    println!("litz: editor link ws://127.0.0.1:{port}/ws");
103    println!("litz: pairing code {token}");
104    println!("litz: paste both into the editor's Connect dialog; Ctrl-C to stop");
105    println!("litz: `litz build --push` from another terminal sends an image here");
106    accept_loop(listener, Arc::new(state(dir, token)));
107    Ok(())
108}
109
110/// Bind the loopback listener and claim the project's lock file.
111fn listen(dir: &Path, port: u16) -> Result<(TcpListener, String), String> {
112    let dir = dir
113        .canonicalize()
114        .map_err(|e| format!("{}: {e}", dir.display()))?;
115    if let Ok((running, _)) = read_lock(&dir)
116        && TcpStream::connect(("127.0.0.1", running)).is_ok()
117    {
118        return Err(format!(
119            "an editor link is already running on port {running}; close it first"
120        ));
121    }
122    let listener = TcpListener::bind(("127.0.0.1", port))
123        .map_err(|e| format!("cannot listen on 127.0.0.1:{port}: {e}"))?;
124    let actual = listener
125        .local_addr()
126        .map_err(|e| format!("editor link: {e}"))?
127        .port();
128    let token = token();
129    write_lock(&dir, actual, &token)?;
130    Ok((listener, token))
131}
132
133fn state(dir: &Path, token: String) -> State {
134    State {
135        dir: dir.to_path_buf(),
136        token,
137        sessions: RwLock::new(Vec::new()),
138        artifacts: Mutex::new(Vec::new()),
139        next_id: AtomicU64::new(1),
140        building: AtomicBool::new(false),
141    }
142}
143
144fn accept_loop(listener: TcpListener, state: Arc<State>) {
145    for stream in listener.incoming() {
146        match stream {
147            Ok(stream) => {
148                let state = state.clone();
149                std::thread::spawn(move || handle(stream, state));
150            }
151            Err(e) => eprintln!("litz: editor link: {e}"),
152        }
153    }
154}
155
156/// A project's built image, ready to hand to an editor.
157///
158/// `board` names a `[[board]]` entry; without one the recipe's `[build]
159/// firmware` is the answer, which is what a single-board project builds.
160pub fn push(dir: &Path, board: Option<&str>) -> Result<String, String> {
161    let (port, token) = read_lock(&dir.canonicalize().map_err(|e| e.to_string())?)?;
162    let (name, path) = build::image_for(dir, board)?;
163    let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
164    let sha = hex(&Sha256::digest(&bytes));
165    let file = path
166        .file_name()
167        .map(|name| name.to_string_lossy().into_owned())
168        .unwrap_or_else(|| "firmware.bin".to_string());
169
170    let mut stream = TcpStream::connect(("127.0.0.1", port))
171        .map_err(|e| format!("editor link on port {port}: {e}"))?;
172    stream
173        .set_read_timeout(Some(Duration::from_secs(30)))
174        .map_err(|e| e.to_string())?;
175    client_handshake(&mut stream, port, &token)?;
176    let published = publish_message(board.or(name.as_deref()), &file, &sha, bytes.len());
177    write_frame(&mut stream, 0x1, published.as_bytes(), true)?;
178    let ready = read_text(&mut stream, false)?;
179    if ready.get("type").and_then(|kind| kind.as_str()) != Some("publish.ready") {
180        return Err(format!("editor link refused the image: {ready}"));
181    }
182    write_frame(&mut stream, 0x2, &bytes, true)?;
183    let done = read_text(&mut stream, false)?;
184    match done.get("type").and_then(|kind| kind.as_str()) {
185        Some("pushed") => Ok(format!("pushed {file} to the editor ({sha})")),
186        _ => Err(format!("editor link did not accept the image: {done}")),
187    }
188}
189
190fn publish_message(board: Option<&str>, file: &str, sha: &str, size: usize) -> String {
191    serde_json::json!({
192        "type": "publish",
193        "board": board,
194        "name": file,
195        "sha256": sha,
196        "size": size,
197    })
198    .to_string()
199}
200
201// ---------------------------------------------------------------------------
202// HTTP side
203
204fn handle(mut stream: TcpStream, state: Arc<State>) {
205    let _ = stream.set_nodelay(true);
206    let _ = stream.set_read_timeout(Some(IDLE));
207    let Ok(request) = read_request(&mut stream) else {
208        return;
209    };
210    let origin = request.headers.get("origin").map(String::as_str);
211    let (path, query) = split_target(&request.target);
212    let provided = query.get("token").map(String::as_str).unwrap_or("");
213    let authorized = same(&state.token, provided);
214
215    if request.method == "OPTIONS" {
216        let _ = respond(&mut stream, 204, "text/plain", b"", origin, &[]);
217        return;
218    }
219    match path.as_str() {
220        "/health" => {
221            let body = serde_json::json!({
222                "ok": true,
223                "version": env!("CARGO_PKG_VERSION"),
224                "project": state.dir.file_name().and_then(|name| name.to_str()).unwrap_or(""),
225            })
226            .to_string();
227            let _ = respond(
228                &mut stream,
229                200,
230                "application/json",
231                body.as_bytes(),
232                origin,
233                &[],
234            );
235        }
236        "/ws" => {
237            if !authorized {
238                let _ = respond(
239                    &mut stream,
240                    403,
241                    "text/plain",
242                    b"the pairing code does not match",
243                    origin,
244                    &[],
245                );
246                return;
247            }
248            let Some(key) = request.headers.get("sec-websocket-key") else {
249                let _ = respond(
250                    &mut stream,
251                    400,
252                    "text/plain",
253                    b"not a websocket handshake",
254                    origin,
255                    &[],
256                );
257                return;
258            };
259            let accept = base64(&sha1(format!("{key}{GUID}").as_bytes()));
260            let _ = write!(
261                stream,
262                "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {accept}\r\n\r\n"
263            );
264            run_socket(stream, state);
265        }
266        target if target.starts_with("/artifact/") => {
267            if !authorized {
268                let _ = respond(
269                    &mut stream,
270                    403,
271                    "text/plain",
272                    b"the pairing code does not match",
273                    origin,
274                    &[],
275                );
276                return;
277            }
278            let sha = &target["/artifact/".len()..];
279            match state.artifact(sha) {
280                Some((_, _, bytes)) => {
281                    let _ = respond(
282                        &mut stream,
283                        200,
284                        "application/octet-stream",
285                        &bytes,
286                        origin,
287                        &["Content-Disposition", "attachment"],
288                    );
289                }
290                None => {
291                    let _ = respond(
292                        &mut stream,
293                        404,
294                        "text/plain",
295                        b"no such image",
296                        origin,
297                        &[],
298                    );
299                }
300            }
301        }
302        _ => {
303            let _ = respond(&mut stream, 404, "text/plain", b"not found", origin, &[]);
304        }
305    }
306}
307
308struct Request {
309    method: String,
310    target: String,
311    headers: HashMap<String, String>,
312}
313
314/// Read a request head without swallowing the bytes that follow it: the first
315/// WebSocket frame may already be in flight when the handshake is answered.
316fn read_request(stream: &mut TcpStream) -> Result<Request, String> {
317    let mut head = Vec::new();
318    let mut byte = [0u8; 1];
319    while !head.ends_with(b"\r\n\r\n") {
320        match stream.read(&mut byte) {
321            Ok(0) => return Err("connection closed during the request".to_string()),
322            Ok(_) => head.push(byte[0]),
323            Err(e) => return Err(e.to_string()),
324        }
325        if head.len() > 16 * 1024 {
326            return Err("request head too large".to_string());
327        }
328    }
329    let text = String::from_utf8_lossy(&head);
330    let mut lines = text.split("\r\n");
331    let mut first = lines.next().unwrap_or("").split(' ');
332    let method = first.next().unwrap_or("").to_string();
333    let target = first.next().unwrap_or("").to_string();
334    let mut headers = HashMap::new();
335    for line in lines {
336        if line.is_empty() {
337            break;
338        }
339        if let Some((name, value)) = line.split_once(':') {
340            headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_string());
341        }
342    }
343    Ok(Request {
344        method,
345        target,
346        headers,
347    })
348}
349
350fn split_target(target: &str) -> (String, HashMap<String, String>) {
351    let (path, query) = target.split_once('?').unwrap_or((target, ""));
352    let mut values = HashMap::new();
353    for pair in query.split('&') {
354        if let Some((key, value)) = pair.split_once('=') {
355            values.insert(key.to_string(), value.replace("%2D", "-"));
356        }
357    }
358    (path.to_string(), values)
359}
360
361#[allow(clippy::too_many_arguments)]
362fn respond(
363    stream: &mut TcpStream,
364    status: u16,
365    mime: &str,
366    body: &[u8],
367    origin: Option<&str>,
368    extra: &[&str],
369) -> std::io::Result<()> {
370    let reason = match status {
371        200 => "OK",
372        204 => "No Content",
373        400 => "Bad Request",
374        403 => "Forbidden",
375        404 => "Not Found",
376        _ => "Unknown",
377    };
378    let allow_origin = origin.unwrap_or("*");
379    write!(
380        stream,
381        "HTTP/1.1 {status} {reason}\r\nContent-Type: {mime}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\nAccess-Control-Allow-Origin: {allow_origin}\r\nAccess-Control-Allow-Methods: GET, POST, OPTIONS\r\nAccess-Control-Allow-Headers: *\r\nAccess-Control-Allow-Private-Network: true\r\nAccess-Control-Expose-Headers: Content-Length\r\nVary: Origin\r\n",
382        body.len()
383    )?;
384    let mut index = 0;
385    while index + 1 < extra.len() {
386        write!(stream, "{}: {}\r\n", extra[index], extra[index + 1])?;
387        index += 2;
388    }
389    write!(stream, "\r\n")?;
390    stream.write_all(body)
391}
392
393// ---------------------------------------------------------------------------
394// WebSocket side
395
396fn run_socket(stream: TcpStream, state: Arc<State>) {
397    let Ok(writer_stream) = stream.try_clone() else {
398        return;
399    };
400    let (out, incoming) = mpsc::channel();
401    std::thread::spawn(move || write_loop(writer_stream, incoming));
402
403    let id = state.next_id.fetch_add(1, Ordering::SeqCst);
404    state.sessions.write().unwrap().push(Session {
405        id,
406        out: out.clone(),
407    });
408
409    let hello = serde_json::json!({
410        "type": "hello",
411        "version": env!("CARGO_PKG_VERSION"),
412        "project": state.dir.file_name().and_then(|name| name.to_str()).unwrap_or(""),
413        "boards": boards(&state.dir),
414    });
415    let _ = out.send(Message::Text(hello.to_string()));
416
417    let mut stream = stream;
418    let mut upload: Option<Upload> = None;
419    while let Ok(frame) = read_frame(&mut stream, true) {
420        match frame.opcode {
421            0x8 => break,
422            0x9 => {
423                let _ = out.send(Message::Pong(frame.payload));
424            }
425            0xA => {}
426            0x2 => {
427                let Some(pending) = upload.take() else {
428                    let _ = out.send(Message::Text(error("an image arrived without a publish")));
429                    continue;
430                };
431                accept_image(&state, id, &out, pending, &frame.payload);
432            }
433            0x1 => {
434                let Ok(message) = serde_json::from_slice::<serde_json::Value>(&frame.payload)
435                else {
436                    let _ = out.send(Message::Text(error("each message is a JSON object")));
437                    continue;
438                };
439                match message.get("type").and_then(|kind| kind.as_str()) {
440                    Some("ping") => {
441                        let _ = out.send(Message::Text(r#"{"type":"pong"}"#.to_string()));
442                    }
443                    Some("build") => {
444                        let board = message
445                            .get("board")
446                            .and_then(|value| value.as_str())
447                            .map(str::to_string);
448                        start_build(state.clone(), out.clone(), board);
449                    }
450                    Some("publish") => match Upload::from_message(&message) {
451                        Some(pending) => {
452                            upload = Some(pending);
453                            let _ =
454                                out.send(Message::Text(r#"{"type":"publish.ready"}"#.to_string()));
455                        }
456                        None => {
457                            let _ = out
458                                .send(Message::Text(error("publish needs name, sha256 and size")));
459                        }
460                    },
461                    Some(other) => {
462                        let _ =
463                            out.send(Message::Text(error(&format!("unknown message {other:?}"))));
464                    }
465                    None => {
466                        let _ = out.send(Message::Text(error("a message needs a type")));
467                    }
468                }
469            }
470            _ => {}
471        }
472    }
473
474    state
475        .sessions
476        .write()
477        .unwrap()
478        .retain(|session| session.id != id);
479    let _ = out.send(Message::Close);
480}
481
482fn boards(dir: &Path) -> Vec<String> {
483    litz_engine::config::Config::load_project(dir)
484        .map(|config| config.boards.into_iter().map(|entry| entry.id).collect())
485        .unwrap_or_default()
486}
487
488fn error(message: &str) -> String {
489    serde_json::json!({ "type": "error", "message": message }).to_string()
490}
491
492struct Upload {
493    board: Option<String>,
494    name: String,
495    sha: String,
496    size: usize,
497}
498
499impl Upload {
500    fn from_message(message: &serde_json::Value) -> Option<Self> {
501        let text = |key: &str| {
502            message
503                .get(key)
504                .and_then(|value| value.as_str())
505                .map(str::to_string)
506        };
507        Some(Self {
508            board: text("board"),
509            name: text("name")?,
510            sha: text("sha256")?,
511            size: message.get("size")?.as_u64()? as usize,
512        })
513    }
514}
515
516fn accept_image(
517    state: &State,
518    id: u64,
519    out: &mpsc::Sender<Message>,
520    pending: Upload,
521    bytes: &[u8],
522) {
523    if bytes.len() != pending.size {
524        let _ = out.send(Message::Text(error(&format!(
525            "expected {} bytes, received {}",
526            pending.size,
527            bytes.len()
528        ))));
529        return;
530    }
531    let sha = hex(&Sha256::digest(bytes));
532    if !same(&sha, &pending.sha) {
533        let _ = out.send(Message::Text(error("the image does not match its sha256")));
534        return;
535    }
536    state.keep(
537        sha.clone(),
538        Artifact {
539            board: pending.board.clone(),
540            name: pending.name.clone(),
541            bytes: Arc::new(bytes.to_vec()),
542        },
543    );
544    // The publisher is answered with `pushed` instead: it asked for an
545    // acknowledgement, not a second copy of what it just sent.
546    broadcast_except(
547        state,
548        Some(id),
549        &artifact_message(pending.board.as_deref(), &pending.name, &sha, bytes.len()),
550    );
551    let _ = out.send(Message::Text(
552        serde_json::json!({ "type": "pushed", "sha256": sha }).to_string(),
553    ));
554}
555
556fn start_build(state: Arc<State>, out: mpsc::Sender<Message>, board: Option<String>) {
557    if state.building.swap(true, Ordering::SeqCst) {
558        let _ = out.send(Message::Text(error("a build is already running")));
559        return;
560    }
561    std::thread::spawn(move || {
562        let started = serde_json::json!({ "type": "build.started", "board": board }).to_string();
563        broadcast(&state, &started);
564        let outcome = run_build(&state, &out, board.as_deref());
565        if let Err(message) = outcome {
566            broadcast(
567                &state,
568                &serde_json::json!({ "type": "build.failed", "message": message }).to_string(),
569            );
570        }
571        state.building.store(false, Ordering::SeqCst);
572    });
573}
574
575fn run_build(
576    state: &State,
577    out: &mpsc::Sender<Message>,
578    board: Option<&str>,
579) -> Result<(), String> {
580    let mut emit = |chunk: &str| {
581        let message = serde_json::json!({ "type": "log", "chunk": chunk }).to_string();
582        let _ = out.send(Message::Text(message));
583    };
584    build::run_with(&state.dir, false, &mut emit)?;
585    let (name, path) = build::image_for(&state.dir, board)?;
586    let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
587    let size = bytes.len();
588    let sha = hex(&Sha256::digest(&bytes));
589    let file = path
590        .file_name()
591        .map(|name| name.to_string_lossy().into_owned())
592        .unwrap_or_else(|| "firmware.bin".to_string());
593    state.keep(
594        sha.clone(),
595        Artifact {
596            board: name.clone(),
597            name: file.clone(),
598            bytes: Arc::new(bytes),
599        },
600    );
601    broadcast(state, &artifact_message(name.as_deref(), &file, &sha, size));
602    Ok(())
603}
604
605fn artifact_message(board: Option<&str>, name: &str, sha: &str, size: usize) -> String {
606    serde_json::json!({
607        "type": "artifact",
608        "board": board,
609        "name": name,
610        "sha256": sha,
611        "size": size,
612        "url": format!("/artifact/{sha}"),
613    })
614    .to_string()
615}
616
617fn broadcast(state: &State, message: &str) {
618    broadcast_except(state, None, message);
619}
620
621fn broadcast_except(state: &State, skip: Option<u64>, message: &str) {
622    let sessions = state.sessions.read().unwrap();
623    for session in sessions.iter() {
624        if Some(session.id) == skip {
625            continue;
626        }
627        let _ = session.out.send(Message::Text(message.to_string()));
628    }
629}
630
631fn write_loop(mut stream: TcpStream, incoming: mpsc::Receiver<Message>) {
632    while let Ok(message) = incoming.recv() {
633        let written = match message {
634            Message::Text(text) => write_frame(&mut stream, 0x1, text.as_bytes(), false),
635            Message::Pong(payload) => write_frame(&mut stream, 0xA, &payload, false),
636            Message::Close => {
637                let _ = write_frame(&mut stream, 0x8, &[], false);
638                return;
639            }
640        };
641        if written.is_err() {
642            return;
643        }
644    }
645}
646
647struct Frame {
648    opcode: u8,
649    payload: Vec<u8>,
650}
651
652fn read_frame(stream: &mut TcpStream, from_client: bool) -> Result<Frame, String> {
653    let mut header = [0u8; 2];
654    read_exact(stream, &mut header)?;
655    let opcode = header[0] & 0x0f;
656    let masked = header[1] & 0x80 != 0;
657    let mut length = (header[1] & 0x7f) as u64;
658    if length == 126 {
659        let mut extended = [0u8; 2];
660        read_exact(stream, &mut extended)?;
661        length = u16::from_be_bytes(extended) as u64;
662    } else if length == 127 {
663        let mut extended = [0u8; 8];
664        read_exact(stream, &mut extended)?;
665        length = u64::from_be_bytes(extended);
666    }
667    if length as usize > MAX_FRAME {
668        return Err("frame too large".to_string());
669    }
670    if from_client && !masked {
671        // RFC 6455: every client frame is masked. Refusing the shape as well
672        // as the token keeps a stray local sender from writing bytes verbatim.
673        return Err("a client frame must be masked".to_string());
674    }
675    let mut payload = vec![0u8; length as usize];
676    if masked {
677        let mut mask = [0u8; 4];
678        read_exact(stream, &mut mask)?;
679        read_exact(stream, &mut payload)?;
680        for (index, byte) in payload.iter_mut().enumerate() {
681            *byte ^= mask[index % 4];
682        }
683    } else {
684        read_exact(stream, &mut payload)?;
685    }
686    Ok(Frame { opcode, payload })
687}
688
689fn write_frame(
690    stream: &mut TcpStream,
691    opcode: u8,
692    payload: &[u8],
693    mask: bool,
694) -> Result<(), String> {
695    let mut head = Vec::with_capacity(14);
696    head.push(0x80 | opcode);
697    let mask_bit = if mask { 0x80u8 } else { 0 };
698    if payload.len() < 126 {
699        head.push(mask_bit | payload.len() as u8);
700    } else if payload.len() <= u16::MAX as usize {
701        head.push(mask_bit | 126);
702        head.extend_from_slice(&(payload.len() as u16).to_be_bytes());
703    } else {
704        head.push(mask_bit | 127);
705        head.extend_from_slice(&(payload.len() as u64).to_be_bytes());
706    }
707    if mask {
708        let key = mask_key();
709        head.extend_from_slice(&key);
710        let mut body = payload.to_vec();
711        for (index, byte) in body.iter_mut().enumerate() {
712            *byte ^= key[index % 4];
713        }
714        stream.write_all(&head).map_err(|e| e.to_string())?;
715        stream.write_all(&body).map_err(|e| e.to_string())?;
716    } else {
717        stream.write_all(&head).map_err(|e| e.to_string())?;
718        stream.write_all(payload).map_err(|e| e.to_string())?;
719    }
720    stream.flush().map_err(|e| e.to_string())
721}
722
723fn read_exact(stream: &mut TcpStream, buffer: &mut [u8]) -> Result<(), String> {
724    let mut filled = 0;
725    while filled < buffer.len() {
726        match stream.read(&mut buffer[filled..]) {
727            Ok(0) => return Err("connection closed".to_string()),
728            Ok(n) => filled += n,
729            Err(e) => return Err(e.to_string()),
730        }
731    }
732    Ok(())
733}
734
735fn read_text(stream: &mut TcpStream, from_client: bool) -> Result<serde_json::Value, String> {
736    let frame = read_frame(stream, from_client)?;
737    if frame.opcode != 0x1 {
738        return Err(format!(
739            "expected a text frame, received opcode {}",
740            frame.opcode
741        ));
742    }
743    serde_json::from_slice(&frame.payload).map_err(|e| e.to_string())
744}
745
746fn client_handshake(stream: &mut TcpStream, port: u16, token: &str) -> Result<(), String> {
747    let key = base64(&entropy_bytes(16));
748    write!(
749        stream,
750        "GET /ws?token={token} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n"
751    )
752    .map_err(|e| e.to_string())?;
753    let mut head = Vec::new();
754    let mut byte = [0u8; 1];
755    while !head.ends_with(b"\r\n\r\n") {
756        match stream.read(&mut byte) {
757            Ok(0) => return Err("the link closed during the handshake".to_string()),
758            Ok(_) => head.push(byte[0]),
759            Err(e) => return Err(e.to_string()),
760        }
761        if head.len() > 16 * 1024 {
762            return Err("handshake head too large".to_string());
763        }
764    }
765    let text = String::from_utf8_lossy(&head);
766    let status = text.lines().next().unwrap_or("");
767    if !status.contains(" 101 ") {
768        return Err(format!("the link refused the handshake: {status}"));
769    }
770    // Drive the first server frame (hello) out of the way.
771    let hello = read_text(stream, false)?;
772    if hello.get("type").and_then(|kind| kind.as_str()) != Some("hello") {
773        return Err(format!("the link did not greet: {hello}"));
774    }
775    Ok(())
776}
777
778// ---------------------------------------------------------------------------
779// The project's lock file: how `build --push` finds a running link.
780
781fn write_lock(dir: &Path, port: u16, token: &str) -> Result<(), String> {
782    let path = dir.join(LOCK_FILE);
783    if let Some(parent) = path.parent() {
784        std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
785    }
786    let body = serde_json::json!({ "port": port, "token": token }).to_string();
787    std::fs::write(&path, body).map_err(|e| format!("{}: {e}", path.display()))?;
788    #[cfg(unix)]
789    {
790        use std::os::unix::fs::PermissionsExt;
791        let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
792    }
793    Ok(())
794}
795
796fn read_lock(dir: &Path) -> Result<(u16, String), String> {
797    let path = dir.join(LOCK_FILE);
798    let text = std::fs::read_to_string(&path).map_err(|_| {
799        format!(
800            "no editor link is running here; start `litz connect-editor` first ({} missing)",
801            path.display()
802        )
803    })?;
804    let value: serde_json::Value =
805        serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
806    let port = value
807        .get("port")
808        .and_then(|port| port.as_u64())
809        .ok_or_else(|| format!("{}: no port", path.display()))?;
810    let token = value
811        .get("token")
812        .and_then(|token| token.as_str())
813        .ok_or_else(|| format!("{}: no token", path.display()))?;
814    Ok((port as u16, token.to_string()))
815}
816
817// ---------------------------------------------------------------------------
818// Small primitives, kept here so the link adds no dependency.
819
820fn token() -> String {
821    let mut text = String::new();
822    for salt in 0..4u8 {
823        if salt > 0 {
824            text.push('-');
825        }
826        text.push_str(&format!("{:04X}", (entropy(salt) & 0xFFFF) as u16));
827    }
828    text
829}
830
831/// A value seeded from the OS through `RandomState`, mixed with the clock and
832/// the process id. `RandomState`'s keys come from the platform's entropy, and
833/// the salt keeps the four groups of a token from being slices of one value.
834fn entropy(salt: u8) -> u64 {
835    use std::hash::{BuildHasher, Hasher};
836    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
837    hasher.write_u8(salt);
838    hasher.write_u32(std::process::id());
839    hasher.write_u128(
840        std::time::SystemTime::now()
841            .duration_since(std::time::UNIX_EPOCH)
842            .map(|elapsed| elapsed.as_nanos())
843            .unwrap_or(0),
844    );
845    hasher.finish()
846}
847
848fn entropy_bytes(length: usize) -> Vec<u8> {
849    let mut bytes = Vec::with_capacity(length);
850    while bytes.len() < length {
851        bytes.extend_from_slice(&entropy(bytes.len() as u8).to_be_bytes());
852    }
853    bytes.truncate(length);
854    bytes
855}
856
857fn mask_key() -> [u8; 4] {
858    let value = entropy(0xFF).to_be_bytes();
859    [value[0], value[1], value[2], value[3]]
860}
861
862fn same(left: &str, right: &str) -> bool {
863    if left.len() != right.len() {
864        return false;
865    }
866    left.bytes()
867        .zip(right.bytes())
868        .fold(0u8, |acc, (a, b)| acc | (a ^ b))
869        == 0
870}
871
872fn hex(bytes: &[u8]) -> String {
873    let mut text = String::with_capacity(bytes.len() * 2);
874    for byte in bytes {
875        text.push_str(&format!("{byte:02x}"));
876    }
877    text
878}
879
880fn sha1(data: &[u8]) -> [u8; 20] {
881    let mut state: [u32; 5] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
882    let mut message = data.to_vec();
883    let bits = (message.len() as u64) * 8;
884    message.push(0x80);
885    while message.len() % 64 != 56 {
886        message.push(0);
887    }
888    message.extend_from_slice(&bits.to_be_bytes());
889
890    for block in message.chunks_exact(64) {
891        let mut words = [0u32; 80];
892        for (index, word) in block.chunks_exact(4).enumerate() {
893            words[index] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
894        }
895        for index in 16..80 {
896            words[index] =
897                (words[index - 3] ^ words[index - 8] ^ words[index - 14] ^ words[index - 16])
898                    .rotate_left(1);
899        }
900        let (mut a, mut b, mut c, mut d, mut e) =
901            (state[0], state[1], state[2], state[3], state[4]);
902        for (index, word) in words.iter().enumerate() {
903            let (function, constant) = match index {
904                0..=19 => ((b & c) | (!b & d), 0x5A827999u32),
905                20..=39 => (b ^ c ^ d, 0x6ED9EBA1),
906                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDC),
907                _ => (b ^ c ^ d, 0xCA62C1D6),
908            };
909            let temp = a
910                .rotate_left(5)
911                .wrapping_add(function)
912                .wrapping_add(e)
913                .wrapping_add(constant)
914                .wrapping_add(*word);
915            e = d;
916            d = c;
917            c = b.rotate_left(30);
918            b = a;
919            a = temp;
920        }
921        state[0] = state[0].wrapping_add(a);
922        state[1] = state[1].wrapping_add(b);
923        state[2] = state[2].wrapping_add(c);
924        state[3] = state[3].wrapping_add(d);
925        state[4] = state[4].wrapping_add(e);
926    }
927
928    let mut digest = [0u8; 20];
929    for (index, word) in state.iter().enumerate() {
930        digest[index * 4..index * 4 + 4].copy_from_slice(&word.to_be_bytes());
931    }
932    digest
933}
934
935fn base64(data: &[u8]) -> String {
936    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
937    let mut text = String::with_capacity(data.len().div_ceil(3) * 4);
938    for chunk in data.chunks(3) {
939        let a = chunk[0];
940        let b = chunk.get(1).copied().unwrap_or(0);
941        let c = chunk.get(2).copied().unwrap_or(0);
942        text.push(ALPHABET[(a >> 2) as usize] as char);
943        text.push(ALPHABET[(((a & 0x03) << 4) | (b >> 4)) as usize] as char);
944        if chunk.len() > 1 {
945            text.push(ALPHABET[(((b & 0x0F) << 2) | (c >> 6)) as usize] as char);
946        } else {
947            text.push('=');
948        }
949        if chunk.len() > 2 {
950            text.push(ALPHABET[(c & 0x3F) as usize] as char);
951        } else {
952            text.push('=');
953        }
954    }
955    text
956}
957
958#[cfg(test)]
959mod tests {
960    use super::*;
961    use std::time::Instant;
962
963    fn scratch(tag: &str) -> PathBuf {
964        static NEXT: AtomicU64 = AtomicU64::new(0);
965        let n = NEXT.fetch_add(1, Ordering::Relaxed);
966        let dir = std::env::temp_dir().join(format!("litz-link-{}-{n}-{tag}", std::process::id()));
967        let _ = std::fs::remove_dir_all(&dir);
968        std::fs::create_dir_all(&dir).unwrap();
969        dir
970    }
971
972    #[test]
973    fn sha1_matches_the_rfc_vectors() {
974        assert_eq!(
975            hex(&sha1(b"abc")),
976            "a9993e364706816aba3e25717850c26c9cd0d89d"
977        );
978        assert_eq!(
979            hex(&sha1(b"The quick brown fox jumps over the lazy dog")),
980            "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"
981        );
982    }
983
984    #[test]
985    fn the_accept_key_matches_the_rfc_example() {
986        let accept = base64(&sha1(
987            b"dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
988        ));
989        assert_eq!(accept, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
990    }
991
992    #[test]
993    fn a_token_is_four_groups_of_hex() {
994        let first = token();
995        assert_eq!(first.len(), 19, "{first}");
996        let groups: Vec<&str> = first.split('-').collect();
997        assert_eq!(groups.len(), 4);
998        for group in groups {
999            assert_eq!(group.len(), 4);
1000            assert!(group.chars().all(|c| c.is_ascii_hexdigit()), "{first}");
1001        }
1002        assert_ne!(first, token());
1003    }
1004
1005    #[test]
1006    fn frames_round_trip_a_masked_client_frame() {
1007        let dir = scratch("frames");
1008        let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
1009        let port = listener.local_addr().unwrap().port();
1010        let handle = std::thread::spawn(move || {
1011            let (mut server, _) = listener.accept().unwrap();
1012            read_frame(&mut server, true).unwrap()
1013        });
1014        let mut client = TcpStream::connect(("127.0.0.1", port)).unwrap();
1015        write_frame(&mut client, 0x1, b"{\"type\":\"ping\"}", true).unwrap();
1016        let frame = handle.join().unwrap();
1017        assert_eq!(frame.opcode, 0x1);
1018        assert_eq!(frame.payload, b"{\"type\":\"ping\"}");
1019        let _ = std::fs::remove_dir_all(&dir);
1020    }
1021
1022    #[test]
1023    fn a_lock_file_round_trips() {
1024        let dir = scratch("lock");
1025        write_lock(&dir, 4317, "ABCD-EF01-2345-6789").unwrap();
1026        let (port, token) = read_lock(&dir).unwrap();
1027        assert_eq!(port, 4317);
1028        assert_eq!(token, "ABCD-EF01-2345-6789");
1029        let _ = std::fs::remove_dir_all(&dir);
1030    }
1031
1032    #[test]
1033    fn a_build_streams_output_and_publishes_the_image() {
1034        let dir = scratch("build");
1035        std::fs::write(
1036            dir.join("litz.build.toml"),
1037            "[build]\nfirmware = \"out/app.bin\"\n\n[[step]]\nrun = \"mkdir -p out && printf hello > out/app.bin\"\n",
1038        )
1039        .unwrap();
1040
1041        let (listener, token) = listen(&dir, 0).unwrap();
1042        let port = listener.local_addr().unwrap().port();
1043        let state = Arc::new(state(&dir, token.clone()));
1044        let running = state.clone();
1045        std::thread::spawn(move || accept_loop(listener, running));
1046
1047        let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
1048        stream
1049            .set_read_timeout(Some(Duration::from_secs(20)))
1050            .unwrap();
1051        client_handshake(&mut stream, port, &token).unwrap();
1052        write_frame(&mut stream, 0x1, br#"{"type":"build"}"#, true).unwrap();
1053
1054        let mut artifact = None;
1055        let started = Instant::now();
1056        while started.elapsed() < Duration::from_secs(20) {
1057            let message = read_text(&mut stream, false).unwrap();
1058            match message.get("type").and_then(|kind| kind.as_str()) {
1059                Some("artifact") => {
1060                    artifact = Some(message);
1061                    break;
1062                }
1063                Some("build.failed") => panic!("build failed: {message}"),
1064                _ => {}
1065            }
1066        }
1067        let artifact = artifact.expect("the build published no image");
1068        let sha = artifact
1069            .get("sha256")
1070            .and_then(|value| value.as_str())
1071            .unwrap();
1072        assert_eq!(artifact["size"], 5);
1073        let (_, _, bytes) = state.artifact(sha).expect("the image is kept");
1074        assert_eq!(&bytes[..], b"hello");
1075        let _ = std::fs::remove_dir_all(&dir);
1076    }
1077}