Banners: download those in the server's files, larger and slower ones

Not every banner arrived:

- Banners kept in the server's own files are linked as ts3image://
  (TeamSpeak 5 and 6: ts3image://<host>?port=…&channel=…&path=…&filename=…,
  the file browser's ts3file:// link with its scheme changed; TeamSpeak 3:
  ts3image://<name>?channel=…&path=…). Only http(s) was fetched, so these
  never were. They now come through the voice connection's file transfer
  (files::server_image), cached under the server and the address.
- A web download had 16 MiB at most and 30 seconds in all, while up to
  eight run at once: a large animated banner, or several on a slow link,
  failed and failed again on every retry. Pictures may now be 64 MiB and
  go to disk as they arrive instead of into memory; a download fails when
  nothing arrives for 20 s or when, after its first 30 s, it averages less
  than 32 KiB/s. Accept names the formats the UI decodes.
- Pictures over file transfer had 30 seconds too; now 30 s plus their
  size at 32 KiB/s, and at most 64 MiB.

The voice protocol's MAX_DECOMPRESSED_SIZE goes back to 2 MiB: it bounds
compressed commands (the channel list), not pictures, and QuickLZ reserves
the size a packet declares, so 1 GiB let any server make the client
allocate a gigabyte with one small packet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEpqsPES27Eacue91u3d2Q
This commit is contained in:
Claude committed 2026-10-04 16:37:02 +00:00
1 parent 3f177a77aa
commit 86c30b6f8f
8 files changed
+333 -58

No files matched your search

+1 -1
View File
@@ -60,7 +60,7 @@ const MAX_QUEUE_LEN: u16 = 200;
/// On large servers with more than 2000 channels, the notifychannelsubscribed packet can be
/// 50 kB large (uncompressed). A maximum size to 2 MiB should allow for even larger servers.
const MAX_DECOMPRESSED_SIZE: u32 = 1024 * 1024 * 1024;
const MAX_DECOMPRESSED_SIZE: u32 = 2 * 1024 * 1024;
const FAKE_KEY: [u8; 16] = *b"c:\\windows\\syste";
const FAKE_NONCE: [u8; 16] = *b"m\\firewall32.cpl";
+16
View File
@@ -77,6 +77,16 @@ pub(crate) fn icon_key(id: u32) -> String {
format!("icons/{id}")
}
/// 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;
/// 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;
/// The cache key of a picture on the web: only `http` and `https`
/// addresses.
pub(crate) fn picture_key(url: &str) -> Option<String> {
@@ -85,6 +95,12 @@ pub(crate) fn picture_key(url: &str) -> Option<String> {
(web && !rest.is_empty()).then(|| format!("pictures/{:x}", md5::compute(url)))
}
/// The cache key of a picture in a server's files (`ts3image://`): the
/// same address names another file on another server.
pub(crate) fn server_picture_key(server: &str, url: &str) -> String {
format!("pictures/{:x}", md5::compute(format!("{server}\n{url}")))
}
impl Cache {
/// A cache in `dir` (created when the first file arrives).
pub fn new(dir: impl Into<PathBuf>) -> Self {
+89
View File
@@ -364,6 +364,59 @@ pub(crate) fn normalize_dir(path: &str) -> String {
}
}
/// A picture in the voice server's files, as banners link one: its
/// channel and path. TeamSpeak 5 and 6 write
/// `ts3image://<host>?port=<port>&channel=<cid>&path=<dir>&filename=<name>`
/// (the file browser's `ts3file://` link with its scheme changed, which is
/// taken as well); TeamSpeak 3's BBCode `ts3image://<name>?channel=<cid>&path=<dir>`.
/// The host is not checked: the file is asked of the server we are on.
pub(crate) fn server_image(url: &str) -> Option<(u64, String)> {
let (scheme, rest) = url.trim().split_once("://")?;
if !scheme.eq_ignore_ascii_case("ts3image") && !scheme.eq_ignore_ascii_case("ts3file") {
return None;
}
let rest = rest.split('#').next().unwrap_or_default();
let (authority, query) = rest.split_once('?').unwrap_or((rest, ""));
let (mut channel, mut dir, mut name, mut port) = (None, None, None, false);
for pair in query.split('&') {
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
match key {
"channel" => channel = value.parse::<u64>().ok(),
"path" => dir = Some(percent_decode(value)?),
"filename" => name = Some(percent_decode(value)?),
"port" => port = true,
_ => {}
}
}
let dir = normalize_dir(dir.as_deref().unwrap_or("/"));
let path = match name {
Some(name) => join_path(&dir, &name),
// TeamSpeak 3: the file's name where the host would be.
None if !port => join_path(&dir, &percent_decode(authority.trim_end_matches('/'))?),
// Only a path: the file itself.
None => dir,
};
(!path.ends_with('/')).then_some((channel?, path))
}
/// `%XX` escapes decoded (a `+` stays one: the clients escape spaces).
fn percent_decode(text: &str) -> Option<String> {
let mut out = Vec::with_capacity(text.len());
let mut bytes = text.bytes();
while let Some(b) = bytes.next() {
if b == b'%' {
let hex = [bytes.next()?, bytes.next()?];
if !hex.iter().all(u8::is_ascii_hexdigit) {
return None;
}
out.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?);
} else {
out.push(b);
}
}
String::from_utf8(out).ok()
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
@@ -389,6 +442,42 @@ mod tests {
assert_eq!(normalize_dir("docs"), "/docs");
}
#[test]
fn server_images() {
// TeamSpeak 5 and 6, as the file browser links a file.
assert_eq!(
server_image(
"ts3image://ts.example.com?port=9987&channel=5&path=%2Fbanners&filename=raid%20night.gif&isDir=0&size=12345"
),
Some((5, "/banners/raid night.gif".into()))
);
assert_eq!(
server_image("TS3FILE://1.2.3.4?port=9987&channel=12&path=/&filename=a+b.png"),
Some((12, "/a+b.png".into()))
);
assert_eq!(
server_image("ts3image://h?port=1&channel=3&path=%2Fdir%2Fx.png"),
Some((3, "/dir/x.png".into()))
);
// TeamSpeak 3's BBCode: the name where the host would be.
assert_eq!(
server_image("ts3image://banner%201.png?channel=1&path=%2F"),
Some((1, "/banner 1.png".into()))
);
assert_eq!(server_image("ts3image://b.png?channel=7"), Some((7, "/b.png".into())));
for refused in [
"https://example.com/b.png",
"ts3image://h?port=1&path=%2F&filename=b.png",
"ts3image://h?port=1&channel=x&filename=b.png",
"ts3image://h?port=1&channel=1&path=%2F",
"ts3image://h?port=1&channel=1&filename=%zz.png",
"ts3image://h?port=1&channel=1&filename=%C3",
"ts3image://",
] {
assert_eq!(server_image(refused), None, "{refused}");
}
}
fn temp(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-files-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
+70 -11
View File
@@ -838,12 +838,12 @@ impl Session {
let Some(key) = cache::avatar_key(hash) else { return };
let waiter = self
.image_waiter(ImageRequest::Avatar { uid: uid.into(), hash: hash.into() }, requested);
self.fetch_image(key, files::avatar_path(uid), waiter);
self.fetch_image(key, files::avatar_path(uid).map(|path| (0, path)), false, waiter);
}
fn fetch_icon(&self, icon: u32) {
let waiter = self.image_waiter(ImageRequest::Icon(icon), false);
self.fetch_image(cache::icon_key(icon), Some(files::icon_path(icon)), waiter);
self.fetch_image(cache::icon_key(icon), Some((0, files::icon_path(icon))), false, waiter);
}
fn wants_image(&self, request: &ImageRequest) -> bool {
@@ -959,12 +959,19 @@ impl Session {
}
}
/// Whether the picture at `url` can be fetched now: on the web, or in
/// the server's files (`ts3image://`) while connected with voice.
fn can_fetch_picture(&self, url: &str) -> bool {
cache::picture_key(url).is_some()
|| (self.voice_presence.is_some() && files::server_image(url).is_some())
}
/// Fetch the banners of the presence shown (any source) that are new,
/// and have the host banner reloaded as often as the server asks.
fn fetch_pictures(&mut self, p: &Presence) {
let enabled = self.settings.current().get(&CACHE_FETCH_IMAGES);
let reload = Some((&p.server.banner_gfx_url, p.server.banner_gfx_interval_s))
.filter(|(url, every)| enabled && cache::picture_key(url).is_some() && *every > 0);
.filter(|(url, every)| enabled && self.can_fetch_picture(url) && *every > 0);
if self.banner_reload.as_ref().map(|(url, every, _)| (url, *every)) != reload {
if let Some((.., timer)) = self.banner_reload.take() {
timer.abort();
@@ -993,7 +1000,7 @@ impl Session {
}
let urls: HashSet<_> = std::iter::once(&p.server.banner_gfx_url)
.chain(p.channels.values().filter_map(|c| c.banner_gfx_url.as_ref()))
.filter(|u| cache::picture_key(u).is_some())
.filter(|u| self.can_fetch_picture(u))
.cloned()
.collect();
self.pictures.retain(|url| urls.contains(url));
@@ -1004,18 +1011,26 @@ impl Session {
}
}
/// Get the picture at `url` into the cache (again with `fresh`).
/// Get the picture at `url` into the cache (again with `fresh`): from
/// the web, or from the server's files through the voice connection.
fn fetch_picture(&self, url: &str, fresh: bool) {
let waiter = self.image_waiter(ImageRequest::Picture(url.into()), false);
web::fetch(self.cache.current(), url, fresh, max_cache_bytes(&self.settings), waiter);
if let Some(file) = files::server_image(url) {
let server = self.state.server_uid.as_deref().unwrap_or(self.voice_address.as_str());
let key = cache::server_picture_key(server, url);
self.fetch_image(key, Some(file), fresh, waiter);
} else {
web::fetch(self.cache.current(), url, fresh, max_cache_bytes(&self.settings), waiter);
}
}
/// Get `key` from the cache, downloading `path` of channel 0 once.
fn fetch_image(&self, key: String, path: Option<String>, waiter: Waiter) {
/// Get `key` from the cache, downloading `file` (channel and path) once
/// (again with `fresh`).
fn fetch_image(&self, key: String, file: Option<(u64, String)>, fresh: bool, waiter: Waiter) {
let cache = self.cache.current();
let Fetch::Download(temp) = cache.fetch(&key, false, waiter) else { return };
let Fetch::Download(temp) = cache.fetch(&key, fresh, waiter) else { return };
let settings = self.settings.clone();
let (Some(path), Some((_, voice))) = (path, &self.voice) else {
let (Some((channel, path)), Some((_, voice))) = (file, &self.voice) else {
cache.finish(&key, &temp, Err(NO_VOICE.into()), max_cache_bytes(&settings));
return;
};
@@ -1032,7 +1047,7 @@ impl Session {
_ => {}
});
let sink = Sink::File { part: temp.clone(), dest: temp, append: false };
let file = Remote { channel: 0, password: None, path };
let file = Remote { channel, password: None, path };
let failed = report.clone();
if voice.send(VoiceCmd::Download { transfer: None, file, sink, report }).is_err() {
failed(TransferState::Failed(NO_VOICE.into()));
@@ -1982,6 +1997,50 @@ mod banner_tests {
std::fs::remove_dir_all(session.cache.current().dir()).unwrap();
}
/// A banner in the server's files (`ts3image://`) comes through the
/// voice connection's file transfer, from its channel and path.
#[tokio::test]
async fn banners_in_the_server_files_come_through_voice() {
let (mut session, mut events) = session("server-files");
let url = "ts3image://ts.example.test?port=9987&channel=7&path=%2Fbanners&filename=raid%20night.png";
let mut presence = Presence::default();
let channel = voelin_model::ChannelInfo {
id: 7,
banner_gfx_url: Some(url.into()),
..Default::default()
};
presence.channels.insert(7, channel);
// Observed without voice: no file transfer to ask yet.
session.fetch_pictures(&presence);
assert!(session.pictures.is_empty());
let (tx, mut commands) = mpsc::unbounded_channel();
session.voice = Some((1, tx));
session.voice_presence = Some(presence.clone());
session.state.server_uid = Some("server-a".into());
session.fetch_pictures(&presence);
assert!(session.pictures.contains(url));
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
commands.try_recv().unwrap()
else {
panic!("expected a file download");
};
assert_eq!((file.channel, file.path.as_str()), (7, "/banners/raid night.png"));
std::fs::create_dir_all(part.parent().unwrap()).unwrap();
std::fs::write(&part, b"banner").unwrap();
report(TransferState::Done { size: 6, path: Some(part), data: None });
let completion = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
session.source_event(completion);
let Ok(Event::PictureReady { url: ready, path, .. }) = events.try_recv() else {
panic!("expected the banner");
};
assert_eq!(ready, url);
// Named by the server too: the same address elsewhere is another file.
let key = cache::server_picture_key("server-a", url);
assert_eq!(path, session.cache.current().dir().join(key));
assert_eq!(std::fs::read(path).unwrap(), b"banner");
std::fs::remove_dir_all(session.cache.current().dir()).unwrap();
}
#[tokio::test]
async fn retries_are_bounded_and_obey_policy_presence_and_epoch() {
let (mut session, mut events) = session("retry-guards");
+2 -2
View File
@@ -1125,11 +1125,11 @@ pub static CACHE_MAX_MB: Key<u64> = Key::new(
|| 256,
);
/// Download the avatars, icons and web banners of servers we are on.
/// Download the avatars, icons and banners of servers we are on.
pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
"cache.fetch_images",
Kind::Bool,
"Download avatars, icons and web banners of the servers we are on.",
"Download avatars, icons and banners of the servers we are on.",
|| true,
);
+25 -1
View File
@@ -28,6 +28,7 @@ use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
use voelin_stream::{PeerConfig, Request, StreamNotification};
use crate::book::presence_from_book;
use crate::cache;
use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState};
use crate::offline::{OfflineMessage, OfflineMessageInfo};
use crate::settings::{FILES_PROGRESS_MS, SharedSettings};
@@ -284,6 +285,13 @@ 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.
fn image_download_time(size: u64) -> Duration {
Duration::from_secs(30 + size / cache::MIN_PICTURE_RATE)
}
/// 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| {
@@ -495,9 +503,17 @@ impl Voice {
if let Some(Job::Download { transfer, offset, sink, report, .. }) =
self.jobs.remove(&handle)
{
// Pictures (avatars, icons, banners): bounded like the
// banners on the web, the user's own files are not.
if transfer.is_none() && download.size > cache::MAX_PICTURE_BYTES {
let limit = cache::MAX_PICTURE_BYTES >> 20;
report(TransferState::Failed(format!("larger than {limit} MiB")));
return Ok(());
}
let part = sink.part().map(ToOwned::to_owned);
let progress = self.progress_every();
let task_report = report.clone();
let deadline = image_download_time(download.size);
let task = tokio::spawn(async move {
let receive = files::download(
download.stream,
@@ -509,7 +525,7 @@ impl Voice {
);
if transfer.is_some() {
receive.await;
} else if timeout(Duration::from_secs(30), receive).await.is_err() {
} else if timeout(deadline, receive).await.is_err() {
task_report(TransferState::Failed("image download timed out".into()));
}
});
@@ -996,4 +1012,12 @@ mod image_download_tests {
expire_image_jobs(&mut jobs, started + Duration::from_secs(60));
assert_eq!(reports.lock().unwrap().len(), 1);
}
#[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));
// The largest picture, at the slowest rate allowed.
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(30 + 2048));
}
}
+112 -36
View File
@@ -4,24 +4,36 @@
//! They go into the engine's cache ([`crate::cache`], named by the MD5 hash
//! of the address) like avatars and icons, and only with
//! `cache.fetch_images`: fetching one contacts a host the server chose, as
//! the official client does. A picture is at most [`MAX_BYTES`], arrives
//! within [`TIMEOUT`] (connected within [`CONNECT_TIMEOUT`]) and is kept
//! only if its content is a picture the UI shows (PNG, JPEG, GIF, WebP,
//! SVG), whatever its address or the server say. The client is the
//! workspace's reqwest with rustls: system proxies (`HTTPS_PROXY`,
//! the official client does. A picture is at most
//! [`cache::MAX_PICTURE_BYTES`] and goes to disk as it arrives; it connects
//! within [`CONNECT_TIMEOUT`], and a download fails when nothing arrives for
//! [`READ_TIMEOUT`] or, after [`GRACE`], when it averages less than
//! [`cache::MIN_PICTURE_RATE`]: a large banner on a slow host still arrives.
//! It is kept only if its content is a picture the UI shows (PNG, JPEG,
//! GIF, WebP, SVG), whatever its address or the server say. The client is
//! the workspace's reqwest with rustls: system proxies (`HTTPS_PROXY`,
//! `NO_PROXY`, …) and the platform's certificate store.
//!
//! Banners in the server's own files (`ts3image://`) come through the voice
//! connection instead ([`crate::files::server_image`]).
use std::path::Path;
use std::sync::LazyLock;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use crate::cache::{self, Cache, Fetch, Waiter};
/// Allow larger GIF/PNG banners while bounding each buffered response.
pub(crate) const MAX_BYTES: u64 = 16 << 20;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
const READ_TIMEOUT: Duration = Duration::from_secs(10);
const TIMEOUT: Duration = Duration::from_secs(30);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const READ_TIMEOUT: Duration = Duration::from_secs(20);
/// 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;
/// 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";
/// 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);
@@ -33,7 +45,6 @@ static CLIENT: LazyLock<Result<reqwest::Client, String>> = LazyLock::new(|| {
reqwest::Client::builder()
.connect_timeout(CONNECT_TIMEOUT)
.read_timeout(READ_TIMEOUT)
.timeout(TIMEOUT)
.user_agent(concat!("Voelin/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|e| e.to_string())
@@ -51,39 +62,69 @@ pub(crate) fn fetch(cache: Cache, url: &str, fresh: bool, max_cache_bytes: u64,
let url = url.to_owned();
tokio::spawn(async move {
let _permit = DOWNLOADS.acquire().await.expect("download semaphore stays open");
let result = download(&url, &temp, MAX_BYTES).await;
let result = download(&url, &temp, &LIMITS).await;
cache.finish(&key, &temp, result, max_cache_bytes);
});
}
/// Download the picture at `url` into `to`: at most `max_bytes`, and only
/// if it is a picture.
async fn download(url: &str, to: &Path, max_bytes: u64) -> Result<(), String> {
/// How large and how slow a download may be.
struct Limits {
max_bytes: u64,
grace: Duration,
/// Bytes a second, on average since the start, once `grace` is over.
min_rate: u64,
}
const LIMITS: Limits =
Limits { max_bytes: cache::MAX_PICTURE_BYTES, grace: GRACE, min_rate: cache::MIN_PICTURE_RATE };
/// Download the picture at `url` into `to` within `limits`, and only if it
/// is a picture (what arrived stays in `to` on failure; the cache removes it).
async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> {
let client = CLIENT.as_ref().map_err(Clone::clone)?;
let too_big = || format!("larger than {} KiB", max_bytes >> 10);
let too_big = || format!("larger than {} KiB", limits.max_bytes >> 10);
let mut response = client
.get(url)
.header(reqwest::header::ACCEPT, ACCEPT)
.send()
.await
.and_then(reqwest::Response::error_for_status)
.map_err(|e| e.to_string())?;
if response.content_length().is_some_and(|n| n > max_bytes) {
if response.content_length().is_some_and(|n| n > limits.max_bytes) {
return Err(too_big());
}
let mut data = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
if (data.len() + chunk.len()) as u64 > max_bytes {
return Err(too_big());
}
data.extend_from_slice(&chunk);
}
if !is_picture(&data) {
return Err("not a picture".into());
}
if let Some(dir) = to.parent() {
tokio::fs::create_dir_all(dir).await.map_err(|e| e.to_string())?;
}
tokio::fs::write(to, &data).await.map_err(|e| e.to_string())
let mut file = tokio::fs::File::create(to).await.map_err(|e| e.to_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())? {
received += chunk.len() as u64;
if received > limits.max_bytes {
return Err(too_big());
}
if head.len() < SNIFF {
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());
}
}
let elapsed = started.elapsed();
let expected = limits.min_rate.saturating_mul(elapsed.as_millis() as u64) / 1000;
if elapsed > limits.grace && received < expected {
return Err(format!("too slow: {} KiB in {} s", received >> 10, elapsed.as_secs()));
}
file.write_all(&chunk).await.map_err(|e| e.to_string())?;
}
file.flush().await.map_err(|e| e.to_string())?;
drop(file);
if !is_picture(&head) {
return Err("not a picture".into());
}
Ok(())
}
/// Whether `data` is a picture the UI decodes, told by its content as the
@@ -134,11 +175,17 @@ mod tests {
"/svg" => {
("200 OK", true, b"<svg xmlns='http://www.w3.org/2000/svg'/>".to_vec())
}
"/large-banner" => ("200 OK", true, [PNG, &vec![0; 5 << 20]].concat()),
// Above the earlier limits of 4 and 16 MiB.
"/large-banner" => ("200 OK", true, [PNG, &vec![0; 20 << 20]].concat()),
// Too big, as announced or as it comes.
"/big" => ("200 OK", true, [PNG, &[0; 4000]].concat()),
"/big-unannounced" => ("200 OK", false, [PNG, &[0; 4000]].concat()),
"/page" => ("200 OK", true, b"<!DOCTYPE html><html></html>".to_vec()),
"/long-page" => {
("200 OK", false, [b"<!DOCTYPE html>", &[b' '; 4000][..]].concat())
}
// A picture, then a byte every 100 ms.
"/slow" => ("200 OK", true, [PNG, &[0; 20]].concat()),
_ => ("404 Not Found", true, b"no".to_vec()),
};
let mut head = format!("HTTP/1.1 {status}\r\nConnection: close\r\n");
@@ -147,6 +194,17 @@ mod tests {
}
head += "\r\n";
let _ = socket.write_all(head.as_bytes()).await;
if path == "/slow" {
let (picture, rest) = body.split_at(PNG.len());
let _ = socket.write_all(picture).await;
for byte in rest {
tokio::time::sleep(Duration::from_millis(100)).await;
if socket.write_all(&[*byte]).await.is_err() {
return;
}
}
return;
}
let _ = socket.write_all(&body).await;
});
}
@@ -165,21 +223,25 @@ mod tests {
let base = server().await;
let dir = temp_dir("download");
let to = dir.join("tmp/x.part");
download(&format!("{base}/banner"), &to, 1000).await.unwrap();
let limits = Limits { max_bytes: 1000, ..LIMITS };
download(&format!("{base}/banner"), &to, &limits).await.unwrap();
assert_eq!(std::fs::read(&to).unwrap(), PNG);
download(&format!("{base}/svg"), &to, 1000).await.unwrap();
download(&format!("{base}/svg"), &to, &limits).await.unwrap();
for (path, error) in [
("/big", "larger than"),
("/big-unannounced", "larger than"),
("/page", "not a picture"),
("/missing", "404"),
] {
let e = download(&format!("{base}{path}"), &to, 1000).await.unwrap_err();
let e = download(&format!("{base}{path}"), &to, &limits).await.unwrap_err();
assert!(e.contains(error), "{path}: {e}");
}
// An error page longer than the first bytes looked at, unannounced.
let e = download(&format!("{base}/long-page"), &to, &LIMITS).await.unwrap_err();
assert!(e.contains("not a picture"), "{e}");
// Nothing listens there.
let port = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap().port();
assert!(download(&format!("http://127.0.0.1:{port}/b"), &to, 1000).await.is_err());
assert!(download(&format!("http://127.0.0.1:{port}/b"), &to, &limits).await.is_err());
std::fs::remove_dir_all(dir).unwrap();
}
@@ -211,12 +273,26 @@ mod tests {
}
#[tokio::test]
async fn banners_above_the_old_four_megabyte_limit_are_downloaded() {
async fn banners_above_the_old_limits_are_downloaded() {
let base = server().await;
let dir = temp_dir("large-banner");
let path = dir.join("large");
download(&format!("{base}/large-banner"), &path, MAX_BYTES).await.unwrap();
assert!(std::fs::metadata(&path).unwrap().len() > 4 << 20);
download(&format!("{base}/large-banner"), &path, &LIMITS).await.unwrap();
assert!(std::fs::metadata(&path).unwrap().len() > 16 << 20);
std::fs::remove_dir_all(dir).unwrap();
}
#[tokio::test]
async fn a_trickling_download_ends_after_its_grace() {
let base = server().await;
let dir = temp_dir("slow");
let to = dir.join("slow");
// Slow, but within its grace: it arrives.
let patient = Limits { grace: Duration::from_secs(60), ..LIMITS };
download(&format!("{base}/slow"), &to, &patient).await.unwrap();
let strict = Limits { grace: Duration::from_millis(150), min_rate: 1 << 20, ..LIMITS };
let e = download(&format!("{base}/slow"), &to, &strict).await.unwrap_err();
assert!(e.contains("too slow"), "{e}");
std::fs::remove_dir_all(dir).unwrap();
}