use std::{ env, fmt::Write as _, fs, path::{Path, PathBuf}, process, }; use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; mod projects; mod route_d; use texrra_engine::rust_typeset; fn main() { if let Err(error) = run() { eprintln!("error: {error}"); process::exit(1); } } fn run() -> Result<(), String> { let mut args = env::args().skip(1); let Some(command) = args.next() else { return Err("usage: texrra serve [input.tex] [port]".into()); }; if command != "serve" { return Err("the only command is `serve`".into()); } let input_path = args .next() .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from("examples/hello.tex")); let port = args .next() .map(|value| value.parse::().map_err(|_| "port must be a number")) .transpose()? .unwrap_or(4173); if args.next().is_some() { return Err("usage: texrra serve [input.tex] [port]".into()); } if !input_path.is_file() { return Err(format!( "input file does not exist: {}", input_path.display() )); } let projects_root = env::var_os("TEXRRA_PROJECTS_DIR") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from("projects")); let store = projects::ProjectStore::new(projects_root.clone())?; store.seed_from_input(&input_path)?; let web_root = find_web_root()?; let address = format!("127.0.0.1:{port}"); let server = Server::http(&address).map_err(|error| format!("could not start server: {error}"))?; println!("texrra is listening at http://{address}"); println!("Projects are stored in {}", projects_root.display()); match &web_root { Some(path) => println!("Serving the web frontend from {}", path.display()), None => println!( "warning: no web frontend found; clone texrra-web and set TEXRRA_WEB_DIR to its directory" ), } let mut compiler = rust_typeset::CompilerSession::default(); for request in server.incoming_requests() { if let Err(error) = handle_request( request, &input_path, &mut compiler, &store, web_root.as_deref(), ) { eprintln!("request error: {error}"); } } Ok(()) } fn handle_request( mut request: Request, input_path: &PathBuf, compiler: &mut rust_typeset::CompilerSession, store: &projects::ProjectStore, web_root: Option<&Path>, ) -> Result<(), String> { let url = request.url().to_string(); let path = url.split('?').next().unwrap_or(&url).to_string(); let method = request.method().clone(); if let Some(rest) = path.strip_prefix("/api/projects") { return handle_project_request(request, &method, rest, &url, compiler, store); } match (&method, path.as_str()) { (&Method::Get, "/") => serve_web_path(request, web_root, "/"), (&Method::Get, "/source") => { let source = fs::read_to_string(input_path) .map_err(|error| format!("could not read {}: {error}", input_path.display()))?; respond(request, 200, "text/plain; charset=utf-8", &source) } (&Method::Post, "/compile") => { let source = match read_and_save(&mut request, input_path) { Ok(source) => source, Err(error) => { return respond(request, 413, "text/plain; charset=utf-8", &error); } }; match compiler.compile(&source, &input_path.display().to_string()) { Ok(pdf) => respond_pdf(request, pdf), Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error), } } (&Method::Get, "/fonts.css") => match rust_typeset::preview_font_css() { Ok(css) => respond_with_cache( request, "text/css; charset=utf-8", css.into_bytes(), Some("public, max-age=3600"), ), Err(error) => respond(request, 500, "text/plain; charset=utf-8", &error), }, (&Method::Get, path) if path.starts_with("/fonts/") => { let name = &path["/fonts/".len()..]; match rust_typeset::preview_font_file(name) { Some(bytes) => respond_with_cache( request, "font/ttf", bytes, Some("public, max-age=31536000, immutable"), ), None => respond(request, 404, "text/plain; charset=utf-8", "not found"), } } (&Method::Post, path) if path.starts_with("/api/route-d/edit/") => { let unit = path["/api/route-d/edit/".len()..].parse::(); let Ok(unit) = unit else { return respond(request, 400, "text/plain; charset=utf-8", "invalid unit"); }; let bytes = match read_body_bytes(&mut request, MAX_SOURCE_BYTES) { Ok(bytes) => bytes, Err(error) => return respond(request, 413, "text/plain; charset=utf-8", &error), }; let source = match String::from_utf8(bytes) { Ok(source) => source, Err(_) => { return respond( request, 400, "text/plain; charset=utf-8", "source is not valid UTF-8", ); } }; match route_d::edit_json(&source, unit) { Ok(json) => respond(request, 200, "application/json; charset=utf-8", &json), Err(error) => respond(request, 422, "application/json; charset=utf-8", &error), } } (&Method::Post, "/api/route-d/pdf") => { let bytes = match read_body_bytes(&mut request, MAX_SOURCE_BYTES) { Ok(bytes) => bytes, Err(error) => return respond(request, 413, "text/plain; charset=utf-8", &error), }; let source = match String::from_utf8(bytes) { Ok(source) => source, Err(_) => { return respond( request, 400, "text/plain; charset=utf-8", "source must be UTF-8", ); } }; match route_d::pdf_bytes(&source) { Ok(pdf) => respond_pdf(request, pdf), Err(error) => respond(request, 422, "application/json; charset=utf-8", &error), } } (&Method::Post, "/api/route-d/preview") => { let bytes = match read_body_bytes(&mut request, MAX_SOURCE_BYTES) { Ok(bytes) => bytes, Err(error) => return respond(request, 413, "text/plain; charset=utf-8", &error), }; let source = match String::from_utf8(bytes) { Ok(source) => source, Err(_) => { return respond( request, 400, "text/plain; charset=utf-8", "source is not valid UTF-8", ); } }; match route_d::preview_json(&source) { Ok(json) => respond(request, 200, "application/json; charset=utf-8", &json), Err(error) => respond(request, 422, "application/json; charset=utf-8", &error), } } (&Method::Post, "/preview") => { let source = match read_and_save(&mut request, input_path) { Ok(source) => source, Err(error) => { return respond( request, 413, "application/json; charset=utf-8", &rust_typeset::preview_error_json(&error), ); } }; match compiler.preview_json(&source, &input_path.display().to_string()) { Ok(json) => respond(request, 200, "application/json; charset=utf-8", &json), Err(error) => respond( request, 422, "application/json; charset=utf-8", &rust_typeset::preview_error_json(&error), ), } } (&Method::Post, "/texrra") => { let source = match read_and_save(&mut request, input_path) { Ok(source) => source, Err(error) => { return respond(request, 413, "text/plain; charset=utf-8", &error); } }; match compiler.render_html_preview(&source, &input_path.display().to_string()) { Ok(html) => respond(request, 200, "text/html; charset=utf-8", &html), Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error), } } (&Method::Get, path) => serve_web_path(request, web_root, path), _ => respond(request, 404, "text/plain; charset=utf-8", "not found"), } } fn find_web_root() -> Result, String> { if let Some(value) = env::var_os("TEXRRA_WEB_DIR") { let path = PathBuf::from(value); if !path.join("index.html").is_file() { return Err(format!( "TEXRRA_WEB_DIR does not contain index.html: {}", path.display() )); } return Ok(Some(path)); } for candidate in [Path::new("../web"), Path::new("web")] { if candidate.join("index.html").is_file() { return Ok(Some(candidate.to_path_buf())); } } Ok(None) } fn serve_web_path(request: Request, web_root: Option<&Path>, path: &str) -> Result<(), String> { let Some(web_root) = web_root else { return respond( request, 200, "text/html; charset=utf-8", "texrra\

texrra web frontend not found

\

Clone texrra-web next to this checkout, or set\ TEXRRA_WEB_DIR to its directory, then reload.

", ); }; let mut relative = percent_decode(path.trim_start_matches('/')); if relative.is_empty() { relative = "index.html".to_string(); } if relative.contains("..") || relative.contains('\\') || relative.starts_with('/') { return respond(request, 404, "text/plain; charset=utf-8", "not found"); } let file = web_root.join(&relative); if !file.is_file() { return respond(request, 404, "text/plain; charset=utf-8", "not found"); } let canonical_root = web_root .canonicalize() .map_err(|error| format!("could not resolve web root: {error}"))?; let canonical_file = file .canonicalize() .map_err(|error| format!("could not resolve {}: {error}", file.display()))?; if !canonical_file.starts_with(&canonical_root) { return respond(request, 404, "text/plain; charset=utf-8", "not found"); } let body = fs::read(&canonical_file) .map_err(|error| format!("could not read {}: {error}", canonical_file.display()))?; respond_with_cache(request, web_content_type(&relative), body, Some("no-cache")) } fn web_content_type(path: &str) -> &'static str { let extension = path .rsplit_once('.') .map(|(_, extension)| extension.to_ascii_lowercase()) .unwrap_or_default(); match extension.as_str() { "html" => "text/html; charset=utf-8", "css" => "text/css; charset=utf-8", "js" | "mjs" => "text/javascript; charset=utf-8", "svg" => "image/svg+xml", "png" => "image/png", "jpg" | "jpeg" => "image/jpeg", "gif" => "image/gif", "webp" => "image/webp", "ico" => "image/x-icon", "json" => "application/json; charset=utf-8", "woff2" => "font/woff2", "woff" => "font/woff", "ttf" => "font/ttf", _ => "application/octet-stream", } } const MAX_SOURCE_BYTES: usize = 4 * 1024 * 1024; fn read_and_save(request: &mut Request, input_path: &Path) -> Result { let bytes = read_body_bytes(request, MAX_SOURCE_BYTES)?; let source = String::from_utf8(bytes).map_err(|_| "source is not valid UTF-8".to_string())?; fs::write(input_path, &source) .map_err(|error| format!("could not save {}: {error}", input_path.display()))?; Ok(source) } fn read_body_bytes(request: &mut Request, limit: usize) -> Result, String> { if request.body_length().is_some_and(|length| length > limit) { return Err(body_too_large_message(limit)); } let mut bytes = Vec::new(); let mut buffer = [0_u8; 8192]; let mut total = 0_usize; let reader = request.as_reader(); loop { let read = reader .read(&mut buffer) .map_err(|error| format!("could not read request body: {error}"))?; if read == 0 { break; } total += read; if total > limit { return Err(body_too_large_message(limit)); } bytes.extend_from_slice(&buffer[..read]); } Ok(bytes) } fn body_too_large_message(limit: usize) -> String { format!("request body is too large (limit {limit} bytes)") } fn respond(request: Request, status: u16, content_type: &str, body: &str) -> Result<(), String> { let header = Header::from_bytes("Content-Type", content_type) .map_err(|_| "invalid response header".to_string())?; let response = Response::from_string(body) .with_status_code(StatusCode(status)) .with_header(header); request .respond(response) .map_err(|error| format!("could not send response: {error}")) } fn respond_with_cache( request: Request, content_type: &str, body: Vec, cache_control: Option<&str>, ) -> Result<(), String> { let content_type = Header::from_bytes("Content-Type", content_type) .map_err(|_| "invalid response header".to_string())?; let cache_header = cache_control .map(|value| { Header::from_bytes("Cache-Control", value) .map_err(|_| "invalid response header".to_string()) }) .transpose()?; let mut response = Response::from_data(body).with_header(content_type); if let Some(cache_header) = cache_header { response = response.with_header(cache_header); } request .respond(response) .map_err(|error| format!("could not send response: {error}")) } fn respond_pdf(request: Request, pdf: Vec) -> Result<(), String> { let content_type = Header::from_bytes("Content-Type", "application/pdf") .map_err(|_| "invalid PDF response header".to_string())?; let disposition = Header::from_bytes("Content-Disposition", "inline; filename=preview.pdf") .map_err(|_| "invalid PDF response header".to_string())?; request .respond( Response::from_data(pdf) .with_header(content_type) .with_header(disposition), ) .map_err(|error| format!("could not send PDF response: {error}")) } const MAX_ZIP_BYTES: usize = 32 * 1024 * 1024; const MAX_UPLOAD_BYTES: usize = 16 * 1024 * 1024; fn expand_project_inputs(source: &str, store: &projects::ProjectStore, id: &str) -> String { let read = |path: &str| { let bytes = store .read_file(id, path) .ok() .or_else(|| store.read_file(id, &format!("{path}.tex")).ok())?; String::from_utf8(bytes).ok() }; route_d::expand_inputs(source, read) } fn handle_project_request( mut request: Request, method: &Method, rest: &str, url: &str, compiler: &mut rust_typeset::CompilerSession, store: &projects::ProjectStore, ) -> Result<(), String> { let segments = rest .split('/') .filter(|segment| !segment.is_empty()) .collect::>(); match (method, segments.as_slice()) { (&Method::Get, []) => match projects_json(store) { Ok(json) => respond_json(request, 200, &json), Err(error) => respond_api_error(request, 500, &error), }, (&Method::Post, []) => { let name = query_param(url, "name").unwrap_or_else(|| "project".to_string()); let bytes = match read_body_bytes(&mut request, MAX_ZIP_BYTES) { Ok(bytes) => bytes, Err(error) => return respond_api_error(request, 413, &error), }; match store.create_from_zip(&name, &bytes) { Ok(info) => respond_json(request, 201, &project_json(&info)), Err(error) => respond_api_error(request, 400, &error), } } (&Method::Post, ["new"]) => { let name = query_param(url, "name").unwrap_or_else(|| "Untitled project".to_string()); match store.create_empty(&name) { Ok(info) => respond_json(request, 201, &project_json(&info)), Err(error) => respond_api_error(request, 500, &error), } } (&Method::Get, [id]) => match store.info(id) { Ok(info) => respond_json(request, 200, &project_json(&info)), Err(error) => respond_api_error(request, 404, &error), }, (&Method::Delete, [id]) => match store.delete(id) { Ok(()) => respond_json(request, 200, "{\"deleted\":true}"), Err(error) => respond_api_error(request, 404, &error), }, (&Method::Get, [id, "zip"]) => match store.zip(id) { Ok(bytes) => { let name = format!("{id}.zip"); respond_file(request, "application/zip", bytes, Some(&name)) } Err(error) => respond_api_error(request, 404, &error), }, (&Method::Get, [id, "raw"]) => { let Some(path) = query_param(url, "path") else { return respond_api_error(request, 400, "missing file path"); }; match store.read_file(id, &path) { Ok(bytes) => { let download = query_param(url, "download").is_some(); let name = download.then(|| download_name(&path)); respond_file(request, file_content_type(&path), bytes, name.as_deref()) } Err(error) => respond_api_error(request, 404, &error), } } (&Method::Put, [id, "file"]) | (&Method::Post, [id, "files"]) => { let Some(path) = query_param(url, "path") else { return respond_api_error(request, 400, "missing file path"); }; let bytes = match read_body_bytes(&mut request, MAX_UPLOAD_BYTES) { Ok(bytes) => bytes, Err(error) => return respond_api_error(request, 413, &error), }; match store.write_file(id, &path, &bytes) { Ok(()) => respond_json(request, 200, "{\"saved\":true}"), Err(error) => respond_api_error(request, 400, &error), } } (&Method::Delete, [id, "file"]) => { let Some(path) = query_param(url, "path") else { return respond_api_error(request, 400, "missing file path"); }; match store.delete_file(id, &path) { Ok(()) => respond_json(request, 200, "{\"deleted\":true}"), Err(error) => respond_api_error(request, 404, &error), } } (&Method::Post, [id, "preview"]) => { let (source, file_name) = match store.main_source(id) { Ok(source) => source, Err(error) => return respond_api_error(request, 422, &error), }; if query_param(url, "engine").as_deref() == Some("route-d") { let expanded = expand_project_inputs(&source, &store, id); return match route_d::project_preview_json(id, &expanded) { Ok(json) => respond_json(request, 200, &json), Err(error) => respond_api_error(request, 422, &error), }; } match compiler.preview_json(&source, &file_name) { Ok(json) => respond_json(request, 200, &json), Err(error) => respond( request, 422, "application/json; charset=utf-8", &rust_typeset::preview_error_json(&error), ), } } (&Method::Post, [id, "pdf"]) => { let (source, file_name) = match store.main_source(id) { Ok(source) => source, Err(error) => return respond_api_error(request, 422, &error), }; if query_param(url, "engine").as_deref() == Some("route-d") { let expanded = expand_project_inputs(&source, &store, id); return match route_d::pdf_bytes(&expanded) { Ok(pdf) => respond_pdf(request, pdf), Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error), }; } match compiler.compile(&source, &file_name) { Ok(pdf) => respond_pdf(request, pdf), Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error), } } _ => respond_api_error(request, 404, "not found"), } } fn projects_json(store: &projects::ProjectStore) -> Result { let projects = store.list()?; let mut output = String::from("{\"projects\":["); for (index, info) in projects.iter().enumerate() { if index > 0 { output.push(','); } output.push_str(&project_json(info)); } output.push_str("]}"); Ok(output) } fn project_json(info: &projects::ProjectInfo) -> String { let mut files = String::new(); for (index, file) in info.files.iter().enumerate() { if index > 0 { files.push(','); } let _ = write!( files, "{{\"path\":{},\"size\":{}}}", rust_typeset::json_string(&file.path), file.size ); } format!( "{{\"id\":{},\"name\":{},\"mainFile\":{},\"createdAt\":{},\"updatedAt\":{},\"files\":[{}]}}", rust_typeset::json_string(&info.id), rust_typeset::json_string(&info.name), rust_typeset::json_string(&info.main_file), info.created_at, info.updated_at, files ) } fn query_param(url: &str, name: &str) -> Option { let (_, query) = url.split_once('?')?; for pair in query.split('&') { let (key, value) = pair.split_once('=').unwrap_or((pair, "")); if percent_decode(key) == name { return Some(percent_decode(value)); } } None } fn percent_decode(value: &str) -> String { let bytes = value.as_bytes(); let mut output = Vec::with_capacity(bytes.len()); let mut index = 0; while index < bytes.len() { match bytes[index] { b'%' if index + 2 < bytes.len() => { let high = hex_digit(bytes[index + 1]); let low = hex_digit(bytes[index + 2]); match (high, low) { (Some(high), Some(low)) => { output.push(high * 16 + low); index += 3; } _ => { output.push(b'%'); index += 1; } } } b'+' => { output.push(b' '); index += 1; } byte => { output.push(byte); index += 1; } } } String::from_utf8_lossy(&output).to_string() } fn hex_digit(byte: u8) -> Option { match byte { b'0'..=b'9' => Some(byte - b'0'), b'a'..=b'f' => Some(byte - b'a' + 10), b'A'..=b'F' => Some(byte - b'A' + 10), _ => None, } } fn respond_json(request: Request, status: u16, body: &str) -> Result<(), String> { respond(request, status, "application/json; charset=utf-8", body) } fn respond_api_error(request: Request, status: u16, message: &str) -> Result<(), String> { respond( request, status, "application/json; charset=utf-8", &format!("{{\"error\":{}}}", rust_typeset::json_string(message)), ) } fn respond_file( request: Request, content_type: &str, body: Vec, download_name: Option<&str>, ) -> Result<(), String> { let content_type_header = Header::from_bytes("Content-Type", content_type) .map_err(|_| "invalid response header".to_string())?; let mut response = Response::from_data(body) .with_status_code(StatusCode(200)) .with_header(content_type_header); if let Some(name) = download_name { let disposition = format!("attachment; filename=\"{}\"", ascii_file_name(name)); let header = Header::from_bytes("Content-Disposition", disposition) .map_err(|_| "invalid response header".to_string())?; response = response.with_header(header); } request .respond(response) .map_err(|error| format!("could not send response: {error}")) } fn file_content_type(path: &str) -> &'static str { let extension = path .rsplit_once('.') .map(|(_, extension)| extension.to_ascii_lowercase()) .unwrap_or_default(); match extension.as_str() { "png" => "image/png", "jpg" | "jpeg" => "image/jpeg", "gif" => "image/gif", "bmp" => "image/bmp", "webp" => "image/webp", "pdf" => "application/pdf", "zip" => "application/zip", "ttf" => "font/ttf", "otf" => "font/otf", _ => "text/plain; charset=utf-8", } } fn download_name(path: &str) -> String { path.rsplit('/').next().unwrap_or(path).to_string() } fn ascii_file_name(name: &str) -> String { name.chars() .map(|character| { if character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_' | ' ') { character } else { '_' } }) .collect() }