banners: tell why one is missing, accept more, bigger defaults

Failures are in the log with the host and the reason, never the whole
address: HTTP status, the whole chain of causes (TLS, DNS, timeouts), what
came instead of a picture (an HTML page, AVIF); banner addresses that
cannot be fetched at all once; avatars and icons in the server's files
when they give up (a closed file transfer port shows here).

More is shown: BMP and ICO, SVG after a comment or a DOCTYPE, addresses
with blanks around them; pictures larger than 4096 px are scaled down
instead of refused (only above 512 MiB of pixels). Banners keep being
tried while shown (after 1, 4, 16, 60, 300, 900 s, then every 15 min).

Defaults: connect 20 s, read 60 s, slow start 120 s, 16 downloads at
once, 20 redirects, pictures up to 128 MiB at 8 KiB/s at least, file
transfer negotiation 30 s and a minute plus size, cache.max_mb 1024,
ui.image_cache_mb 256.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
This commit is contained in:
Claude committed 2026-10-05 22:05:12 +00:00
1 parent 259a23a165
commit db94e21e27
9 files changed
+282 -85

No files matched your search

+7 -2
View File
@@ -46,7 +46,7 @@ fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails {
tsclientlib::HostMessageMode::Modalquit => HostMessageMode::ModalQuit,
},
banner_url: server.hostbanner_url.clone(),
banner_gfx_url: server.hostbanner_gfx_url.clone(),
banner_gfx_url: server.hostbanner_gfx_url.trim().to_owned(),
banner_gfx_interval_s: server.hostbanner_gfx_interval.whole_seconds().max(0) as u64,
banner_mode: match server.hostbanner_mode {
tsclientlib::HostBannerMode::NoAdjust => BannerMode::NoAdjust,
@@ -115,7 +115,12 @@ pub(crate) fn presence_from_book(
needed_talk_power: c.needed_talk_power.unwrap_or(0),
is_default: c.is_default.unwrap_or(false),
icon: c.icon.map_or(0, |i| i.0),
banner_gfx_url: c.banner_gfx_url.clone().filter(|u| !u.is_empty()),
banner_gfx_url: c
.banner_gfx_url
.as_deref()
.map(str::trim)
.filter(|u| !u.is_empty())
.map(str::to_owned),
// A number the book keeps as text.
banner_mode: c
.banner_mode
+4 -3
View File
@@ -80,16 +80,17 @@ pub(crate) fn icon_key(id: u32) -> String {
/// The largest picture downloaded into the cache, from the web or from the
/// server's files: animated banners of several megabytes are common. The
/// download goes to disk as it arrives, so this bounds the disk, not memory.
pub(crate) const MAX_PICTURE_BYTES: u64 = 64 << 20;
pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
/// The slowest a picture may arrive on average after its first seconds:
/// a large banner on a slow link still arrives, one trickling in forever
/// does not hold a download slot.
pub(crate) const MIN_PICTURE_RATE: u64 = 32 << 10;
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
/// The cache key of a picture on the web: only `http` and `https`
/// addresses.
/// addresses (blanks around one are not part of it).
pub(crate) fn picture_key(url: &str) -> Option<String> {
let url = url.trim();
let (scheme, rest) = url.split_once("://")?;
let web = scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https");
(web && !rest.is_empty()).then(|| format!("pictures/{:x}", md5::compute(url)))
+76 -16
View File
@@ -15,7 +15,7 @@ use std::time::Duration;
use tokio::time::Instant;
use tokio::sync::{broadcast, mpsc, watch};
use tracing::{debug, warn};
use tracing::{debug, info, warn};
use tsclientlib::ClientId;
use voelin_audio::AudioSettings;
use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature};
@@ -167,13 +167,54 @@ impl Drop for ImageDownload {
}
}
/// At most three retries (after 1, 4 and 16 seconds) per image version.
/// Keeping exhausted entries prevents presence traffic from causing a retry storm.
/// Retries per image version ([`retry_delay`]). Keeping exhausted entries
/// prevents presence traffic from causing a retry storm.
struct ImageRetry {
failures: u8,
due: Option<Instant>,
}
/// When to try an image again after its `failures`-th failed download:
/// a banner after 1, 4, 16, 60, 300 and 900 seconds, then every 15 minutes
/// while it is shown (its host may be away for a while); avatars and icons
/// after 1, 4 and 16 seconds, then no more.
fn retry_delay(request: &ImageRequest, failures: u8) -> Option<Duration> {
const BANNERS: [u64; 6] = [1, 4, 16, 60, 300, 900];
let failures = usize::from(failures.max(1));
match request {
ImageRequest::Picture(_) => Some(Duration::from_secs(BANNERS[(failures - 1).min(5)])),
_ if failures <= 3 => Some(Duration::from_secs(1 << (2 * (failures - 1)))),
_ => None,
}
}
/// A failed image download in the log, with what it was and why (the
/// host, never the whole address): banners at once, avatars and icons in
/// the server's files when they give up (their files unreachable, a
/// closed file transfer port).
fn log_image_failure(
request: &ImageRequest,
failures: u8,
retry_in: Option<Duration>,
error: &str,
) {
let retry_in_s = retry_in.map(|d| d.as_secs());
match request {
ImageRequest::Picture(url) if failures <= 6 => {
let host = web::host_of(url);
info!(%host, failures, ?retry_in_s, %error, "banner not downloaded");
}
ImageRequest::MytsAvatar { url, .. } if retry_in.is_none() => {
let host = web::host_of(url);
info!(%host, %error, "myTeamSpeak avatar not downloaded");
}
ImageRequest::Avatar { .. } | ImageRequest::Icon(_) if retry_in.is_none() => {
info!(?request, %error, "server file not downloaded (avatar or icon)");
}
_ => debug!(?request, failures, ?retry_in_s, %error, "image download failed"),
}
}
/// Whether an explicitly requested image belongs to the voice connection
/// (downloaded over it, so dropped with it); a myTeamSpeak avatar is on the
/// web.
@@ -250,6 +291,9 @@ struct Session {
icons: HashSet<u32>,
/// Pictures on the web (banners) reported or being fetched, by address.
pictures: HashSet<String>,
/// Banner addresses that cannot be fetched at all (another scheme),
/// logged once.
unfetchable: HashSet<String>,
image_epoch: u64,
images_enabled: bool,
image_retries: HashMap<ImageRequest, ImageRetry>,
@@ -289,6 +333,7 @@ impl Session {
server_avatars_failed: HashSet::new(),
icons: HashSet::new(),
pictures: HashSet::new(),
unfetchable: HashSet::new(),
image_epoch: 0,
images_enabled: settings.current().get(&CACHE_FETCH_IMAGES),
image_retries: HashMap::new(),
@@ -866,6 +911,7 @@ impl Session {
self.server_avatars_failed.clear();
self.icons.clear();
self.pictures.clear();
self.unfetchable.clear();
self.contact_audio.clear();
self.stream_friends.clear();
self.details = None;
@@ -1030,22 +1076,18 @@ impl Session {
});
}
Err(error) => {
debug!(?request, %error, "image download failed");
let avatar_of = match &request {
ImageRequest::Avatar { uid, .. } => Some(uid.clone()),
_ => None,
};
let retry = self
.image_retries
.entry(request)
.entry(request.clone())
.or_insert(ImageRetry { failures: 0, due: None });
retry.failures = retry.failures.saturating_add(1);
retry.due = match retry.failures {
1..=3 => {
Some(Instant::now() + Duration::from_secs(1 << (2 * (retry.failures - 1))))
}
_ => None,
};
let delay = retry_delay(&request, retry.failures);
retry.due = delay.map(|delay| Instant::now() + delay);
log_image_failure(&request, retry.failures, delay, &error);
// The server's avatar gave up (its files unreachable): the
// myTeamSpeak one, if the client has one.
if let (None, Some(uid)) = (retry.due, avatar_of)
@@ -1148,11 +1190,18 @@ impl Session {
if !enabled {
return;
}
let urls: HashSet<_> = std::iter::once(&p.server.banner_gfx_url)
let all = std::iter::once(&p.server.banner_gfx_url)
.chain(p.channels.values().filter_map(|c| c.banner_gfx_url.as_ref()))
.filter(|u| self.can_fetch_picture(u))
.cloned()
.collect();
.filter(|u| !u.is_empty());
let mut urls = HashSet::new();
for url in all {
if self.can_fetch_picture(url) {
urls.insert(url.clone());
} else if files::server_image(url).is_none() && self.unfetchable.insert(url.clone()) {
let scheme = url.split(':').next().unwrap_or_default();
info!(%scheme, "banner not downloaded: only http, https and ts3image addresses");
}
}
self.pictures.retain(|url| urls.contains(url));
for url in &urls {
if self.pictures.insert(url.clone()) {
@@ -2249,6 +2298,16 @@ mod banner_tests {
let _ = std::fs::remove_dir_all(cache.dir());
}
#[test]
fn banners_keep_trying_avatars_and_icons_give_up() {
let banner = ImageRequest::Picture("https://example.com/b.png".into());
let delays: Vec<_> = (1..=8).map(|f| retry_delay(&banner, f).unwrap().as_secs()).collect();
assert_eq!(delays, [1, 4, 16, 60, 300, 900, 900, 900]);
let icon = ImageRequest::Icon(1234);
let delays: Vec<_> = (1..=4).map(|f| retry_delay(&icon, f).map(|d| d.as_secs())).collect();
assert_eq!(delays, [Some(1), Some(4), Some(16), None]);
}
#[tokio::test]
async fn retries_are_bounded_and_obey_policy_presence_and_epoch() {
let (mut session, mut events) = session("retry-guards");
@@ -2264,7 +2323,8 @@ mod banner_tests {
);
let retry = &session.image_retries[&request];
assert_eq!(retry.failures, failure);
assert_eq!(retry.due.is_some(), failure <= 3);
// A banner is tried again while it is shown.
assert!(retry.due.is_some());
}
assert!(events.try_recv().is_err());
// Disabling fetch invalidates pending retries and completions.
+2 -2
View File
@@ -1121,8 +1121,8 @@ pub static CHAT_RETENTION_DAYS: Key<u32> = Key::new(
pub static CACHE_MAX_MB: Key<u64> = Key::new(
"cache.max_mb",
Kind::UInt { min: 0 },
"Size of the avatar and icon cache in MiB (0: no limit).",
|| 256,
"Size of the picture cache (avatars, icons, banners) in MiB (0: no limit).",
|| 1024,
);
/// Download the avatars, icons and banners of servers we are on.
+14 -10
View File
@@ -295,17 +295,21 @@ impl Job {
}
}
/// How long a picture of `size` bytes may take to arrive: half a minute,
/// plus its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on
/// slow links while a stalled transfer still ends.
/// How long a picture of `size` bytes may take to arrive: a minute, plus
/// its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on slow
/// links while a stalled transfer still ends.
fn image_download_time(size: u64) -> Duration {
Duration::from_secs(30 + size / cache::MIN_PICTURE_RATE)
Duration::from_secs(60 + size / cache::MIN_PICTURE_RATE)
}
/// How long the server may take to start an image transfer (a busy server
/// answers the requests of a large channel tree in turn).
const IMAGE_NEGOTIATION: Duration = Duration::from_secs(30);
/// Bound background image handshakes without imposing a deadline on user transfers.
fn expire_image_jobs(jobs: &mut HashMap<FiletransferHandle, Job>, now: Instant) {
jobs.retain(|_, job| {
if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= Duration::from_secs(15)) {
if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= IMAGE_NEGOTIATION) {
job.report()(TransferState::Failed("image transfer negotiation timed out".into()));
false
} else {
@@ -1136,10 +1140,10 @@ mod image_download_tests {
},
);
}
expire_image_jobs(&mut jobs, started + Duration::from_secs(14));
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION - Duration::from_secs(1));
assert_eq!(jobs.len(), 2);
assert!(reports.lock().unwrap().is_empty());
expire_image_jobs(&mut jobs, started + Duration::from_secs(15));
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION);
assert_eq!(jobs.len(), 1);
assert!(jobs.contains_key(&FiletransferHandle(2)));
assert!(
@@ -1151,10 +1155,10 @@ mod image_download_tests {
#[test]
fn large_pictures_get_time_to_arrive() {
assert_eq!(image_download_time(0), Duration::from_secs(30));
assert_eq!(image_download_time(100 << 10), Duration::from_secs(33));
assert_eq!(image_download_time(0), Duration::from_secs(60));
assert_eq!(image_download_time(100 << 10), Duration::from_secs(72));
// The largest picture, at the slowest rate allowed.
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(30 + 2048));
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(60 + 16384));
}
}
+109 -18
View File
@@ -25,18 +25,22 @@ use tokio::io::AsyncWriteExt;
use crate::cache::{self, Cache, Fetch, Waiter};
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const READ_TIMEOUT: Duration = Duration::from_secs(20);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
const READ_TIMEOUT: Duration = Duration::from_secs(60);
/// How long a download may start slowly before its rate counts.
const GRACE: Duration = Duration::from_secs(30);
/// The first bytes, enough to tell a picture from an error page.
const SNIFF: usize = 1024;
const GRACE: Duration = Duration::from_secs(120);
/// The first bytes, enough to tell a picture from an error page (SVG with
/// a comment or a DOCTYPE before it too).
const SNIFF: usize = 4096;
/// The pictures the UI decodes, so a host choosing between formats
/// (`Accept`) does not answer with one it cannot show (AVIF, JPEG XL).
const ACCEPT: &str = "image/png,image/jpeg,image/gif,image/webp,image/svg+xml;q=0.9,*/*;q=0.1";
const ACCEPT: &str = "image/png,image/jpeg,image/gif,image/webp,image/svg+xml,image/bmp,\
image/x-icon;q=0.9,*/*;q=0.1";
/// Fetch independent URLs in parallel without letting a large channel tree
/// open unbounded connections or buffer unbounded image data.
static DOWNLOADS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(8);
static DOWNLOADS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(16);
/// Redirects followed, as many as a browser does.
const REDIRECTS: usize = 20;
/// The host banner is reloaded at most this often, whatever the server
/// asks (TeamSpeak 3 and 6 servers refuse intervals below a minute).
pub(crate) const MIN_RELOAD: Duration = Duration::from_secs(60);
@@ -45,6 +49,7 @@ static CLIENT: LazyLock<Result<reqwest::Client, String>> = LazyLock::new(|| {
reqwest::Client::builder()
.connect_timeout(CONNECT_TIMEOUT)
.read_timeout(READ_TIMEOUT)
.redirect(reqwest::redirect::Policy::limited(REDIRECTS))
.user_agent(concat!("Voelin/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|e| e.to_string())
@@ -79,7 +84,7 @@ fn fetch_within(
let url = url.to_owned();
tokio::spawn(async move {
let _permit = DOWNLOADS.acquire().await.expect("download semaphore stays open");
let result = download(&url, &temp, limits).await;
let result = download(url.trim(), &temp, limits).await;
cache.finish(&key, &temp, result, max_cache_bytes);
});
}
@@ -108,7 +113,7 @@ async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> {
.send()
.await
.and_then(reqwest::Response::error_for_status)
.map_err(|e| e.to_string())?;
.map_err(describe)?;
if response.content_length().is_some_and(|n| n > limits.max_bytes) {
return Err(too_big());
}
@@ -119,7 +124,7 @@ async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> {
let started = tokio::time::Instant::now();
let mut head = Vec::with_capacity(SNIFF);
let mut received = 0u64;
while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
while let Some(chunk) = response.chunk().await.map_err(describe)? {
received += chunk.len() as u64;
if received > limits.max_bytes {
return Err(too_big());
@@ -128,7 +133,7 @@ async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> {
head.extend_from_slice(&chunk[..chunk.len().min(SNIFF - head.len())]);
// An error page is refused without waiting for all of it.
if head.len() == SNIFF && !is_picture(&head) {
return Err("not a picture".into());
return Err(not_a_picture(&head));
}
}
let elapsed = started.elapsed();
@@ -141,20 +146,92 @@ async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> {
file.flush().await.map_err(|e| e.to_string())?;
drop(file);
if !is_picture(&head) {
return Err("not a picture".into());
return Err(not_a_picture(&head));
}
Ok(())
}
/// What went wrong, for the log: the status, or the whole chain of causes
/// (a TLS, DNS or timeout reason); never the address, whose query may be
/// a signed link's secret.
fn describe(error: reqwest::Error) -> String {
if let Some(status) = error.status() {
return format!("HTTP {status}");
}
let error = error.without_url();
let mut text = if error.is_timeout() {
"timed out".to_owned()
} else if error.is_connect() {
"could not connect".to_owned()
} else if error.is_redirect() {
"too many redirects".to_owned()
} else {
error.to_string()
};
let mut source = std::error::Error::source(&error);
while let Some(cause) = source {
text.push_str(": ");
text.push_str(&cause.to_string());
source = cause.source();
}
text
}
/// What arrived instead of a picture, for the log.
fn not_a_picture(head: &[u8]) -> String {
let start = head.trim_ascii_start();
let lower =
start.get(..15.min(start.len())).map(<[u8]>::to_ascii_lowercase).unwrap_or_default();
let what = if lower.starts_with(b"<!doctype html") || lower.starts_with(b"<html") {
"an HTML page"
} else if head.len() >= 12 && &head[4..8] == b"ftyp" {
"AVIF or HEIF, which cannot be shown"
} else if start.starts_with(b"{") {
"JSON"
} else {
"something else"
};
format!("not a picture ({what})")
}
/// The host of `url`, for the log; the scheme for one without (a server
/// file, `ts3image://`).
pub(crate) fn host_of(url: &str) -> String {
match reqwest::Url::parse(url.trim()) {
Ok(u) if matches!(u.scheme(), "http" | "https") => u.host_str().unwrap_or("?").to_owned(),
Ok(u) => u.scheme().to_owned(),
Err(_) => "?".to_owned(),
}
}
/// Whether `data` is a picture the UI decodes, told by its content as the
/// UI tells it (SVG by its start, without leading blanks).
/// UI tells it (SVG by its start, without leading blanks, or after a
/// comment or a DOCTYPE).
fn is_picture(data: &[u8]) -> bool {
const STARTS: [&[u8]; 4] = [b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"GIF87a", b"GIF89a"];
let xml = data.strip_prefix(b"\xef\xbb\xbf").unwrap_or(data).trim_ascii_start();
const STARTS: [&[u8]; 7] = [
b"\x89PNG\r\n\x1a\n",
b"\xff\xd8\xff",
b"GIF87a",
b"GIF89a",
b"BM",
// ICO and CUR.
b"\0\0\x01\0",
b"\0\0\x02\0",
];
STARTS.iter().any(|s| data.starts_with(s))
|| xml.starts_with(b"<?xml")
|| xml.starts_with(b"<svg")
|| (data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP")
|| is_svg(data)
}
/// Whether `data` starts an SVG document: after a BOM and blanks, with
/// `<svg`, `<?xml`, or a comment or a DOCTYPE with `<svg` after it.
pub(crate) fn is_svg(data: &[u8]) -> bool {
let xml = data.strip_prefix(b"\xef\xbb\xbf").unwrap_or(data).trim_ascii_start();
let prolog = xml.starts_with(b"<!--")
|| xml.get(..9).is_some_and(|s| s.eq_ignore_ascii_case(b"<!doctype"));
xml.starts_with(b"<?xml")
|| xml.starts_with(b"<svg")
|| (prolog && xml.windows(4).any(|w| w == b"<svg"))
}
#[cfg(test)]
@@ -286,7 +363,7 @@ mod tests {
// A failed download is reported and leaves nothing behind.
fetch(cache.clone(), &format!("{base}/page"), false, 0, waiter(&tx));
let failed = tokio::task::spawn_blocking(move || rx.recv().unwrap()).await.unwrap();
assert_eq!(failed, Err("not a picture".into()));
assert_eq!(failed, Err("not a picture (an HTML page)".into()));
assert_eq!(cache.size(), PNG.len() as u64);
std::fs::remove_dir_all(dir).unwrap();
}
@@ -393,5 +470,19 @@ mod tests {
assert!(!is_picture(b"<!DOCTYPE html>"));
assert!(!is_picture(b"RIFF\x24\0\0\0WAVEfmt "));
assert!(!is_picture(b""));
// What browsers show too: BMP, ICO, SVG after a comment or DOCTYPE.
assert!(is_picture(b"BM\x36\0\0\0"));
assert!(is_picture(b"\0\0\x01\0\x01\0"));
assert!(is_picture(b"<!-- made with a tool -->\n<svg/>"));
assert!(is_picture(b"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"><svg/>"));
assert!(!is_picture(b"<!-- a page --><html></html>"));
// What came instead is told.
assert_eq!(not_a_picture(b"<!DOCTYPE html><html>"), "not a picture (an HTML page)");
assert_eq!(
not_a_picture(b"\0\0\0\x1cftypavif"),
"not a picture (AVIF or HEIF, which cannot be shown)"
);
assert_eq!(host_of(" https://cdn.example.test/b.png?sig=x "), "cdn.example.test");
assert_eq!(host_of("ts3image://banner.png?channel=1"), "ts3image");
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ dirs = "6"
# Slint decodes pictures with `image`, which it builds with PNG and JPEG only;
# avatars, icons and banners on TeamSpeak servers are GIF and WebP too (the
# decoders are in the tree already, for SVG pictures).
image = { version = "0.25", default-features = false, features = ["gif", "webp"] }
image = { version = "0.25", default-features = false, features = ["gif", "webp", "bmp", "ico"] }
# Twemoji archive blocks (raw deflate); already used by png.
miniz_oxide = "0.8"
png = "0.18"
+67 -31
View File
@@ -93,7 +93,7 @@ fn svg_cost(svg_len: usize) -> usize {
}
thread_local! {
static CACHE: RefCell<Lru<Image>> = RefCell::new(Lru::new(64 << 20));
static CACHE: RefCell<Lru<Image>> = RefCell::new(Lru::new(256 << 20));
}
/// Set the budget in megabytes.
@@ -138,35 +138,59 @@ pub fn forget(path: &std::path::Path) {
CACHE.with(|c| c.borrow_mut().remove(&path.to_string_lossy()));
}
/// The largest side a raster picture keeps: larger ones (a banner made for
/// print) are scaled down when decoded, as nothing shows them larger.
const MAX_SIDE: u32 = 4096;
/// A picture with more pixels than this (RGBA bytes) is not decoded at all.
const MAX_DECODED_BYTES: u64 = 512 << 20;
/// Compressed pictures can be small on disk but huge when decoded. Check
/// raster dimensions before Slint allocates pixels on the UI thread. SVGs
/// keep Slint's native vector loader and are rasterized at the displayed size.
fn decode(bytes: &[u8]) -> Option<(Image, usize)> {
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
let cost = if reader.format().is_some() {
let (width, height) = reader.into_dimensions().ok()?;
// At most the default decoded-image cache (64 MiB of RGBA).
if width == 0
|| height == 0
|| width > 16_384
|| height > 16_384
|| u64::from(width) * u64::from(height) * 4 > 64 << 20
{
tracing::debug!(width, height, "image exceeds the decoded raster size limit");
return None;
}
width as usize * height as usize * 4
} else {
if reader.format().is_none() {
let start = bytes.trim_ascii_start();
if !start.starts_with(b"<svg") && !start.starts_with(b"<?xml") {
if !is_svg(start) {
return None;
}
// Intrinsic SVG dimensions describe coordinates, not an allocated
// pixel buffer. Use the same vector cost as the emoji cache.
return Image::load_from_svg_data(start).ok().map(|image| (image, svg_cost(bytes.len())));
};
Image::load_from_data(bytes, None).ok().map(|image| (image, cost))
}
let (width, height) = reader.into_dimensions().ok()?;
if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES {
tracing::warn!(width, height, "picture not shown: too large to decode");
return None;
}
if width <= MAX_SIDE && height <= MAX_SIDE {
let cost = width as usize * height as usize * 4;
return Image::load_from_data(bytes, None).ok().map(|image| (image, cost));
}
// Scaled down (the first frame of an animation).
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_DECODED_BYTES + (64 << 20));
reader.limits(limits);
let small = reader.decode().ok()?.thumbnail(MAX_SIDE, MAX_SIDE).to_rgba8();
let (width, height) = small.dimensions();
let pixels = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::clone_from_slice(
small.as_raw(),
width,
height,
);
Some((Image::from_rgba8(pixels), width as usize * height as usize * 4))
}
/// Whether `start` (without a BOM and leading blanks) is an SVG document:
/// `<svg`, `<?xml`, or a comment or a DOCTYPE with `<svg` after it.
fn is_svg(start: &[u8]) -> bool {
let prolog = start.starts_with(b"<!--")
|| start.get(..9).is_some_and(|s| s.eq_ignore_ascii_case(b"<!doctype"));
start.starts_with(b"<svg")
|| start.starts_with(b"<?xml")
|| (prolog && start.windows(4).any(|w| w == b"<svg"))
}
/// A picture from encoded bytes (PNG, JPEG, GIF, WebP), decoded once and
@@ -264,7 +288,25 @@ mod tests {
}
#[test]
fn oversized_rasters_are_refused_before_pixels_are_read() {
fn svg_after_a_comment_or_doctype_decodes() {
let svg = b"<!-- tool --><!DOCTYPE svg><svg xmlns='http://www.w3.org/2000/svg' width='8' height='4'><rect width='8' height='4'/></svg>";
assert_eq!(picture("test:svg-prolog", svg).size().width, 8);
assert!(decode(b"<!-- a page --><html></html>").is_none());
}
#[test]
fn rasters_beyond_the_pixel_cap_are_refused_before_pixels_are_read() {
// Only the header: its size is all that is read.
let mut bytes = Vec::new();
let mut encoder = png::Encoder::new(&mut bytes, 20_000, 20_000);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
std::mem::forget(encoder.write_header().unwrap());
assert!(decode(&bytes).is_none());
}
#[test]
fn large_rasters_are_scaled_down() {
use std::io::Write;
for (width, height) in [(6000, 6000), (16_385, 1), (1, 16_385)] {
let mut bytes = Vec::new();
@@ -279,19 +321,13 @@ mod tests {
}
stream.finish().unwrap();
writer.finish().unwrap();
// A valid solid picture fits the download cap but not the
// decoded budget. Generate it a row at a time, without ever
// allocating the large pixel buffer this test guards against.
// Generated a row at a time.
assert!(bytes.len() < 4 << 20);
assert_eq!(
image::ImageReader::new(Cursor::new(&bytes))
.with_guessed_format()
.unwrap()
.into_dimensions()
.unwrap(),
(width, height)
);
assert!(decode(&bytes).is_none());
let (image, cost) = decode(&bytes).unwrap();
let size = image.size();
assert!(size.width <= MAX_SIDE && size.height <= MAX_SIDE, "{size:?}");
assert_eq!(size.width.max(size.height), MAX_SIDE);
assert_eq!(cost, size.width as usize * size.height as usize * 4);
}
}
+2 -2
View File
@@ -87,8 +87,8 @@ pub static UI_NARROW_BREAKPOINT: Key<u32> = Key::new(
pub static UI_IMAGE_CACHE_MB: Key<u32> = Key::new(
"ui.image_cache_mb",
Kind::UInt { min: 0 },
"Memory in MB for decoded images (avatars, icons, emoji); 0 keeps none.",
|| 64,
"Memory in MB for decoded images (avatars, icons, banners, emoji); 0 keeps none.",
|| 256,
);
/// `ui.members_width`: how wide the members and streams panel is, in