// SPDX-License-Identifier: MIT //! The file formats a Lynx cart or program arrives in, read from the bytes, never the //! extension (`cart/formats.py`). //! //! docs/cartridge.md, "Formats". Three kinds, each loose or inside a `.zip` or //! `.7z`: //! //! - `lnx`: bytes 0-3 are `LYNX`; a 64-byte header (Handy's layout, K. Wilkins, //! zlib licence, `libretro-handy/lynx/cart.h`; bytes 59 and 60 a later //! community extension, cc65 `exehdr.s`) followed by the payload. //! - `bll`: bytes 0-1 are `$80 $08` and bytes 6-9 `BS93`: a RAM image with a //! big-endian load address (2-3) and a length that includes the 10-byte header //! (4-5) (42Bastian's BLL; MAME calls it "Quickload"). //! - `raw` (`.lyx`): none of the others; the payload alone, which is what //! No-Intro hashes. //! //! Every function here is pure: bytes in, values out. Unwrapping a `.7z` runs //! the system `7z` program (`7z e -so`) and reads its output in memory; //! nothing is extracted to disk. //! //! Differences forced by Rust: Python's exception `FormatError` is the error type //! [`FormatError`] returned in a `Result`; `split`'s header (an `LnxHeader`, a `BllHeader` //! or None) is the enum [`Header`]; `unwrap` takes a path or bytes as [`Source`]. use std::io::Read; use std::path::Path; use std::process::Command; pub const LNX_MAGIC: &[u8; 4] = b"LYNX"; pub const LNX_HEADER_SIZE: usize = 64; pub const BLL_HEADER_SIZE: usize = 10; pub const ROTATIONS: [&str; 3] = ["none", "left", "right"]; // header byte 58: 0, 1, 2 pub const EEPROM_TYPES: [&str; 6] = ["none", "93C46", "93C56", "93C66", "93C76", "93C86"]; // header byte 60, bits 0-2 /// Member names inside an archive that are never the cart (text that ships with dumps). const NOT_CARTS: [&str; 8] = [ ".txt", ".nfo", ".diz", ".xml", ".jpg", ".png", ".pdf", ".md", ]; /// The bytes are not a Lynx cart, program or archive holding one. #[derive(Debug, Clone)] pub struct FormatError(pub String); impl std::fmt::Display for FormatError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) } } impl std::error::Error for FormatError {} /// The 64-byte LNX header as written, before any judgement of its claims. #[derive(Clone, Debug, PartialEq, Eq)] pub struct LnxHeader { pub bank0_block: usize, pub bank1_block: usize, pub version: u16, pub name: String, pub maker: String, pub rotation: u8, // raw byte 58 pub audin: u8, // raw byte 59 pub eeprom: u8, // raw byte 60 pub spare: Vec, // bytes 61-63 } impl LnxHeader { /// 'none', 'left' or 'right'; None when the byte holds anything else. pub fn rotation_name(&self) -> Option<&'static str> { ROTATIONS.get(self.rotation as usize).copied() } /// The header bytes; the inverse of [`parse_lnx_header`]. pub fn to_bytes(&self) -> Vec { let latin1 = |s: &str, n: usize| { let mut v: Vec = s.chars().map(|c| c as u32 as u8).take(n).collect(); v.resize(n, 0); v }; let mut out = LNX_MAGIC.to_vec(); out.extend((self.bank0_block as u16).to_le_bytes()); out.extend((self.bank1_block as u16).to_le_bytes()); out.extend(self.version.to_le_bytes()); out.extend(latin1(&self.name, 32)); out.extend(latin1(&self.maker, 16)); out.extend([self.rotation, self.audin, self.eeprom]); let mut spare: Vec = self.spare.iter().copied().take(3).collect(); spare.resize(3, 0); out.extend(spare); out } } /// The 10-byte BLL (`BS93`) header. #[derive(Clone, Debug, PartialEq, Eq)] pub struct BllHeader { pub load: u16, pub length: u16, // includes the 10 header bytes } #[derive(Clone, Debug, PartialEq, Eq)] pub enum Header { Lnx(LnxHeader), Bll(BllHeader), } /// Header byte 60 as (type, organisation in bits), or None for no EEPROM. /// /// Bits 0-2 select 93C46..93C86 (1..5); bit 6 set means the 8-bit organisation, /// clear the 16-bit one; bit 7 asks for the save on an SD card (a flash-cart /// matter, ignored here). cc65's header source computes the size with a /// "please recheck" note (C13). A type of 6 or 7 is not defined: None. pub fn decode_eeprom(byte: u8) -> Option<(String, u32)> { let kind = (byte & 7) as usize; if kind == 0 || kind >= EEPROM_TYPES.len() { return None; } Some(( EEPROM_TYPES[kind].to_string(), if byte & 0x40 != 0 { 8 } else { 16 }, )) } /// The inverse of [`decode_eeprom`] (the SD-card bit is never set). pub fn encode_eeprom(eeprom: &Option<(String, u32)>) -> u8 { match eeprom { None => 0, Some((kind, organisation)) => { let index = EEPROM_TYPES.iter().position(|t| t == kind).unwrap_or(0) as u8; index | if *organisation == 8 { 0x40 } else { 0 } } } } /// 'lnx', 'bll' or 'raw', from the content alone. pub fn sniff(data: &[u8]) -> &'static str { if data.len() >= LNX_HEADER_SIZE && &data[..4] == LNX_MAGIC { return "lnx"; } if data.len() >= BLL_HEADER_SIZE && data[..2] == [0x80, 0x08] && &data[6..10] == b"BS93" { return "bll"; } "raw" } fn text(raw: &[u8]) -> String { raw.split(|&b| b == 0) .next() .unwrap_or(&[]) .iter() .map(|&b| b as char) .collect() } /// Read the claims of an LNX header; FormatError if there is none. pub fn parse_lnx_header(data: &[u8]) -> Result { if sniff(data) != "lnx" { return Err(FormatError("no LYNX header".into())); } Ok(LnxHeader { bank0_block: u16::from_le_bytes([data[4], data[5]]) as usize, bank1_block: u16::from_le_bytes([data[6], data[7]]) as usize, version: u16::from_le_bytes([data[8], data[9]]), name: text(&data[10..42]), maker: text(&data[42..58]), rotation: data[58], audin: data[59], eeprom: data[60], spare: data[61..64].to_vec(), }) } pub fn parse_bll_header(data: &[u8]) -> Result { if sniff(data) != "bll" { return Err(FormatError("no BS93 header".into())); } Ok(BllHeader { load: u16::from_be_bytes([data[2], data[3]]), length: u16::from_be_bytes([data[4], data[5]]), }) } /// (kind, header claims, payload). A BLL image is its own payload, header included. pub fn split(data: &[u8]) -> Result<(&'static str, Option
, Vec), FormatError> { let kind = sniff(data); if kind == "lnx" { return Ok(( kind, Some(Header::Lnx(parse_lnx_header(data)?)), data[LNX_HEADER_SIZE..].to_vec(), )); } if kind == "bll" { return Ok(( kind, Some(Header::Bll(parse_bll_header(data)?)), data.to_vec(), )); } Ok((kind, None, data.to_vec())) } // -- containers -------------------------------------------------------------- fn container(data: &[u8]) -> Option<&'static str> { if data.starts_with(b"PK\x03\x04") || data.starts_with(b"PK\x05\x06") { return Some("zip"); } if data.starts_with(b"7z\xbc\xaf\x27\x1c") { return Some("7z"); } None } /// The one cart member: text and pictures ignored; a LYNX/BS93 member preferred. fn pick(members: Vec<(String, Vec)>, origin: &str) -> Result<(String, Vec), FormatError> { let carts: Vec<(String, Vec)> = members .into_iter() .filter(|(n, d)| { let lower = n.to_lowercase(); !NOT_CARTS.iter().any(|e| lower.ends_with(e)) && !d.is_empty() }) .collect(); if carts.is_empty() { return Err(FormatError(format!("{origin}: no cart inside the archive"))); } let sniffed: Vec<&(String, Vec)> = carts.iter().filter(|(_, d)| sniff(d) != "raw").collect(); if carts.len() > 1 && sniffed.len() == 1 { return Ok(sniffed[0].clone()); } if carts.len() > 1 { let names: Vec<&str> = carts.iter().map(|(n, _)| n.as_str()).collect(); return Err(FormatError(format!( "{origin}: {} possible carts inside the archive: {}", carts.len(), names.join(", ") ))); } Ok(carts.into_iter().next().unwrap()) } fn zip_members(data: &[u8]) -> Result)>, FormatError> { let mut archive = zip::ZipArchive::new(std::io::Cursor::new(data)) .map_err(|e| FormatError(format!("bad zip: {e}")))?; let mut out = Vec::new(); for i in 0..archive.len() { let mut file = archive .by_index(i) .map_err(|e| FormatError(format!("bad zip: {e}")))?; if file.is_dir() { continue; } let mut bytes = Vec::new(); file.read_to_end(&mut bytes) .map_err(|e| FormatError(format!("bad zip: {e}")))?; out.push((file.name().to_string(), bytes)); } Ok(out) } fn which(tool: &str) -> Option { let path = std::env::var_os("PATH")?; std::env::split_paths(&path) .map(|d| d.join(tool)) .find(|p| p.is_file()) } fn sevenzip_members(path: &Path) -> Result)>, FormatError> { let tool = which("7z") .or_else(|| which("7za")) .or_else(|| which("7zr")) .ok_or_else(|| { FormatError(format!( "{}: reading .7z needs the 7z program on PATH", path.display() )) })?; let listing = Command::new(&tool) .args(["l", "-ba", "-slt"]) .arg(path) .output() .map_err(|e| FormatError(e.to_string()))?; let listing = String::from_utf8_lossy(&listing.stdout).to_string(); let mut names: Vec = Vec::new(); let mut is_dir: std::collections::HashMap = Default::default(); let mut current: Option = None; for line in listing.lines() { if let Some(rest) = line.strip_prefix("Path = ") { current = Some(rest.to_string()); names.push(rest.to_string()); } else if let (Some(rest), Some(c)) = (line.strip_prefix("Attributes = "), ¤t) { is_dir.insert(c.clone(), rest.starts_with('D')); } } let mut out = Vec::new(); for name in names { if is_dir.get(&name).copied().unwrap_or(false) { continue; } let data = Command::new(&tool) .args(["e", "-so"]) .arg(path) .arg(&name) .output() .map_err(|e| FormatError(e.to_string()))?; out.push((name, data.stdout)); } Ok(out) } /// A path or bytes, as `unwrap` takes them. pub enum Source<'a> { Path(&'a Path), Bytes(&'a [u8]), } /// Return (member name, bytes, container) for a path or bytes; container is /// 'zip', '7z' or 'loose'. Archives are read in memory, in place. pub fn unwrap( source: Source, name: Option<&str>, ) -> Result<(String, Vec, &'static str), FormatError> { let (path, data, origin, name) = match source { Source::Bytes(b) => ( None, b.to_vec(), name.unwrap_or("").to_string(), name.map(String::from), ), Source::Path(p) => { let data = std::fs::read(p).map_err(|e| FormatError(format!("{}: {e}", p.display())))?; let file = p .file_name() .map(|n| n.to_string_lossy().to_string()) .unwrap_or_default(); ( Some(p), data, p.display().to_string(), Some(name.map(String::from).unwrap_or(file)), ) } }; match container(&data) { Some("zip") => { let (member, inner) = pick(zip_members(&data)?, &origin)?; Ok((member, inner, "zip")) } Some(_) => { let path = path.ok_or_else(|| { FormatError("a .7z must be given as a path (it is read with the 7z program)".into()) })?; let (member, inner) = pick(sevenzip_members(path)?, &origin)?; Ok((member, inner, "7z")) } None => Ok((name.unwrap_or_else(|| "".into()), data, "loose")), } }