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");
|
||||
}
|
||||
|
||||
@@ -191,7 +191,8 @@ async fn session(
|
||||
Some(n) => handle_notification(&n, presence, events),
|
||||
None => {
|
||||
// Resync and publish only what changed.
|
||||
let fresh = load(&client).await?;
|
||||
let listed = load(&client).await?;
|
||||
let fresh = keep_unlisted(&presence.read().unwrap(), listed);
|
||||
let deltas = presence.read().unwrap().diff(&fresh);
|
||||
if !deltas.is_empty() {
|
||||
debug!(changes = deltas.len(), "observer resync");
|
||||
@@ -206,6 +207,24 @@ async fn session(
|
||||
}
|
||||
}
|
||||
|
||||
/// What `clientlist` does not tell (the avatars, which come with
|
||||
/// `notifycliententerview` and `notifyclientupdated`), kept from what was
|
||||
/// known of the same client: a resync must not take them away.
|
||||
fn keep_unlisted(old: &Presence, mut fresh: Presence) -> Presence {
|
||||
for (id, client) in &mut fresh.clients {
|
||||
let Some(known) = old.clients.get(id).filter(|known| known.uid == client.uid) else {
|
||||
continue;
|
||||
};
|
||||
if client.avatar.is_none() {
|
||||
client.avatar.clone_from(&known.avatar);
|
||||
}
|
||||
if client.myts_avatar.is_none() {
|
||||
client.myts_avatar.clone_from(&known.myts_avatar);
|
||||
}
|
||||
}
|
||||
fresh
|
||||
}
|
||||
|
||||
fn handle_notification(
|
||||
n: &Notification,
|
||||
presence: &RwLock<Presence>,
|
||||
@@ -240,3 +259,36 @@ fn handle_notification(
|
||||
let _ = events.send(ObserverEvent::Delta(d));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod resync_tests {
|
||||
use super::*;
|
||||
use voelin_model::ClientInfo;
|
||||
|
||||
#[test]
|
||||
fn a_resync_keeps_the_avatars_the_list_does_not_tell() {
|
||||
let client = |uid: &str, myts: Option<&str>| ClientInfo {
|
||||
id: 5,
|
||||
uid: Some(uid.into()),
|
||||
nickname: "a".into(),
|
||||
avatar: myts.map(|_| "0123456789abcdef0123456789abcdef".into()),
|
||||
myts_avatar: myts.map(Into::into),
|
||||
..Default::default()
|
||||
};
|
||||
let mut old = Presence::default();
|
||||
old.clients.insert(5, client("u=", Some("https://a.example.test/on.png")));
|
||||
let mut listed = Presence::default();
|
||||
listed.clients.insert(5, client("u=", None));
|
||||
let fresh = keep_unlisted(&old, listed.clone());
|
||||
assert_eq!(fresh.clients[&5], old.clients[&5]);
|
||||
assert!(old.diff(&fresh).is_empty());
|
||||
// Another client in the same slot starts without them.
|
||||
let mut other = Presence::default();
|
||||
other.clients.insert(5, client("v=", None));
|
||||
let fresh = keep_unlisted(&old, other);
|
||||
assert_eq!(
|
||||
(fresh.clients[&5].avatar.clone(), fresh.clients[&5].myts_avatar.clone()),
|
||||
(None, None)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1004,8 +1004,8 @@ impl App {
|
||||
// Pictures can arrive after the rows were built: draw them again.
|
||||
Event::AvatarReady { session, client_uid, path, .. } => {
|
||||
let view = self.sessions.entry(session as i64).or_default();
|
||||
// A file that arrives again is decoded again.
|
||||
crate::images::forget(&path);
|
||||
// A file that arrives again is decoded again if it changed.
|
||||
crate::images::reloaded(&path);
|
||||
view.avatars.insert(client_uid, path);
|
||||
if self.current == Some(session as i64) {
|
||||
self.refresh_tree();
|
||||
@@ -1017,7 +1017,7 @@ impl App {
|
||||
}
|
||||
Event::IconReady { session, icon, path } => {
|
||||
let view = self.sessions.entry(session as i64).or_default();
|
||||
crate::images::forget(&path);
|
||||
crate::images::reloaded(&path);
|
||||
view.icons.insert(icon, path);
|
||||
self.refresh_servers();
|
||||
if self.current == Some(session as i64) {
|
||||
@@ -1028,7 +1028,7 @@ impl App {
|
||||
Event::PictureReady { session, url, path } => {
|
||||
let view = self.sessions.entry(session as i64).or_default();
|
||||
// The host banner reloads into the same file.
|
||||
crate::images::forget(&path);
|
||||
crate::images::reloaded(&path);
|
||||
view.pictures.insert(url, path);
|
||||
if self.current == Some(session as i64) {
|
||||
self.refresh_toolbar();
|
||||
|
||||
@@ -94,6 +94,16 @@ fn svg_cost(svg_len: usize) -> usize {
|
||||
|
||||
thread_local! {
|
||||
static CACHE: RefCell<Lru<Image>> = RefCell::new(Lru::new(256 << 20));
|
||||
/// What each file decoded held (its length and a hash of its bytes), so
|
||||
/// one that arrives again unchanged is not decoded again.
|
||||
static DECODED: RefCell<HashMap<String, (usize, u64)>> = RefCell::new(HashMap::new());
|
||||
}
|
||||
|
||||
fn fingerprint(bytes: &[u8]) -> (usize, u64) {
|
||||
use std::hash::{DefaultHasher, Hasher};
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hasher.write(bytes);
|
||||
(bytes.len(), hasher.finish())
|
||||
}
|
||||
|
||||
/// Set the budget in megabytes.
|
||||
@@ -124,25 +134,34 @@ pub fn file(path: &std::path::Path) -> Image {
|
||||
// (`avatars/<md5>`, `icons/<id>`), and servers keep PNG, JPEG
|
||||
// and SVG icons alike.
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
DECODED.with(|d| d.borrow_mut().insert(key.to_string(), fingerprint(&bytes)));
|
||||
// One that cannot be shown (too large, not a picture) is
|
||||
// remembered as such, not read again on every refresh; a
|
||||
// changed file is forgotten first (`forget`).
|
||||
// changed file is forgotten first (`reloaded`).
|
||||
Some(decode(&bytes).unwrap_or((Image::default(), UNDECODABLE_COST)))
|
||||
})
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Forget the decoded picture of a file that changed (a reloaded banner).
|
||||
pub fn forget(path: &std::path::Path) {
|
||||
CACHE.with(|c| c.borrow_mut().remove(&path.to_string_lossy()));
|
||||
/// A file that arrived again (a reloaded banner, an avatar fetched again):
|
||||
/// its decoded picture is forgotten if it changed, so it is decoded again.
|
||||
pub fn reloaded(path: &std::path::Path) {
|
||||
let key = path.to_string_lossy();
|
||||
let now = std::fs::read(path).ok().map(|bytes| fingerprint(&bytes));
|
||||
let decoded = DECODED.with(|d| d.borrow().get(key.as_ref()).copied());
|
||||
if now.is_none() || now != decoded {
|
||||
DECODED.with(|d| d.borrow_mut().remove(key.as_ref()));
|
||||
CACHE.with(|c| c.borrow_mut().remove(&key));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
/// A picture with more pixels than this (RGBA bytes) is not decoded at all:
|
||||
/// it is decoded and scaled down on the UI thread.
|
||||
const MAX_DECODED_BYTES: u64 = 128 << 20;
|
||||
|
||||
/// Compressed pictures can be small on disk but huge when decoded. Check
|
||||
/// raster dimensions before Slint allocates pixels on the UI thread. SVGs
|
||||
@@ -151,29 +170,53 @@ 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()?;
|
||||
if reader.format().is_none() {
|
||||
let start = bytes.trim_ascii_start();
|
||||
if !is_svg(start) {
|
||||
// As the engine tells one when it downloads it.
|
||||
if !voelin_core::is_svg(bytes) {
|
||||
return None;
|
||||
}
|
||||
let start = bytes.trim_ascii_start();
|
||||
// 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())));
|
||||
}
|
||||
let (width, height) = reader.into_dimensions().ok()?;
|
||||
let format = reader.format();
|
||||
let (width, height) = match reader.into_dimensions() {
|
||||
Ok(size) => size,
|
||||
Err(error) => {
|
||||
tracing::warn!(?format, %error, "picture not shown: unreadable");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
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));
|
||||
return match Image::load_from_data(bytes, None) {
|
||||
Ok(image) => Some((image, cost)),
|
||||
Err(error) => {
|
||||
tracing::warn!(?format, %error, "picture not shown: not decoded");
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
// Scaled down (the first frame of an animation).
|
||||
// Scaled down (the first frame of an animation). 16 bits a channel
|
||||
// take twice the bytes.
|
||||
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));
|
||||
limits.max_alloc = Some(2 * MAX_DECODED_BYTES + (64 << 20));
|
||||
reader.limits(limits);
|
||||
let small = reader.decode().ok()?.thumbnail(MAX_SIDE, MAX_SIDE).to_rgba8();
|
||||
let full = match reader.decode() {
|
||||
Ok(full) => full,
|
||||
Err(error) => {
|
||||
tracing::warn!(?format, width, height, %error, "picture not shown: not decoded");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let small = full.thumbnail(MAX_SIDE, MAX_SIDE);
|
||||
drop(full);
|
||||
let small = small.into_rgba8();
|
||||
let (width, height) = small.dimensions();
|
||||
let pixels = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::clone_from_slice(
|
||||
small.as_raw(),
|
||||
@@ -183,21 +226,18 @@ fn decode(bytes: &[u8]) -> Option<(Image, usize)> {
|
||||
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
|
||||
/// kept by `key`; an empty image if it cannot be decoded.
|
||||
/// kept by `key`; an empty image if it cannot be decoded (remembered too,
|
||||
/// until [`forget_picture`]).
|
||||
pub fn picture(key: &str, bytes: &[u8]) -> Image {
|
||||
let cache_key = format!("picture:{key}");
|
||||
CACHE.with(|c| c.borrow_mut().get_or_load(&cache_key, || decode(bytes))).unwrap_or_default()
|
||||
CACHE
|
||||
.with(|c| {
|
||||
c.borrow_mut().get_or_load(&cache_key, || {
|
||||
Some(decode(bytes).unwrap_or((Image::default(), UNDECODABLE_COST)))
|
||||
})
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Forget the decoded picture kept by `key` (a changed account avatar).
|
||||
@@ -270,6 +310,10 @@ mod tests {
|
||||
encoder.write_header().unwrap().write_image_data(&[200; 32]).unwrap();
|
||||
assert_eq!(picture("test:4x2", &png).size().width, 4);
|
||||
assert_eq!(picture("test:junk", b"not a picture").size().width, 0);
|
||||
// Remembered: not decoded (and warned about) on every refresh.
|
||||
assert_eq!(picture("test:junk", &png).size().width, 0);
|
||||
forget_picture("test:junk");
|
||||
assert_eq!(picture("test:junk", &png).size().width, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -292,6 +336,8 @@ mod tests {
|
||||
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());
|
||||
// A page with an SVG in it is a page (told so by the engine).
|
||||
assert!(decode(b"<!DOCTYPE html><html><svg/></html>").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -308,7 +354,7 @@ mod tests {
|
||||
#[test]
|
||||
fn large_rasters_are_scaled_down() {
|
||||
use std::io::Write;
|
||||
for (width, height) in [(6000, 6000), (16_385, 1), (1, 16_385)] {
|
||||
for (width, height) in [(5000, 5000), (16_385, 1), (1, 16_385)] {
|
||||
let mut bytes = Vec::new();
|
||||
let mut encoder = png::Encoder::new(&mut bytes, width, height);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
@@ -364,16 +410,23 @@ mod tests {
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
assert_eq!(file(&path).size().width, width, "{name}");
|
||||
}
|
||||
// A file that changed is decoded again once forgotten.
|
||||
// A file that arrives again unchanged is not decoded again.
|
||||
let path = dir.join("287478770");
|
||||
let decoded = || CACHE.with(|c| c.borrow().len());
|
||||
let before = decoded();
|
||||
std::fs::write(&path, &png).unwrap();
|
||||
reloaded(&path);
|
||||
assert_eq!(decoded(), before, "kept");
|
||||
// One that changed is, once it arrived.
|
||||
let mut wider = Vec::new();
|
||||
let mut encoder = png::Encoder::new(&mut wider, 5, 2);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
encoder.write_header().unwrap().write_image_data(&[90; 40]).unwrap();
|
||||
std::fs::write(&path, wider).unwrap();
|
||||
assert_eq!(file(&path).size().width, 3, "kept until forgotten");
|
||||
forget(&path);
|
||||
assert_eq!(file(&path).size().width, 3, "kept until it arrived");
|
||||
reloaded(&path);
|
||||
assert_eq!(decoded(), before - 1);
|
||||
assert_eq!(file(&path).size().width, 5);
|
||||
// A file that is no picture is remembered as such until forgotten,
|
||||
// not read again on every refresh.
|
||||
@@ -382,7 +435,7 @@ mod tests {
|
||||
assert_eq!(file(&junk).size().width, 0);
|
||||
std::fs::write(&junk, &png).unwrap();
|
||||
assert_eq!(file(&junk).size().width, 0, "remembered");
|
||||
forget(&junk);
|
||||
reloaded(&junk);
|
||||
assert_eq!(file(&junk).size().width, 3);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
+11
-8
@@ -117,14 +117,17 @@ port, the service name says whether it speaks TLS:
|
||||
| `_tsgw._tcp.<name> SRV <prio> <weight> <port> <host>` | `ws://<host>:<port>/v1` (plain, e.g. tsgw itself on 7788) |
|
||||
| `_tsgws._tcp.<name> TXT "path=/<path>"` (optional, same for `_tsgw`) | another path than `/v1`, e.g. behind a reverse proxy |
|
||||
|
||||
The order: the most specific name first; at a name `_tsgws` before
|
||||
`_tsgw`; among several records of one name the lowest priority first;
|
||||
then tsgw's own answer (below), but only when a plain record or nothing is
|
||||
published, so a server that publishes only TLS is never reached without
|
||||
it. A TLS proxy that fails (no rule for the host, no certificate) thus
|
||||
falls back to a published plain gateway. A target of `.` means "no gateway
|
||||
here" and the search goes on at the parent domain. Examples (zone of
|
||||
`example.org`):
|
||||
Which gateways: those of the most specific name that publishes a record,
|
||||
and only those (a parent domain's records are another server's gateway
|
||||
when the host publishes its own). At that name `_tsgws` before `_tsgw`,
|
||||
among several records of one kind the lowest priority first, then tsgw's
|
||||
own answer at that name (below), but only when a plain record is published
|
||||
there, so a server that publishes only TLS is never reached without it. A
|
||||
TLS proxy that fails (no rule for the host, no certificate) thus falls
|
||||
back to the plain gateway published next to it. With no record at any
|
||||
name, tsgw's own answer at the most specific name that gives one. A target
|
||||
of `.` means "no gateway here" and the search goes on at the parent
|
||||
domain. Examples (zone of `example.org`):
|
||||
|
||||
```dns
|
||||
; Behind a TLS proxy at gw.example.org that forwards /tsgw/v1 to tsgw:
|
||||
|
||||
@@ -461,7 +461,11 @@ impl Runner<'_> {
|
||||
{
|
||||
let data = std::fs::read(&path)?;
|
||||
let actual = format!("{:x}", md5_of(&data));
|
||||
if actual != hash {
|
||||
// A server avatar is named by its MD5; a myTeamSpeak
|
||||
// avatar by its address.
|
||||
let server_avatar =
|
||||
hash.len() == 32 && hash.bytes().all(|b| b.is_ascii_hexdigit());
|
||||
if server_avatar && actual != hash {
|
||||
bail!("avatar file hash {actual} is not the announced {hash}");
|
||||
}
|
||||
if let Some(md5) = md5
|
||||
|
||||
@@ -99,7 +99,7 @@ pub async fn run(args: GatewayArgs) -> Result<()> {
|
||||
}
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: SESSION,
|
||||
url: args.url.clone(),
|
||||
urls: vec![args.url.clone()],
|
||||
identity: Box::new(identity.clone()),
|
||||
});
|
||||
if let Some(addr) = &args.voice {
|
||||
|
||||
Reference in new issue
Block a user