review: fix what the review of the gateway, avatar and banner changes found
- voelinctl observes with the new gateway list and checks avatar hashes only when they are MD5s (a myTeamSpeak avatar's hash is its link). - Gateway discovery keeps to the most specific name that publishes a record; another server's gateway is no fallback. The admin guide says so. - The observer's resync keeps the avatars clientlist does not tell (they come with the enter and update notifications). - A server avatar given up on counts for that picture only: a new one is tried again, and one that arrives after all is shown again. - updatemytsdata goes again after tsclientlib reconnects (the server forgets it), and once, not twice, when signing in. - SVG is told by its prolog: a page with an svg in it (HTML, XHTML) is a page, refused and logged as one; the UI tells it the same way. - Cursors (CUR) are no longer taken for pictures; MP4 and MOV are named videos, not AVIF. - The UI decodes at most 128 MiB of pixels on its thread, drops the full picture before copying the small one, logs what it cannot decode, and remembers pictures it cannot show instead of decoding them on every refresh; a banner that reloads unchanged is not decoded again. - The early refusal of a long error page is tested again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
This commit is contained in:
1 parent
07038c58c3
commit
47f5e2d9aa
11 files changed
+415
-125
No files matched your search
@@ -15,10 +15,12 @@
|
||||
//! tried. That answer is plain HTTP, so it is asked only when nothing or a
|
||||
//! plain record is published: a TLS-only publication stays TLS-only.
|
||||
//!
|
||||
//! Every gateway found is kept, best first (the most specific name, at a
|
||||
//! name TLS before plain, by priority, then the gateway's own answer), and
|
||||
//! tried in turn ([`crate::Command::ObserveGateway`]): a TLS proxy that
|
||||
//! fails falls back to a published plain one. Discovery trusts DNS and the
|
||||
//! The most specific name with a record wins: a parent domain's records
|
||||
//! are another server's gateway when the host publishes its own. Every
|
||||
//! gateway of that name is kept, best first (TLS before plain, by
|
||||
//! priority, then the gateway's own answer at that name), and tried in turn
|
||||
//! ([`crate::Command::ObserveGateway`]): a TLS proxy that fails falls back
|
||||
//! to the plain gateway published next to it. Discovery trusts DNS and the
|
||||
//! network as TSDNS does; falling back from a published `_tsgws` to a
|
||||
//! published `_tsgw` is no weaker than publishing only `_tsgw`. What an
|
||||
//! admin publishes is in `docs/gateway-admin.md`.
|
||||
@@ -135,20 +137,26 @@ async fn gateways_with(address: &str, lookups: Lookups) -> Vec<String> {
|
||||
if names.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut urls = if host.parse::<IpAddr>().is_err() && host.contains('.') {
|
||||
let srv = if host.parse::<IpAddr>().is_err() && host.contains('.') {
|
||||
from_srv(&names, &lookups).await
|
||||
} else {
|
||||
Vec::new()
|
||||
None
|
||||
};
|
||||
// The gateway's own answer comes over plain HTTP: not for a server that
|
||||
// publishes only TLS.
|
||||
if urls.is_empty() || urls.iter().any(|url| url.starts_with("ws://")) {
|
||||
for url in from_well_known(&names, &lookups).await {
|
||||
if !urls.contains(&url) {
|
||||
// publishes only TLS; at the name that publishes, or without records the
|
||||
// most specific name that answers.
|
||||
let mut urls = match srv {
|
||||
None => from_well_known(&names, &lookups).await.into_iter().collect(),
|
||||
Some((name, mut urls)) => {
|
||||
if urls.iter().any(|url| url.starts_with("ws://"))
|
||||
&& let Some(url) = from_well_known(&[name], &lookups).await
|
||||
&& !urls.contains(&url)
|
||||
{
|
||||
urls.push(url);
|
||||
}
|
||||
urls
|
||||
}
|
||||
}
|
||||
};
|
||||
urls.truncate(MAX_CANDIDATES);
|
||||
urls
|
||||
}
|
||||
@@ -181,17 +189,21 @@ fn names(host: &str) -> Vec<&str> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The URLs from SRV records, every name and service asked at once: the
|
||||
/// most specific name first, at a name TLS first, by priority.
|
||||
async fn from_srv(names: &[&str], lookups: &Lookups) -> Vec<String> {
|
||||
let queries: Vec<(&str, String)> = names
|
||||
/// The URLs from SRV records, every name and service asked at once: those
|
||||
/// of the most specific name with a usable record (with that name), TLS
|
||||
/// first, by priority.
|
||||
async fn from_srv<'a>(names: &[&'a str], lookups: &Lookups) -> Option<(&'a str, Vec<String>)> {
|
||||
let queries: Vec<(&str, &str, String)> = names
|
||||
.iter()
|
||||
.flat_map(|name| {
|
||||
[("wss", format!("_tsgws._tcp.{name}.")), ("ws", format!("_tsgw._tcp.{name}."))]
|
||||
[
|
||||
(*name, "wss", format!("_tsgws._tcp.{name}.")),
|
||||
(*name, "ws", format!("_tsgw._tcp.{name}.")),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
let answers = join_all(queries.iter().map(|(_, owner)| (lookups.srv)(owner.clone()))).await;
|
||||
let found: Vec<_> = queries
|
||||
let answers = join_all(queries.iter().map(|(.., owner)| (lookups.srv)(owner.clone()))).await;
|
||||
let mut found: Vec<_> = queries
|
||||
.iter()
|
||||
.zip(answers)
|
||||
.filter_map(|(query, mut records)| {
|
||||
@@ -201,9 +213,11 @@ async fn from_srv(names: &[&str], lookups: &Lookups) -> Vec<String> {
|
||||
(!records.is_empty()).then_some((query, records))
|
||||
})
|
||||
.collect();
|
||||
let paths = join_all(found.iter().map(|((_, owner), _)| path_at(lookups, owner))).await;
|
||||
let name = found.first()?.0.0;
|
||||
found.retain(|((n, ..), _)| *n == name);
|
||||
let paths = join_all(found.iter().map(|((.., owner), _)| path_at(lookups, owner))).await;
|
||||
let mut urls = Vec::new();
|
||||
for (((scheme, _), records), path) in found.into_iter().zip(paths) {
|
||||
for (((_, scheme, _), records), path) in found.into_iter().zip(paths) {
|
||||
for (_, target, port) in records {
|
||||
let url = format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.'));
|
||||
if !urls.contains(&url) {
|
||||
@@ -211,7 +225,7 @@ async fn from_srv(names: &[&str], lookups: &Lookups) -> Vec<String> {
|
||||
}
|
||||
}
|
||||
}
|
||||
urls
|
||||
Some((name, urls))
|
||||
}
|
||||
|
||||
/// The path at a SRV record's name: `path=…` from its TXT records, `/v1`
|
||||
@@ -228,17 +242,11 @@ async fn path_at(lookups: &Lookups, owner: &str) -> String {
|
||||
path
|
||||
}
|
||||
|
||||
/// The URLs gateways give for themselves at `names`, all asked at once,
|
||||
/// the most specific first.
|
||||
async fn from_well_known(names: &[&str], lookups: &Lookups) -> Vec<String> {
|
||||
/// The URL a gateway gives for itself at one of `names`, all asked at
|
||||
/// once; the most specific that answers wins.
|
||||
async fn from_well_known(names: &[&str], lookups: &Lookups) -> Option<String> {
|
||||
let answers = join_all(names.iter().map(|name| (lookups.probe)((*name).to_owned()))).await;
|
||||
let mut urls: Vec<String> = Vec::new();
|
||||
for url in answers.into_iter().flatten() {
|
||||
if !urls.contains(&url) {
|
||||
urls.push(url);
|
||||
}
|
||||
}
|
||||
urls
|
||||
answers.into_iter().flatten().next()
|
||||
}
|
||||
|
||||
/// tsgw's answer at `http://<host>:<port>/.well-known/tsgw`.
|
||||
@@ -325,8 +333,10 @@ mod tests {
|
||||
assert!(gateways_with("example", lookups).await.is_empty());
|
||||
}
|
||||
|
||||
/// All of the most specific name's gateways, TLS first, by priority; a
|
||||
/// parent domain's only for a host without its own.
|
||||
#[tokio::test]
|
||||
async fn every_record_in_order_most_specific_name_then_tls() {
|
||||
async fn the_most_specific_name_wins_with_all_its_gateways() {
|
||||
let lookups = fake(
|
||||
&[
|
||||
("_tsgws._tcp.example.test.", 0, "domain.example.test.", 443),
|
||||
@@ -342,7 +352,6 @@ mod tests {
|
||||
"wss://tls.example.test:8443/tsgw/v1",
|
||||
"wss://backup.example.test:443/tsgw/v1",
|
||||
"ws://plain.example.test:7788/v1",
|
||||
"wss://domain.example.test:443/v1",
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -373,6 +382,28 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A gateway at the domain fronts another server than one of its hosts
|
||||
/// that publishes its own: never a fallback for it, nor the domain's own
|
||||
/// answer.
|
||||
#[tokio::test]
|
||||
async fn another_servers_gateway_is_no_fallback() {
|
||||
let lookups = answering(
|
||||
fake(
|
||||
&[
|
||||
("_tsgws._tcp.ts1.example.test.", 0, "gw1.example.test.", 443),
|
||||
("_tsgw._tcp.ts1.example.test.", 0, "ts1.example.test.", 7788),
|
||||
("_tsgws._tcp.example.test.", 0, "gw-main.example.test.", 443),
|
||||
],
|
||||
&[],
|
||||
),
|
||||
&[("example.test", "ws://main.example.test:7788/v1")],
|
||||
);
|
||||
assert_eq!(
|
||||
gateways_with("ts1.example.test", lookups).await,
|
||||
["wss://gw1.example.test:443/v1", "ws://ts1.example.test:7788/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_gateways_own_answer_comes_last() {
|
||||
let lookups = answering(
|
||||
|
||||
@@ -96,6 +96,8 @@ use voelin_stream::{
|
||||
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
|
||||
};
|
||||
pub use voice::VoiceOptions;
|
||||
/// Banners are downloaded and shown by the same rule.
|
||||
pub use web::is_svg;
|
||||
|
||||
pub type SessionId = u64;
|
||||
|
||||
@@ -646,9 +648,10 @@ pub enum Event {
|
||||
request: RequestId,
|
||||
result: Result<(), String>,
|
||||
},
|
||||
/// A client's avatar is in the cache: `path`, its MD5 `hash`
|
||||
/// ([`voelin_model::ClientInfo::avatar`]). Comes when the client appears
|
||||
/// with an avatar and when it changes.
|
||||
/// A client's avatar is in the cache: `path`, and `hash`: the MD5 of a
|
||||
/// server avatar ([`voelin_model::ClientInfo::avatar`]), or the address
|
||||
/// of a myTeamSpeak avatar ([`voelin_model::ClientInfo::myts_avatar`]).
|
||||
/// Comes when the client appears with an avatar and when it changes.
|
||||
AvatarReady {
|
||||
session: SessionId,
|
||||
client_uid: String,
|
||||
|
||||
@@ -284,9 +284,10 @@ struct Session {
|
||||
/// myTeamSpeak avatars wanted per client unique id (their link), any
|
||||
/// presence: where the server's avatar is not shown.
|
||||
myts_avatars: HashMap<String, String>,
|
||||
/// Clients whose server avatar could not be downloaded (retries used
|
||||
/// up): their myTeamSpeak avatar is shown instead.
|
||||
server_avatars_failed: HashSet<String>,
|
||||
/// Server avatars that could not be downloaded (retries used up), per
|
||||
/// client unique id (their hash): the client's myTeamSpeak avatar is
|
||||
/// shown instead, until it sets another.
|
||||
server_avatars_failed: HashMap<String, String>,
|
||||
/// Icons reported or being fetched, voice only.
|
||||
icons: HashSet<u32>,
|
||||
/// Pictures on the web (banners) reported or being fetched, by address.
|
||||
@@ -330,7 +331,7 @@ impl Session {
|
||||
contacts_rx,
|
||||
avatars: HashMap::new(),
|
||||
myts_avatars: HashMap::new(),
|
||||
server_avatars_failed: HashSet::new(),
|
||||
server_avatars_failed: HashMap::new(),
|
||||
icons: HashSet::new(),
|
||||
pictures: HashSet::new(),
|
||||
unfetchable: HashSet::new(),
|
||||
@@ -748,7 +749,7 @@ impl Session {
|
||||
.as_ref()
|
||||
.and_then(|p| p.client_by_uid(&client_uid))
|
||||
.and_then(|c| c.avatar.clone())
|
||||
.filter(|_| !self.server_avatars_failed.contains(&client_uid));
|
||||
.filter(|hash| self.server_avatars_failed.get(&client_uid) != Some(hash));
|
||||
let myts = self.shown_client(&client_uid).and_then(|c| c.myts_avatar.clone());
|
||||
if let Some(hash) = hash.filter(|_| self.voice.is_some()) {
|
||||
self.fetch_avatar(&client_uid, &hash, true);
|
||||
@@ -979,7 +980,7 @@ impl Session {
|
||||
let (Some(uid), Some(url)) = (&c.uid, &c.myts_avatar) else { continue };
|
||||
let server_avatar = c.avatar.is_some()
|
||||
&& self.voice.is_some()
|
||||
&& !self.server_avatars_failed.contains(uid);
|
||||
&& self.server_avatars_failed.get(uid) != c.avatar.as_ref();
|
||||
if server_avatar {
|
||||
continue;
|
||||
}
|
||||
@@ -1058,6 +1059,16 @@ impl Session {
|
||||
match result {
|
||||
Ok(path) => {
|
||||
self.image_retries.remove(&request);
|
||||
// A server avatar given up on came after all (asked for
|
||||
// again): it is shown again in place of the myTeamSpeak one.
|
||||
if let ImageRequest::Avatar { uid, hash } = &request
|
||||
&& self.server_avatars_failed.get(uid) == Some(hash)
|
||||
{
|
||||
self.server_avatars_failed.remove(uid);
|
||||
if let Some(presence) = self.voice_presence.clone() {
|
||||
self.fetch_myts_avatars(&presence);
|
||||
}
|
||||
}
|
||||
if !requested && !self.settings.current().get(&CACHE_FETCH_IMAGES) {
|
||||
return;
|
||||
}
|
||||
@@ -1077,7 +1088,7 @@ impl Session {
|
||||
}
|
||||
Err(error) => {
|
||||
let avatar_of = match &request {
|
||||
ImageRequest::Avatar { uid, .. } => Some(uid.clone()),
|
||||
ImageRequest::Avatar { uid, hash } => Some((uid.clone(), hash.clone())),
|
||||
_ => None,
|
||||
};
|
||||
let retry = self
|
||||
@@ -1090,11 +1101,13 @@ impl Session {
|
||||
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)
|
||||
&& self.server_avatars_failed.insert(uid)
|
||||
&& let Some(presence) = self.voice_presence.clone()
|
||||
if let (None, Some((uid, hash))) = (retry.due, avatar_of)
|
||||
&& self.server_avatars_failed.get(&uid) != Some(&hash)
|
||||
{
|
||||
self.fetch_myts_avatars(&presence);
|
||||
self.server_avatars_failed.insert(uid, hash);
|
||||
if let Some(presence) = self.voice_presence.clone() {
|
||||
self.fetch_myts_avatars(&presence);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1107,6 +1120,7 @@ impl Session {
|
||||
self.image_epoch += 1;
|
||||
self.avatars.clear();
|
||||
self.myts_avatars.clear();
|
||||
self.server_avatars_failed.clear();
|
||||
self.icons.clear();
|
||||
self.pictures.clear();
|
||||
self.image_retries.clear();
|
||||
@@ -2464,6 +2478,12 @@ mod banner_tests {
|
||||
);
|
||||
}
|
||||
assert_eq!(session.myts_avatars.get("B=").map(String::as_str), Some(b));
|
||||
// A new server avatar is tried again: the failure was that one's.
|
||||
let presence = session.voice_presence.as_mut().unwrap();
|
||||
presence.clients.get_mut(&2).unwrap().avatar =
|
||||
Some("fedcba9876543210fedcba9876543210".into());
|
||||
session.publish_presence();
|
||||
assert_eq!(session.myts_avatars.keys().collect::<Vec<_>>(), ["A="]);
|
||||
std::fs::remove_dir_all(cache.dir()).unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -349,6 +349,9 @@ struct Voice {
|
||||
pending: HashMap<MessageHandle, Pending>,
|
||||
jobs: HashMap<FiletransferHandle, Job>,
|
||||
transfers: HashMap<TransferId, Slot>,
|
||||
/// `updatemytsdata` is to be sent once connected again: a reconnect
|
||||
/// (tsclientlib's own) leaves the server without it.
|
||||
myts_data_due: bool,
|
||||
}
|
||||
|
||||
async fn run_inner(
|
||||
@@ -443,12 +446,13 @@ async fn run_inner(
|
||||
pending: HashMap::new(),
|
||||
jobs: HashMap::new(),
|
||||
transfers: HashMap::new(),
|
||||
myts_data_due: false,
|
||||
};
|
||||
voice.publish_state()?;
|
||||
// The account's avatar, for everyone on the server (as the official
|
||||
// client, once connected).
|
||||
data.borrow_and_update();
|
||||
voice.send_myts_data(&identity, &data);
|
||||
voice.send_myts_data();
|
||||
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(250));
|
||||
let result = loop {
|
||||
@@ -472,12 +476,14 @@ async fn run_inner(
|
||||
}
|
||||
Err(e) => break Err(anyhow::anyhow!("myTeamSpeak account update: {e}")),
|
||||
}
|
||||
// After the proof, what is shown of the account (a sign-in).
|
||||
voice.send_myts_data(&identity, &data);
|
||||
// After the proof, what is shown of the account (a sign-in):
|
||||
// its change, if any, is in this one.
|
||||
data.borrow_and_update();
|
||||
voice.send_myts_data();
|
||||
}
|
||||
Input::MytsDataChanged => {
|
||||
data.borrow_and_update();
|
||||
voice.send_myts_data(&identity, &data);
|
||||
voice.send_myts_data();
|
||||
}
|
||||
Input::Item(None) => break Err(anyhow::anyhow!("connection closed")),
|
||||
Input::Item(Some(Err(e))) => break Err(e.into()),
|
||||
@@ -590,6 +596,10 @@ impl Voice {
|
||||
self.message(target, invoker, message);
|
||||
}
|
||||
}
|
||||
// Connected again after a reconnect.
|
||||
if self.myts_data_due {
|
||||
self.send_myts_data();
|
||||
}
|
||||
self.publish_state()?;
|
||||
}
|
||||
StreamItem::Audio(packet) => {
|
||||
@@ -672,6 +682,7 @@ impl Voice {
|
||||
}
|
||||
StreamItem::DisconnectedTemporarily(reason) => {
|
||||
warn!(?reason, "voice connection interrupted, reconnecting");
|
||||
self.myts_data_due = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -843,22 +854,22 @@ impl Voice {
|
||||
}
|
||||
|
||||
/// Show the server the account's certificate and avatar
|
||||
/// (`updatemytsdata`), when connected with the account.
|
||||
fn send_myts_data(
|
||||
&mut self,
|
||||
identity: &watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: &watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
) {
|
||||
if identity.borrow().is_none() {
|
||||
/// (`updatemytsdata`), when connected with the account; while
|
||||
/// reconnecting, once connected again.
|
||||
fn send_myts_data(&mut self) {
|
||||
self.myts_data_due = false;
|
||||
if self.link.myts_identity.borrow().is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(data) = data.borrow().clone().filter(|d| !d.certificate.is_empty()) else {
|
||||
let data = self.link.myts_data.borrow().clone();
|
||||
let Some(data) = data.filter(|d| !d.certificate.is_empty()) else {
|
||||
return;
|
||||
};
|
||||
match self.con.send_myts_data(&data) {
|
||||
Ok(handle) => {
|
||||
self.pending.insert(handle, Pending::MytsData);
|
||||
}
|
||||
Err(tsclientlib::Error::NotConnected) => self.myts_data_due = true,
|
||||
Err(e) => warn!(error = %e, "the account's avatar was not sent"),
|
||||
}
|
||||
}
|
||||
@@ -1205,6 +1216,51 @@ mod account_tests {
|
||||
assert!(network > 0 && timers > 0 && audio > 0);
|
||||
}
|
||||
|
||||
/// A reconnect (tsclientlib's own) leaves the server without the
|
||||
/// account's avatar: it goes again once connected, not before.
|
||||
#[tokio::test]
|
||||
async fn account_data_waits_for_the_connection() {
|
||||
// A silent UDP peer: never connected.
|
||||
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
// Scalar one and the standard compressed Edwards base point.
|
||||
let mut private = [0; 32];
|
||||
private[0] = 1;
|
||||
let mut public = [0x66; 32];
|
||||
public[0] = 0x58;
|
||||
let identity =
|
||||
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap();
|
||||
let data = tsclientlib::MytsData { certificate: vec![1], avatar: Vec::new() };
|
||||
let (events, _) = broadcast::channel(8);
|
||||
let link = VoiceLink {
|
||||
session: 1,
|
||||
events,
|
||||
settings: SharedSettings::new(crate::settings::Settings::default()),
|
||||
myts_identity: watch::channel(Some(Arc::new(identity))).1,
|
||||
myts_data: watch::channel(Some(Arc::new(data))).1,
|
||||
};
|
||||
let mut voice = Voice {
|
||||
con: Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap(),
|
||||
link,
|
||||
events: mpsc::unbounded_channel().0,
|
||||
server_uid: String::new(),
|
||||
talking: HashMap::new(),
|
||||
pending: HashMap::new(),
|
||||
jobs: HashMap::new(),
|
||||
transfers: HashMap::new(),
|
||||
myts_data_due: false,
|
||||
};
|
||||
voice.send_myts_data();
|
||||
assert!(voice.myts_data_due && voice.pending.is_empty());
|
||||
voice.myts_data_due = false;
|
||||
let reconnecting = tsclientlib::TemporaryDisconnectReason::Timeout("test");
|
||||
voice.item(StreamItem::DisconnectedTemporarily(reconnecting)).unwrap();
|
||||
assert!(voice.myts_data_due);
|
||||
// Not connected yet: still due.
|
||||
let _ = voice.item(StreamItem::BookEvents(Vec::new()));
|
||||
assert!(voice.myts_data_due && voice.pending.is_empty());
|
||||
timeout(Duration::from_millis(100), shutdown_connection(voice.con)).await.unwrap().unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_never_polls_a_connecting_connection() {
|
||||
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
|
||||
@@ -185,7 +185,12 @@ fn not_a_picture(head: &[u8]) -> String {
|
||||
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"
|
||||
// ISO media, told by its brand.
|
||||
match &head[8..12] {
|
||||
b"avif" | b"avis" | b"heic" | b"heix" | b"heim" | b"heis" | b"hevc" | b"hevx"
|
||||
| b"mif1" | b"msf1" => "AVIF or HEIF, which cannot be shown",
|
||||
_ => "a video (MP4, MOV), which cannot be shown",
|
||||
}
|
||||
} else if start.starts_with(b"{") {
|
||||
"JSON"
|
||||
} else {
|
||||
@@ -205,33 +210,62 @@ pub(crate) fn host_of(url: &str) -> String {
|
||||
}
|
||||
|
||||
/// Whether `data` is a picture the UI decodes, told by its content as the
|
||||
/// UI tells it (SVG by its start, without leading blanks, or after a
|
||||
/// comment or a DOCTYPE).
|
||||
/// UI tells it (SVG by [`is_svg`]).
|
||||
fn is_picture(data: &[u8]) -> bool {
|
||||
const STARTS: [&[u8]; 7] = [
|
||||
const STARTS: [&[u8]; 6] = [
|
||||
b"\x89PNG\r\n\x1a\n",
|
||||
b"\xff\xd8\xff",
|
||||
b"GIF87a",
|
||||
b"GIF89a",
|
||||
b"BM",
|
||||
// ICO and CUR.
|
||||
// ICO.
|
||||
b"\0\0\x01\0",
|
||||
b"\0\0\x02\0",
|
||||
];
|
||||
STARTS.iter().any(|s| data.starts_with(s))
|
||||
|| (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"))
|
||||
/// Whether `data` starts an SVG document: after a BOM and the prolog (the
|
||||
/// XML declaration and other processing instructions, comments, blanks),
|
||||
/// a DOCTYPE `svg` or an `svg` element. A page with an `svg` in it (an
|
||||
/// HTML page, XHTML too) is not; nor is a start cut off before it tells.
|
||||
pub fn is_svg(data: &[u8]) -> bool {
|
||||
let mut rest = data.strip_prefix(b"\xef\xbb\xbf").unwrap_or(data);
|
||||
loop {
|
||||
rest = rest.trim_ascii_start();
|
||||
let (skipped, end) = if let Some(pi) = rest.strip_prefix(b"<?") {
|
||||
(pi, b"?>".as_slice())
|
||||
} else if let Some(comment) = rest.strip_prefix(b"<!--") {
|
||||
(comment, b"-->".as_slice())
|
||||
} else if rest.get(..9).is_some_and(|s| s.eq_ignore_ascii_case(b"<!doctype")) {
|
||||
// The root element it declares.
|
||||
let name = rest[9..].trim_ascii_start();
|
||||
return name.get(..3).is_some_and(|n| n.eq_ignore_ascii_case(b"svg"))
|
||||
&& name
|
||||
.get(3)
|
||||
.is_some_and(|b| b.is_ascii_whitespace() || matches!(b, b'>' | b'['));
|
||||
} else if let Some(element) = rest.strip_prefix(b"<") {
|
||||
return names_svg(element);
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
let Some(at) = skipped.windows(end.len()).position(|w| w == end) else {
|
||||
return false;
|
||||
};
|
||||
rest = &skipped[at + end.len()..];
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the element named at the start of `tag` is `svg`, with a
|
||||
/// namespace prefix or without.
|
||||
fn names_svg(tag: &[u8]) -> bool {
|
||||
let Some(len) = tag.iter().position(|b| b.is_ascii_whitespace() || matches!(b, b'>' | b'/'))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let name = &tag[..len];
|
||||
name == b"svg" || name.ends_with(b":svg")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -277,9 +311,11 @@ mod tests {
|
||||
"/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())
|
||||
}
|
||||
"/long-page" | "/endless-page" => (
|
||||
"200 OK",
|
||||
false,
|
||||
[b"<!DOCTYPE html>".as_slice(), &vec![b' '; SNIFF]].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()),
|
||||
@@ -302,6 +338,12 @@ mod tests {
|
||||
return;
|
||||
}
|
||||
let _ = socket.write_all(&body).await;
|
||||
// Never done: refused by its start or not at all.
|
||||
if path == "/endless-page" {
|
||||
while socket.write_all(b" ").await.is_ok() {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -332,9 +374,14 @@ mod tests {
|
||||
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}");
|
||||
// An error page longer than the first bytes looked at, unannounced:
|
||||
// refused by them, without waiting for the rest.
|
||||
for path in ["/long-page", "/endless-page"] {
|
||||
let url = format!("{base}{path}");
|
||||
let fetch = download(&url, &to, &LIMITS);
|
||||
let e = tokio::time::timeout(Duration::from_secs(5), fetch).await.unwrap().unwrap_err();
|
||||
assert!(e.contains("not a picture (an HTML page)"), "{path}: {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, &limits).await.is_err());
|
||||
@@ -476,12 +523,33 @@ mod tests {
|
||||
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>"));
|
||||
assert!(is_picture(b"<svg:svg xmlns:svg='http://www.w3.org/2000/svg'/>"));
|
||||
assert!(is_picture(
|
||||
b"<?xml version=\"1.0\"?><!-- c --><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"x\"><svg/>"
|
||||
));
|
||||
assert!(is_picture(b"<!DOCTYPE svg [ <!ENTITY e \"x\"> ]><svg/>"));
|
||||
// Pages with an SVG in them are pages.
|
||||
assert!(!is_picture(
|
||||
b"<!DOCTYPE html><html><head><link rel=icon href=\"data:image/svg+xml,<svg/>\"></head></html>"
|
||||
));
|
||||
assert!(!is_picture(b"<!-- x --><html><body><svg/></body></html>"));
|
||||
assert!(!is_picture(b"<?xml version=\"1.0\"?><!DOCTYPE html><html><svg/></html>"));
|
||||
assert!(!is_picture(b"<svgx/>"));
|
||||
// Cut off before it tells.
|
||||
assert!(!is_picture(b"<?xml version=\"1.0\"?><!-- a long comment"));
|
||||
assert!(!is_picture(b"<svg"));
|
||||
// A cursor (CUR) is not shown.
|
||||
assert!(!is_picture(b"\0\0\x02\0\x01\0"));
|
||||
// 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!(
|
||||
not_a_picture(b"\0\0\0\x20ftypisom\0\0\x02\0isomiso2avc1mp41"),
|
||||
"not a picture (a video (MP4, MOV), 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");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user