feat: render safe local media, MathML and Markdown anchors

This commit is contained in:
cflmy committed 2026-11-24 13:23:35 +08:00
1 parent 37291137eb
commit 07fa0d62a8
16 files changed
+1122 -67

No files matched your search

+7 -2
View File
@@ -70,6 +70,8 @@ pub fn build(input: BuildInput<'_>) -> PresentationModel {
PresentationModel {
version: PRESENTATION_VERSION,
title: document.title(),
heading_slugs: super::links::heading_slugs(&document.blocks),
media: Default::default(),
document,
semantic,
source_status: status,
@@ -313,7 +315,8 @@ impl DocumentService {
(None, _) => None,
};
Ok(build(BuildInput {
let media = super::media::collect(&self.project, relative, &document.blocks);
let mut model = build(BuildInput {
document,
analysis: verified.as_ref(),
status,
@@ -322,7 +325,9 @@ impl DocumentService {
navigation,
core_version: self.core_version.clone(),
run: attached_run.as_ref(),
}))
});
model.media = media;
Ok(model)
}
}
+14 -1
View File
@@ -71,6 +71,18 @@ impl AssetBundle {
"image/webp",
include_bytes!("../../assets/feather.webp"),
),
asset(
"noto-math",
"ttf",
"font/ttf",
include_bytes!("../../assets/NotoSansMath-Regular.ttf"),
),
asset(
"noto-math-license",
"txt",
"text/plain; charset=utf-8",
include_bytes!("../../assets/licenses/NOTO-MATH-LICENSE.txt"),
),
];
let mut by_hashed_name = HashMap::new();
for (index, asset) in assets.iter().enumerate() {
@@ -79,7 +91,8 @@ impl AssetBundle {
let css_text = std::str::from_utf8(assets[0].bytes).expect("reader.css is UTF-8");
let css_with_images = css_text
.replace("__BLOSSOM__", &assets[3].data_uri())
.replace("__FEATHER__", &assets[4].data_uri());
.replace("__FEATHER__", &assets[4].data_uri())
.replace("__MATH_FONT__", &assets[5].hashed_name());
let css_served_sha256 = sha256_hex(css_with_images.as_bytes());
Self {
assets,
+100
View File
@@ -0,0 +1,100 @@
//! Markdown navigation and URL normalization shared by Live and export.
use crate::reader::markdown::{DocBlock, Inline};
use crate::reader::source::{SafeRelativePath, SourceSpan};
use std::collections::{HashMap, HashSet};
pub fn decode(raw: &str) -> Option<String> {
let mut result = Vec::with_capacity(raw.len());
let mut bytes = raw.bytes();
while let Some(byte) = bytes.next() {
if byte == b'%' {
let hi = (bytes.next()? as char).to_digit(16)?;
let lo = (bytes.next()? as char).to_digit(16)?;
result.push((hi * 16 + lo) as u8);
} else {
result.push(byte);
}
}
String::from_utf8(result)
.ok()
.filter(|value| !value.chars().any(char::is_control))
}
pub fn relative_url(current: &SafeRelativePath, url: &str) -> Option<SafeRelativePath> {
let relative = decode(url)?;
if relative.is_empty() || relative.starts_with('/') || relative.contains(['\\', ':']) {
return None;
}
let parent = current.parent();
let mut components = parent
.as_ref()
.map_or_else(Vec::new, |parent| parent.as_str().split('/').collect());
for part in relative.split('/') {
match part {
"" | "." => {}
".." => {
components.pop()?;
}
_ => components.push(part),
}
}
SafeRelativePath::parse(&components.join("/")).ok()
}
pub fn heading_slugs(blocks: &[DocBlock]) -> HashMap<SourceSpan, String> {
let mut slugs = HashMap::new();
let mut used = HashSet::new();
visit_headings(blocks, &mut |span, content| {
let label = content.iter().map(Inline::plain_text).collect::<String>();
let label = ["@exec", "@knowledge"]
.into_iter()
.find_map(|prefix| {
label
.strip_prefix(prefix)
.filter(|suffix| suffix.starts_with(char::is_whitespace))
})
.unwrap_or(&label)
.trim();
let base: String = label
.to_lowercase()
.chars()
.filter_map(|ch| {
if ch.is_whitespace() {
Some('-')
} else if ch.is_alphanumeric() || matches!(ch, '-' | '_') {
Some(ch)
} else {
None
}
})
.collect();
let base = if base.is_empty() { "section" } else { &base };
let base = if base.starts_with("mq-") {
format!("section-{base}")
} else {
base.to_string()
};
let mut slug = base.clone();
let mut suffix = 1;
while !used.insert(slug.clone()) {
slug = format!("{base}-{suffix}");
suffix += 1;
}
slugs.insert(span, slug);
});
slugs
}
fn visit_headings(blocks: &[DocBlock], visit: &mut impl FnMut(SourceSpan, &[Inline])) {
for block in blocks {
match block {
DocBlock::Heading { span, content, .. } => visit(*span, content),
DocBlock::List { items, .. } => visit_headings(items, visit),
DocBlock::ListItem { children, .. } | DocBlock::BlockQuote { children, .. } => {
visit_headings(children, visit)
}
_ => {}
}
}
}
+124
View File
@@ -0,0 +1,124 @@
//! Bounded TeX math to inert MathML, shared by all rendering modes.
use pulldown_latex::{config::DisplayMode, push_mathml, Parser, RenderConfig, Storage};
pub fn render(source: &str, block: bool) -> Option<String> {
if source.len() > 4096
|| source.chars().filter(|ch| *ch == '{').count() > 128
|| source.split('\\').skip(1).any(|rest| {
let end = rest
.find(|ch: char| !ch.is_ascii_alphabetic())
.unwrap_or(rest.len());
matches!(
&rest[..end],
"def"
| "gdef"
| "edef"
| "xdef"
| "newcommand"
| "renewcommand"
| "providecommand"
| "let"
| "futurelet"
| "csname"
| "input"
| "include"
| "href"
| "url"
| "includegraphics"
| "htmlClass"
| "htmlStyle"
| "htmlId"
)
})
{
return None;
}
let storage = Storage::new();
let config = RenderConfig {
display_mode: if block {
DisplayMode::Block
} else {
DisplayMode::Inline
},
..Default::default()
};
let mut html = String::new();
let mut parsed = true;
let parser = Parser::new(source, &storage).inspect(|event| parsed &= event.is_ok());
push_mathml(&mut html, parser, config).ok()?;
if !parsed || html.len() > 64 * 1024 {
return None;
}
let xml = roxmltree::Document::parse(&html).ok()?;
if xml.root_element().tag_name().name() != "math" {
return None;
}
let safe = xml
.descendants()
.filter(roxmltree::Node::is_element)
.all(|node| {
matches!(
node.tag_name().name(),
"math"
| "mrow"
| "mi"
| "mo"
| "mn"
| "mtext"
| "mfrac"
| "msqrt"
| "mroot"
| "msub"
| "msup"
| "msubsup"
| "munder"
| "mover"
| "munderover"
| "mtable"
| "mtr"
| "mtd"
| "mspace"
| "mpadded"
| "mstyle"
| "menclose"
| "mphantom"
| "mmultiscripts"
| "mprescripts"
| "none"
) && node.attributes().all(|attr| {
attr.namespace().is_none()
&& matches!(
attr.name(),
"display"
| "mathvariant"
| "mathsize"
| "mathcolor"
| "displaystyle"
| "scriptlevel"
| "stretchy"
| "symmetric"
| "movablelimits"
| "form"
| "fence"
| "separator"
| "lspace"
| "rspace"
| "minsize"
| "maxsize"
| "accent"
| "accentunder"
| "linethickness"
| "width"
| "height"
| "depth"
| "columnalign"
| "rowalign"
| "rowspacing"
| "columnspacing"
| "notation"
)
})
});
safe.then_some(html)
}
+302
View File
@@ -0,0 +1,302 @@
//! Bounded project-local assets used by the reader and static export.
use crate::reader::links::relative_url;
use crate::reader::markdown::{DocBlock, Inline};
use crate::reader::source::{sha256_hex, Project, SafeRelativePath};
use image::{ImageFormat, ImageReader};
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::io::{Cursor, Read};
use std::sync::Arc;
const MAX_BYTES: usize = 4 * 1024 * 1024;
const MAX_DOCUMENT_BYTES: usize = 16 * 1024 * 1024;
const MAX_REFERENCES: usize = 128;
const MAX_AXIS: u32 = 8192;
const MAX_PIXELS: u64 = 16_000_000;
#[derive(Debug)]
pub struct Media {
pub path: SafeRelativePath,
pub bytes: Vec<u8>,
pub digest: String,
pub mime: &'static str,
pub extension: &'static str,
pub width: u32,
pub height: u32,
}
impl Media {
pub fn filename(&self) -> String {
format!("{}.{}", self.digest, self.extension)
}
}
pub fn collect(
project: &Project,
current: &SafeRelativePath,
blocks: &[DocBlock],
) -> BTreeMap<String, Arc<Media>> {
let mut urls = BTreeSet::new();
scan_blocks(blocks, &mut urls);
let mut total = 0;
let mut resolved = BTreeMap::<SafeRelativePath, Arc<Media>>::new();
let mut result = BTreeMap::new();
for url in urls {
let Some(path) = relative_url(current, url) else {
continue;
};
if let Some(media) = resolved.get(&path) {
result.insert(url.to_string(), Arc::clone(media));
continue;
}
if let Some(media) = load(project, &path) {
total += media.bytes.len();
if total > MAX_DOCUMENT_BYTES {
break;
}
let media = Arc::new(media);
resolved.insert(path, Arc::clone(&media));
result.insert(url.to_string(), media);
}
}
result
}
fn scan_blocks<'a>(blocks: &'a [DocBlock], urls: &mut BTreeSet<&'a str>) {
for block in blocks {
match block {
DocBlock::Heading { content, .. } | DocBlock::Paragraph { content, .. } => {
scan_inlines(content, urls)
}
DocBlock::List { items, .. } => scan_blocks(items, urls),
DocBlock::ListItem { children, .. } | DocBlock::BlockQuote { children, .. } => {
scan_blocks(children, urls)
}
DocBlock::Table { header, rows, .. } => {
for cell in header.iter().chain(rows.iter().flatten()) {
scan_inlines(cell, urls);
}
}
_ => {}
}
}
}
fn scan_inlines<'a>(inlines: &'a [Inline], urls: &mut BTreeSet<&'a str>) {
for inline in inlines {
if urls.len() >= MAX_REFERENCES {
return;
}
match inline {
Inline::Image { url, .. } => {
urls.insert(url);
}
Inline::Emph { children, .. }
| Inline::Strong { children, .. }
| Inline::Strikethrough { children, .. }
| Inline::Link { children, .. } => scan_inlines(children, urls),
_ => {}
}
}
}
pub fn load(project: &Project, path: &SafeRelativePath) -> Option<Media> {
let extension = path.file_name().rsplit_once('.')?.1.to_ascii_lowercase();
let (mime, extension, format) = match extension.as_str() {
"png" => ("image/png", "png", Some(ImageFormat::Png)),
"jpeg" | "jpg" => ("image/jpeg", "jpg", Some(ImageFormat::Jpeg)),
"gif" => ("image/gif", "gif", Some(ImageFormat::Gif)),
"webp" => ("image/webp", "webp", Some(ImageFormat::WebP)),
"svg" => ("image/svg+xml", "svg", None),
_ => return None,
};
let file = open_beneath(project, path)?;
let metadata = file.metadata().ok()?;
if !metadata.is_file() || metadata.len() > MAX_BYTES as u64 {
return None;
}
let mut bytes = Vec::with_capacity(metadata.len() as usize);
file.take(MAX_BYTES as u64 + 1)
.read_to_end(&mut bytes)
.ok()?;
if bytes.len() > MAX_BYTES {
return None;
}
let (width, height) = if let Some(format) = format {
if image::guess_format(&bytes).ok()? != format {
return None;
}
let dimensions = ImageReader::with_format(Cursor::new(&bytes), format)
.into_dimensions()
.ok()?;
if !valid_dimensions(dimensions.0, dimensions.1) {
return None;
}
let mut decoder = ImageReader::with_format(Cursor::new(&bytes), format);
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_AXIS);
limits.max_image_height = Some(MAX_AXIS);
limits.max_alloc = Some(128 * 1024 * 1024);
decoder.limits(limits);
decoder.decode().ok()?;
dimensions
} else {
svg_dimensions(&bytes)?
};
if !valid_dimensions(width, height) {
return None;
}
Some(Media {
path: path.clone(),
digest: sha256_hex(&bytes),
bytes,
mime,
extension,
width,
height,
})
}
fn valid_dimensions(width: u32, height: u32) -> bool {
width > 0
&& height > 0
&& width <= MAX_AXIS
&& height <= MAX_AXIS
&& u64::from(width) * u64::from(height) <= MAX_PIXELS
}
#[cfg(target_os = "linux")]
fn open_beneath(project: &Project, path: &SafeRelativePath) -> Option<File> {
use std::os::fd::{AsRawFd, FromRawFd};
let root = project.root_handle();
let name = std::ffi::CString::new(path.as_str()).ok()?;
// SAFETY: open_how is a C struct of integer fields.
let mut how: libc::open_how = unsafe { std::mem::zeroed() };
how.flags = (libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NONBLOCK) as u64;
how.resolve = libc::RESOLVE_BENEATH | libc::RESOLVE_NO_MAGICLINKS;
// SAFETY: the descriptor and both pointers stay valid for openat2.
let fd = unsafe {
libc::syscall(
libc::SYS_openat2,
root.as_raw_fd(),
name.as_ptr(),
&how as *const libc::open_how,
std::mem::size_of_val(&how),
)
};
if fd < 0 {
return None;
}
// SAFETY: openat2 returned a new owned descriptor.
Some(unsafe { File::from_raw_fd(fd as std::os::fd::RawFd) })
}
#[cfg(not(target_os = "linux"))]
fn open_beneath(_project: &Project, _path: &SafeRelativePath) -> Option<File> {
None
}
fn svg_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
const SVG: &str = "http://www.w3.org/2000/svg";
let xml = std::str::from_utf8(bytes).ok()?;
let options = roxmltree::ParsingOptions {
nodes_limit: 10_000,
..Default::default()
};
let tree = roxmltree::Document::parse_with_options(xml, options).ok()?;
if tree.descendants().any(|node| node.is_pi()) {
return None;
}
let root = tree.root_element();
if !root.has_tag_name((SVG, "svg")) {
return None;
}
for node in tree.descendants().filter(roxmltree::Node::is_element) {
if node.tag_name().namespace() != Some(SVG)
|| !matches!(
node.tag_name().name(),
"svg"
| "g"
| "path"
| "rect"
| "circle"
| "ellipse"
| "line"
| "polyline"
| "polygon"
| "text"
| "tspan"
| "title"
| "desc"
)
{
return None;
}
for attr in node.attributes() {
if attr.namespace().is_some()
|| !matches!(
attr.name(),
"width"
| "height"
| "viewBox"
| "preserveAspectRatio"
| "x"
| "y"
| "x1"
| "x2"
| "y1"
| "y2"
| "rx"
| "ry"
| "r"
| "cx"
| "cy"
| "d"
| "points"
| "transform"
| "fill"
| "fill-rule"
| "fill-opacity"
| "stroke"
| "stroke-width"
| "stroke-opacity"
| "stroke-linecap"
| "stroke-linejoin"
| "stroke-dasharray"
| "opacity"
| "font-size"
| "text-anchor"
| "dominant-baseline"
)
|| (matches!(attr.name(), "fill" | "stroke")
&& !attr
.value()
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || ch == '#'))
{
return None;
}
}
}
let dimension = |key| {
root.attribute(key)?
.trim_end_matches("px")
.parse::<u32>()
.ok()
};
if let (Some(width), Some(height)) = (dimension("width"), dimension("height")) {
return Some((width, height));
}
let viewbox: Vec<f64> = root
.attribute("viewBox")?
.split(|ch: char| ch.is_whitespace() || ch == ',')
.filter(|part| !part.is_empty())
.map(str::parse)
.collect::<Result<_, _>>()
.ok()?;
if viewbox.len() != 4 || !viewbox.iter().all(|value| value.is_finite()) {
return None;
}
Some((viewbox[2].ceil() as u32, viewbox[3].ceil() as u32))
}
+3
View File
@@ -6,7 +6,10 @@
pub mod assemble;
pub mod assets;
pub mod links;
pub mod markdown;
pub mod math;
pub mod media;
pub mod model;
pub mod render;
pub mod source;
+2
View File
@@ -91,6 +91,8 @@ pub struct PresentationModel {
pub version: u32,
pub title: String,
pub document: DocumentModel,
pub heading_slugs: std::collections::HashMap<crate::reader::source::SourceSpan, String>,
pub media: std::collections::BTreeMap<String, std::sync::Arc<super::media::Media>>,
pub semantic: Option<SemanticProjection>,
pub source_status: SourceStatus,
/// Human-readable reason for a degraded status (already normalized: no
+91 -54
View File
@@ -41,7 +41,23 @@ impl LinkPolicy {
for _ in 0..*page_depth {
prefix.push_str("../");
}
format!("{prefix}pages/{}.html", target.as_str())
format!(
"{prefix}pages/{}.html",
percent_encode_path(target.as_str())
)
}
}
}
fn media_href(&self, media: &super::media::Media) -> String {
match self {
LinkPolicy::LocalServer => format!(
"/media/{}?path={}",
media.filename(),
percent_encode_path(media.path.as_str())
),
LinkPolicy::StaticRelative { page_depth } => {
format!("{}media/{}", "../".repeat(*page_depth), media.filename())
}
}
}
@@ -814,6 +830,18 @@ fn render_block(
} => {
let unit = resolve_heading_unit(model, *span, *level);
let anchor = anchor_for_span(span.start, span.end);
let slug = model
.heading_slugs
.get(span)
.map(String::as_str)
.unwrap_or(&anchor);
if slug != anchor {
let _ = write!(
html,
"<span class=\"mq-heading-anchor\" id=\"{}\" aria-hidden=\"true\"></span>",
escape_attr(&anchor)
);
}
let (badge, cleaned) = display_heading_content(content, unit);
let data_semantic = if let Some((_, data)) = badge {
data
@@ -830,7 +858,7 @@ fn render_block(
html,
"<h{} id=\"{}\" data-source-id=\"{}\" data-semantic=\"{}\">",
level,
escape_attr(&anchor),
escape_attr(slug),
source_id_id(model, *span),
data_semantic,
);
@@ -979,13 +1007,13 @@ fn render_block(
DocBlock::MathBlock { span, literal } => {
let _ = write!(
html,
"<div class=\"mq-math-block\" data-resource-kind=\"formula\" data-source-id=\"{}\"><code>{}</code><span class=\"mq-math-note\">公式原文 · 未渲染数学</span></div>\n",
"<div class=\"mq-math-block\" data-resource-kind=\"formula\" data-source-id=\"{}\">{}</div>\n",
escape_attr(&source_id(
&model.document.identity.module_id,
*span,
"resource-formula"
)),
escape_text(literal)
render_math(literal, true)
);
}
DocBlock::ThematicBreak { .. } => html.push_str("<hr/>\n"),
@@ -1220,7 +1248,7 @@ fn render_inline(
} => {
let reference = projection.and_then(|projection| projection.reference_for_span(*span));
let state = reference.map(|reference| reference.state.as_str());
let target = resolve_link(url, current, &ctx.links);
let target = resolve_link(url, current, model, &ctx.links);
match target {
Some(href) => {
let _ = write!(html, "<a href=\"{href}\"", href = escape_attr(&href));
@@ -1246,17 +1274,14 @@ fn render_inline(
Inline::Image {
url, alt, title, ..
} => {
// Remote or unverified images are never loaded implicitly.
let _ = (url, title);
let _ = write!(
html,
"<span class=\"mq-raw-omitted\" role=\"note\">[图片已阻止自动加载:{}]</span>",
escape_text(if alt.is_empty() {
"无替代文本"
} else {
alt
})
);
if let Some(media) = model.media.get(url) {
let _ = write!(html, "<img class=\"mq-document-image\" src=\"{}\" alt=\"{}\" width=\"{}\" height=\"{}\" title=\"{}\">",
escape_attr(&ctx.links.media_href(media)), escape_attr(alt),
media.width, media.height, escape_attr(title));
} else {
let _ = write!(html, "<span class=\"mq-raw-omitted\" role=\"note\" title=\"{}\">[图片已阻止自动加载:{}]</span>",
escape_attr(url), escape_text(if alt.is_empty() { "无替代文本" } else { alt }));
}
}
Inline::Math {
span,
@@ -1277,9 +1302,8 @@ fn render_inline(
))
))
.unwrap_or_default(),
escape_text(literal)
render_math(literal, *display)
);
let _ = display;
}
Inline::HtmlInline { .. } => {
html.push_str("<span class=\"mq-raw-omitted\">已忽略原始行内 HTML</span>");
@@ -1362,51 +1386,64 @@ fn percent_encode_path(raw: &str) -> String {
/// Sanitize one Markdown link destination. Returns `None` for schemes the
/// reader must never expose (`javascript:`, `data:`, `file:`, ...) and for
/// console-control-looking payloads.
fn resolve_link(raw: &str, current: &SafeRelativePath, policy: &LinkPolicy) -> Option<String> {
fn resolve_link(
raw: &str,
current: &SafeRelativePath,
model: &PresentationModel,
policy: &LinkPolicy,
) -> Option<String> {
let url = raw.trim();
if url.is_empty() {
if url.is_empty()
|| url.chars().any(char::is_control)
|| url.contains('\\')
|| url.starts_with('/')
{
return None;
}
if url.chars().any(|ch| ch.is_control() || ch == '\u{7f}') {
return None;
let (path_with_query, fragment) = url
.split_once('#')
.map_or((url, None), |(path, fragment)| (path, Some(fragment)));
let path = path_with_query.split('?').next()?;
if let Some((scheme, _)) = path.split_once(':') {
return matches!(
scheme.to_ascii_lowercase().as_str(),
"http" | "https" | "mailto"
)
.then(|| url.to_string());
}
// Explicit scheme: only http/https/mailto are navigable. A single-letter
// prefix is a Windows drive, not a scheme.
if let Some(colon) = url.find(':') {
let scheme = &url[..colon];
if scheme.len() > 1 && scheme.chars().all(|ch| ch.is_ascii_alphabetic()) {
return match scheme.to_ascii_lowercase().as_str() {
"http" | "https" | "mailto" => Some(url.to_string()),
_ => None,
};
let fragment = fragment
.map(super::links::decode)
.unwrap_or_else(|| Some(String::new()))?;
let suffix = if fragment.is_empty() {
String::new()
} else {
format!("#{}", percent_encode_path(&fragment))
};
if path.is_empty() {
return Some(suffix);
}
let target = super::links::relative_url(current, path)?;
if target.as_str().ends_with(".mq.md") {
if !model.navigation.documents.contains(&target) {
return None;
}
}
if url.starts_with("//") {
return None;
}
if url.starts_with('#') {
return Some(url.to_string());
}
if url.starts_with('/') {
return match policy {
LinkPolicy::LocalServer => Some(url.to_string()),
LinkPolicy::StaticRelative { .. } => None,
};
}
let path_part = url.split(['?', '#']).next().unwrap_or(url);
if path_part.ends_with(".mq.md") {
let joined = match current.parent() {
Some(dir) => format!("{dir}/{path_part}"),
None => path_part.to_string(),
};
if let Ok(target) = SafeRelativePath::parse(&joined) {
return Some(policy.document_href(current, &target));
}
return None;
return Some(format!(
"{}{suffix}",
policy.document_href(current, &target)
));
}
Some(url.to_string())
}
fn render_math(literal: &str, display: bool) -> String {
super::math::render(literal, display).unwrap_or_else(|| {
format!(
"<code title=\"公式无法排版\">{}</code>",
escape_text(literal)
)
})
}
fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span: SourceSpan) {
let Some(run) = &model.run else {
return;
+26 -2
View File
@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
/// Half-open byte span `[start, end)` into one module's exact source bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub struct SourceSpan {
pub start: u64,
pub end: u64,
@@ -402,6 +402,8 @@ pub struct DocumentRef {
#[derive(Debug, Clone)]
pub struct Project {
root: PathBuf,
#[cfg(target_os = "linux")]
root_handle: std::sync::Arc<std::fs::File>,
entry: DocumentRef,
}
@@ -419,6 +421,8 @@ impl Project {
if metadata.is_file() {
let root = discover_project_root(&canonical);
let project = Self {
#[cfg(target_os = "linux")]
root_handle: Self::open_root(&root)?,
entry: DocumentRef {
relative: SafeRelativePath("placeholder".to_string()),
absolute: canonical.clone(),
@@ -428,6 +432,8 @@ impl Project {
let relative = project.relative_for(&canonical)?;
Ok(Self {
root: project.root,
#[cfg(target_os = "linux")]
root_handle: project.root_handle,
entry: DocumentRef {
relative,
absolute: canonical,
@@ -436,6 +442,8 @@ impl Project {
} else if metadata.is_dir() {
let project = Self {
root: canonical.clone(),
#[cfg(target_os = "linux")]
root_handle: Self::open_root(&canonical)?,
entry: DocumentRef {
relative: SafeRelativePath("placeholder".to_string()),
absolute: canonical.clone(),
@@ -444,8 +452,8 @@ impl Project {
let documents = project.list_documents()?;
let chosen = choose_entry(&project.root, &documents)?;
Ok(Self {
root: project.root,
entry: chosen,
..project
})
} else {
Err(ViewError::PathForbidden {
@@ -454,6 +462,22 @@ impl Project {
}
}
#[cfg(target_os = "linux")]
fn open_root(path: &Path) -> ViewResult<std::sync::Arc<std::fs::File>> {
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW)
.open(path)
.map(std::sync::Arc::new)
.map_err(|err| ViewError::io("open project root", err))
}
#[cfg(target_os = "linux")]
pub(super) fn root_handle(&self) -> &std::fs::File {
&self.root_handle
}
pub fn root(&self) -> &Path {
&self.root
}
+55 -7
View File
@@ -50,21 +50,29 @@ impl ServerState {
/// bytes are unchanged. This path performs the read-only `check` only.
pub fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
let digest = self.service.project().source_digest(relative)?;
if let Ok(cache) = self.cache.lock() {
if let Some(entry) = cache.get(relative.as_str()) {
if entry.source_digest == digest {
return Ok(entry.model.clone());
}
}
let cached = self.cache.lock().ok().and_then(|cache| {
let entry = cache.get(relative.as_str())?;
(entry.source_digest == digest).then(|| entry.model.clone())
});
if let Some(mut model) = cached {
model.media = crate::reader::media::collect(
self.service.project(),
relative,
&model.document.blocks,
);
model.navigation.documents = self.service.project().list_documents()?;
return Ok(model);
}
let model = self.service.load(relative)?;
if let Ok(mut cache) = self.cache.lock() {
if cache.len() < 64 {
let mut cached = model.clone();
cached.media.clear();
cache.insert(
relative.as_str().to_string(),
CacheEntry {
source_digest: digest,
model: model.clone(),
model: cached,
},
);
}
@@ -102,6 +110,9 @@ pub fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
if let Some(hashed_name) = path.strip_prefix("/assets/") {
return serve_asset(request, hashed_name);
}
if let Some(name) = path.strip_prefix("/media/") {
return serve_media(state, request, name, query);
}
if path == "/" || path == "/index.html" {
return serve_page(state, request, None);
}
@@ -387,6 +398,43 @@ fn cancel_run(state: &ServerState, request: Request, run_id: &str) -> ViewResult
}
}
fn serve_media(state: &ServerState, request: Request, name: &str, query: &str) -> ViewResult<()> {
if let Err(err) = state.security.require_session(&request) {
return respond_error(request, status_for(&err), &err);
}
let Some(path) =
query_param(query, "path").and_then(|path| SafeRelativePath::parse(&path).ok())
else {
return respond_text(
request,
StatusCode(404),
"media not found\n",
CacheKind::NoStore,
);
};
let Some(media) = crate::reader::media::load(state.service.project(), &path)
.filter(|media| media.filename() == name)
else {
return respond_text(
request,
StatusCode(404),
"media not found\n",
CacheKind::NoStore,
);
};
respond_bytes(
request,
StatusCode(200),
media.mime,
media.bytes,
CacheKind::NoStore,
vec![
Header::from_bytes("Content-Security-Policy", "default-src 'none'; sandbox")
.expect("valid media CSP"),
],
)
}
fn serve_asset(request: Request, hashed_name: &str) -> ViewResult<()> {
let bundle = AssetBundle::get();
if hashed_name == bundle.hashed_css_name() {