1use std::sync::Arc;
53use std::sync::atomic::{AtomicUsize, Ordering};
54use std::time::Duration;
55
56use base64::Engine;
57use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
58use futures_util::StreamExt;
59use futures_util::future::join_all;
60use nostr_sdk::prelude::{Event, EventBuilder, Kind, Tag, Timestamp, Url};
61use reqwest::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE};
62use reqwest::{Method, Response, StatusCode};
63use serde::Deserialize;
64use sha2::{Digest, Sha256};
65
66use crate::media::Media;
67
68const SERVER_TAG: &str = "server";
71
72const IMETA_TAG: &str = "imeta";
75
76const AUTH_SECONDS: u64 = 60 * 60;
79
80const UPLOAD_TIMEOUT: Duration = Duration::from_secs(AUTH_SECONDS);
83const MIRROR_TIMEOUT: Duration = Duration::from_secs(120);
84
85const PIECE: usize = 64 * 1024;
88
89const MAX_ANSWER: usize = 64 * 1024;
92
93const MAX_REASON: usize = 300;
95
96const NOT_ASKED_THAT: [StatusCode; 3] = [StatusCode::NOT_FOUND, StatusCode::METHOD_NOT_ALLOWED, StatusCode::NOT_IMPLEMENTED];
100
101const NOT_READ: [StatusCode; 2] = [StatusCode::BAD_REQUEST, StatusCode::UNAUTHORIZED];
104
105pub type Sent = Arc<AtomicUsize>;
108
109pub fn typed_server(typed: &str) -> Option<Url> {
114 let typed = typed.trim();
115 if typed.is_empty() || typed.contains(char::is_whitespace) {
116 return None;
117 }
118 let url = if typed.contains("://") { Url::parse(typed) } else { Url::parse(&format!("https://{typed}")) }.ok()?;
119 server_of(&url)
120}
121
122fn server_of(url: &Url) -> Option<Url> {
124 if url.scheme() != "https" || url.host_str().is_none_or(|host| !host.contains('.')) {
125 return None;
126 }
127 Url::parse(&url.origin().ascii_serialization()).ok()
128}
129
130pub fn server_name(server: &Url) -> String {
132 let name = server.as_str().trim_end_matches('/');
133 name.strip_prefix("https://").unwrap_or(name).to_string()
134}
135
136fn endpoint(server: &Url, path: &str) -> String {
138 format!("{}/{path}", server.origin().ascii_serialization())
139}
140
141fn names_server(tag: &Tag) -> bool {
143 tag.as_slice().first().is_some_and(|name| name == SERVER_TAG)
144}
145
146pub fn servers(list: Option<&Event>) -> Vec<Url> {
149 let mut servers = Vec::new();
150 let named = list.into_iter().flat_map(|list| list.tags.iter()).filter(|tag| names_server(tag));
151 for server in named.filter_map(|tag| Url::parse(tag.as_slice().get(1)?).ok()).filter_map(|url| server_of(&url)) {
152 if !servers.contains(&server) {
153 servers.push(server);
154 }
155 }
156 servers
157}
158
159pub fn server_list(earlier: Option<&Event>, servers_now: &[Url], now: Timestamp) -> Option<EventBuilder> {
166 if earlier.is_some() && servers(earlier) == servers_now {
167 return None;
168 }
169 let kept = earlier.into_iter().flat_map(|earlier| earlier.tags.iter()).filter(|tag| !names_server(tag)).cloned();
170 let named = servers_now.iter().filter_map(|server| Tag::parse([SERVER_TAG, server.as_str().trim_end_matches('/')]).ok());
171 let tags: Vec<Tag> = named.chain(kept).collect();
172 let content = earlier.map(|earlier| earlier.content.clone()).unwrap_or_default();
173 let after = earlier.map_or(now, |earlier| now.max(Timestamp::from_secs(earlier.created_at.as_secs() + 1)));
175 Some(EventBuilder::new(Kind::BlossomServerList, content).tags(tags).custom_created_at(after))
176}
177
178pub fn hash_of(bytes: &[u8]) -> String {
181 Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect()
182}
183
184pub fn upload_auth(name: &str, hash: &str, now: Timestamp) -> EventBuilder {
188 let tags = [Tag::parse(["t", "upload"]).ok(), Tag::parse(["x", hash]).ok(), Some(Tag::expiration(now + AUTH_SECONDS))];
189 EventBuilder::new(Kind::BlossomAuth, format!("Upload {name}")).tags(tags.into_iter().flatten()).custom_created_at(now)
190}
191
192fn authorization(auth: &Event, padded: bool) -> String {
196 let json = auth.as_json();
197 let encoded = if padded { STANDARD.encode(json) } else { URL_SAFE_NO_PAD.encode(json) };
198 format!("Nostr {encoded}")
199}
200
201#[derive(Debug, Clone, PartialEq, Eq)]
203pub enum UploadError {
204 Unreachable(String),
206 Refused { status: u16, reason: String },
208 Unreadable(String),
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct Blob {
216 pub url: String,
218 pub hash: String,
220}
221
222#[derive(Deserialize)]
224struct Descriptor {
225 url: String,
226 sha256: Option<String>,
227}
228
229async fn answer(mut response: Response) -> Vec<u8> {
231 let mut bytes = Vec::new();
232 while let Ok(Some(chunk)) = response.chunk().await {
233 let room = MAX_ANSWER.saturating_sub(bytes.len());
234 bytes.extend_from_slice(chunk.get(..chunk.len().min(room)).unwrap_or_default());
235 if bytes.len() >= MAX_ANSWER {
236 break;
237 }
238 }
239 bytes
240}
241
242async fn refusal(response: Response) -> UploadError {
246 let status = response.status();
247 let header = response.headers().get("x-reason").and_then(|reason| reason.to_str().ok()).map(str::to_string);
248 let reason = match header.filter(|reason| !reason.trim().is_empty()) {
249 Some(reason) => reason,
250 None => {
251 let said = String::from_utf8_lossy(&answer(response).await).trim().to_string();
252 let message = serde_json::from_str::<serde_json::Value>(&said)
253 .ok()
254 .and_then(|json| json.get("message").and_then(|message| message.as_str().map(str::to_string)));
255 message.or_else(|| (!said.is_empty() && !said.starts_with('<')).then_some(said)).unwrap_or_default()
257 }
258 };
259 let reason = if reason.trim().is_empty() { status.canonical_reason().unwrap_or_default().to_string() } else { reason };
260 UploadError::Refused { status: status.as_u16(), reason: reason.trim().chars().take(MAX_REASON).collect() }
261}
262
263fn why(error: &dyn std::error::Error) -> String {
266 let mut said = error.to_string();
267 let mut behind = error.source();
268 while let Some(cause) = behind {
269 let cause_said = cause.to_string();
270 if !said.contains(&cause_said) {
271 said = format!("{said}: {cause_said}");
272 }
273 behind = cause.source();
274 }
275 said
276}
277
278struct Asking<'a> {
282 http: &'a reqwest::Client,
283 auth: &'a Event,
284 padded: bool,
285}
286
287impl Asking<'_> {
288 async fn send(&mut self, request: impl Fn(&reqwest::Client) -> reqwest::RequestBuilder) -> Result<Response, UploadError> {
290 let unreachable = |e: reqwest::Error| UploadError::Unreachable(why(&e.without_url()));
291 let sent = |padded: bool| request(self.http).header(AUTHORIZATION, authorization(self.auth, padded)).send();
292 let response = sent(self.padded).await.map_err(unreachable)?;
293 if self.padded || !NOT_READ.contains(&response.status()) {
294 return Ok(response);
295 }
296 self.padded = true;
297 sent(true).await.map_err(unreachable)
298 }
299}
300
301fn counted(bytes: &Arc<Vec<u8>>, sent: &Sent) -> reqwest::Body {
304 let (bytes, sent) = (bytes.clone(), sent.clone());
305 sent.store(0, Ordering::Relaxed);
306 let pieces = futures_util::stream::iter((0..bytes.len()).step_by(PIECE)).map(move |start| {
307 let end = (start + PIECE).min(bytes.len());
308 sent.store(end, Ordering::Relaxed);
309 Ok::<_, std::io::Error>(bytes.get(start..end).unwrap_or_default().to_vec())
310 });
311 reqwest::Body::wrap_stream(pieces)
312}
313
314pub async fn upload(
319 http: &reqwest::Client,
320 server: &Url,
321 auth: &Event,
322 bytes: &Arc<Vec<u8>>,
323 hash: &str,
324 mime: &str,
325 sent: &Sent,
326) -> Result<Blob, UploadError> {
327 let address = endpoint(server, "upload");
328 let mut asking = Asking { http, auth, padded: false };
329
330 let asked = asking
331 .send(|http| {
332 http.request(Method::HEAD, &address)
333 .header("X-SHA-256", hash)
334 .header("X-Content-Length", bytes.len())
335 .header("X-Content-Type", mime)
336 })
337 .await?;
338 if !asked.status().is_success() && !NOT_ASKED_THAT.contains(&asked.status()) {
339 return Err(refusal(asked).await);
340 }
341
342 let taken = asking
343 .send(|http| {
344 http.put(&address)
345 .timeout(UPLOAD_TIMEOUT)
346 .header(CONTENT_TYPE, mime)
347 .header(CONTENT_LENGTH, bytes.len())
350 .header("X-SHA-256", hash)
351 .body(counted(bytes, sent))
352 })
353 .await?;
354 if !taken.status().is_success() {
355 return Err(refusal(taken).await);
356 }
357 let said = answer(taken).await;
358 let descriptor: Descriptor = serde_json::from_slice(&said).map_err(|e| UploadError::Unreadable(e.to_string()))?;
359 let url = Url::parse(&descriptor.url).ok().filter(|url| matches!(url.scheme(), "https" | "http"));
360 let url = url.ok_or_else(|| UploadError::Unreadable(format!("no address: {}", descriptor.url)))?;
361 let is_hash = |hash: &String| hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit());
364 let kept = descriptor.sha256.map(|hash| hash.to_ascii_lowercase()).filter(is_hash).unwrap_or_else(|| hash.to_string());
365 Ok(Blob { url: url.to_string(), hash: kept })
366}
367
368pub async fn mirror(http: &reqwest::Client, server: &Url, auth: &Event, url: &str) -> Result<(), UploadError> {
371 let address = endpoint(server, "mirror");
372 let body = serde_json::json!({ "url": url }).to_string();
373 let mut asking = Asking { http, auth, padded: false };
374 let fetched = asking
375 .send(|http| http.put(&address).timeout(MIRROR_TIMEOUT).header(CONTENT_TYPE, "application/json").body(body.clone()))
376 .await?;
377 if fetched.status().is_success() { Ok(()) } else { Err(refusal(fetched).await) }
378}
379
380#[derive(Debug, Clone, PartialEq, Eq)]
382pub struct Attachment {
383 pub url: String,
385 pub imeta: Tag,
387 pub server: Url,
389 pub mirrored: Vec<Url>,
391}
392
393pub fn imeta(url: &str, media: &Media, hash: &str) -> Tag {
397 let mut fields =
398 vec![format!("url {url}"), format!("m {}", media.mime), format!("x {hash}"), format!("size {}", media.bytes.len())];
399 fields.extend(media.dim.map(|(width, height)| format!("dim {width}x{height}")));
400 Tag::custom(IMETA_TAG, fields)
401}
402
403pub fn imeta_url(tag: &Tag) -> Option<&str> {
405 let fields = tag.as_slice();
406 if fields.first()? != IMETA_TAG {
407 return None;
408 }
409 fields.iter().skip(1).find_map(|field| field.strip_prefix("url ")).map(str::trim)
410}
411
412pub async fn send(
423 http: &reqwest::Client,
424 servers: &[Url],
425 auth: &Event,
426 media: Media,
427 hash: &str,
428 sent: &Sent,
429) -> Result<Attachment, Vec<(Url, UploadError)>> {
430 let bytes = Arc::new(media.bytes);
431 let mut refused = Vec::new();
432 let mut taken = None;
433 for server in servers {
434 match upload(http, server, auth, &bytes, hash, media.mime, sent).await {
435 Ok(blob) => {
436 taken = Some((server.clone(), blob));
437 break;
438 }
439 Err(e) => {
440 tracing::warn!("{server} did not take {}: {e:?}", media.name);
441 refused.push((server.clone(), e));
442 }
443 }
444 }
445 let Some((server, blob)) = taken else {
446 return Err(refused);
447 };
448 sent.store(bytes.len(), Ordering::Relaxed);
449
450 let others: Vec<&Url> =
451 servers.iter().filter(|other| **other != server && !refused.iter().any(|(tried, _)| tried == *other)).collect();
452 let mut mirrored = Vec::new();
453 if blob.hash == hash {
454 let fetched = join_all(others.iter().map(|other| mirror(http, other, auth, &blob.url))).await;
455 for (other, result) in others.into_iter().zip(fetched) {
456 match result {
457 Ok(()) => mirrored.push(other.clone()),
458 Err(e) => tracing::warn!("{other} did not fetch {}: {e:?}", blob.url),
459 }
460 }
461 } else {
462 tracing::warn!("{server} keeps {} as another file than was sent: {} for {hash}", media.name, blob.hash);
463 }
464 let media = Media { bytes: Arc::unwrap_or_clone(bytes), ..media };
465 Ok(Attachment { imeta: imeta(&blob.url, &media, &blob.hash), url: blob.url, server, mirrored })
466}
467
468#[cfg(test)]
469mod tests {
470 use super::{
471 Attachment, Sent, UploadError, authorization, hash_of, imeta, imeta_url, send, server_list, server_name, servers,
472 typed_server, upload_auth,
473 };
474 use crate::media::Media;
475 use base64::Engine;
476 use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
477 use nostr_sdk::prelude::{Event, EventBuilder, FinalizeEvent, Keys, Kind, Tag, Timestamp, Url};
478 use std::collections::HashMap;
479 use std::sync::atomic::Ordering;
480 use std::sync::{Arc, Mutex};
481 use std::time::Duration;
482 use tokio::io::{AsyncReadExt, AsyncWriteExt};
483 use tokio::net::{TcpListener, TcpStream};
484
485 fn url(server: &str) -> Url {
486 Url::parse(server).unwrap()
487 }
488
489 fn fields(event: &Event) -> Vec<Vec<&str>> {
490 event.tags.iter().map(|tag| tag.as_slice().iter().map(String::as_str).collect()).collect()
491 }
492
493 #[test]
494 fn a_server_is_typed_with_or_without_its_scheme_and_is_the_root_of_its_domain() {
495 let server = url("https://cdn.example.com/");
496 assert_eq!(typed_server("cdn.example.com"), Some(server.clone()));
497 assert_eq!(typed_server(" https://cdn.example.com/ "), Some(server.clone()));
498 assert_eq!(typed_server("https://CDN.example.com/upload?x=1"), Some(server.clone()), "its endpoints are at the root");
499 assert_eq!(typed_server("cdn.example.com:8443"), Some(url("https://cdn.example.com:8443/")));
500 assert_eq!(server_name(&server), "cdn.example.com");
501
502 assert_eq!(typed_server("http://cdn.example.com"), None, "nothing is sent in the clear");
503 assert_eq!(typed_server("wss://relay.example.com"), None);
504 for typed in ["", " ", "two words", "nodots", "https://"] {
505 assert_eq!(typed_server(typed), None, "{typed:?} is no server");
506 }
507 }
508
509 #[test]
510 fn a_server_list_is_written_with_its_servers_in_order_and_the_rest_as_it_was() {
511 let me = Keys::generate();
512 let (first, second, third) =
513 (url("https://one.example.com/"), url("https://two.example.com/"), url("https://three.example.com/"));
514 let now = Timestamp::from_secs(2_000);
515 assert!(servers(None).is_empty());
516
517 let list = server_list(None, std::slice::from_ref(&first), now).unwrap().finalize(&me).unwrap();
519 assert_eq!(list.kind, Kind::BlossomServerList);
520 assert_eq!(fields(&list), [vec!["server", "https://one.example.com"]]);
521 assert_eq!(servers(Some(&list)), [first.clone()]);
522 assert!(server_list(None, &[], now).is_some());
524
525 let theirs = [
528 Tag::parse(["server", "https://one.example.com/"]).unwrap(),
529 Tag::parse(["client", "another"]).unwrap(),
530 Tag::parse(["server", "https://two.example.com"]).unwrap(),
531 Tag::parse(["server", "https://one.example.com"]).unwrap(),
532 Tag::parse(["server", "http://clear.example.com"]).unwrap(),
533 Tag::parse(["server", "not an address"]).unwrap(),
534 ];
535 let earlier =
536 EventBuilder::new(Kind::BlossomServerList, "kept").tags(theirs).custom_created_at(Timestamp::from_secs(5_000));
537 let earlier = earlier.finalize(&me).unwrap();
538 assert_eq!(servers(Some(&earlier)), [first.clone(), second.clone()]);
539 assert!(server_list(Some(&earlier), &[first.clone(), second.clone()], now).is_none(), "it says so already");
540
541 let changed = server_list(Some(&earlier), &[third, second, first], now).unwrap().finalize(&me).unwrap();
542 assert_eq!(
543 fields(&changed),
544 [
545 vec!["server", "https://three.example.com"],
546 vec!["server", "https://two.example.com"],
547 vec!["server", "https://one.example.com"],
548 vec!["client", "another"],
549 ]
550 );
551 assert_eq!(changed.content, "kept");
552 assert_eq!(changed.created_at.as_secs(), 5_001, "it is the newer of the two");
553 }
554
555 #[test]
556 fn an_upload_is_authorized_for_one_file_and_for_a_while() {
557 let me = Keys::generate();
558 let hash = hash_of(b"a file");
559 assert_eq!(hash.len(), 64);
560 assert_eq!(hash_of(b""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
561
562 let auth = upload_auth("holiday.jpg", &hash, Timestamp::from_secs(1_000)).finalize(&me).unwrap();
563 assert_eq!(auth.kind, Kind::BlossomAuth);
564 assert_eq!(auth.content, "Upload holiday.jpg");
565 assert_eq!(auth.created_at.as_secs(), 1_000);
566 assert_eq!(fields(&auth), [vec!["t", "upload"], vec!["x", hash.as_str()], vec!["expiration", "4600"]]);
567
568 let said = authorization(&auth, false);
570 let token = said.strip_prefix("Nostr ").unwrap();
571 assert!(!token.contains(['+', '/', '=']));
572 assert_eq!(Event::from_json(URL_SAFE_NO_PAD.decode(token).unwrap()).unwrap(), auth);
573 let said = authorization(&auth, true);
574 assert_eq!(Event::from_json(STANDARD.decode(said.strip_prefix("Nostr ").unwrap()).unwrap()).unwrap(), auth);
575 }
576
577 fn picture() -> Media {
579 let bytes = (0..200_000u32).map(|nth| (nth % 251) as u8).collect();
580 Media { name: "holiday.png".into(), bytes, mime: "image/png", dim: Some((640, 480)) }
581 }
582
583 #[test]
584 fn a_note_says_of_a_link_what_is_at_it() {
585 let tag = imeta("https://cdn.example.com/abc.png", &picture(), "abc");
586 assert_eq!(
587 tag.as_slice(),
588 ["imeta", "url https://cdn.example.com/abc.png", "m image/png", "x abc", "size 200000", "dim 640x480"]
589 );
590 assert_eq!(imeta_url(&tag), Some("https://cdn.example.com/abc.png"));
591
592 let unmeasured = imeta("https://cdn.example.com/abc.mp4", &Media { mime: "video/mp4", dim: None, ..picture() }, "abc");
593 assert_eq!(unmeasured.as_slice().len(), 5, "what was not measured is not said");
594 assert_eq!(imeta_url(&Tag::parse(["t", "url https://cdn.example.com/abc.png"]).unwrap()), None);
595 assert_eq!(imeta_url(&Tag::parse(["imeta", "m image/png"]).unwrap()), None);
596 }
597
598 #[derive(Debug, Clone)]
600 struct Asked {
601 method: String,
602 path: String,
603 headers: HashMap<String, String>,
604 body: Vec<u8>,
605 }
606
607 #[derive(Debug, Clone, Copy, Default)]
609 struct Manner {
610 refuses: Option<u16>,
612 asked_nothing: bool,
614 reads_the_old_way: bool,
617 changes: bool,
619 }
620
621 struct Server {
623 url: Url,
624 asked: Arc<Mutex<Vec<Asked>>>,
625 }
626
627 impl Server {
628 fn asked(&self) -> Vec<Asked> {
629 self.asked.lock().unwrap().clone()
630 }
631
632 fn requests(&self) -> Vec<String> {
634 self.asked().iter().map(|asked| format!("{} {}", asked.method, asked.path)).collect()
635 }
636 }
637
638 async fn read_request(stream: &mut TcpStream) -> Option<Asked> {
640 let mut buffer = Vec::new();
641 let head_end = loop {
642 if let Some(end) = buffer.windows(4).position(|window| window == b"\r\n\r\n") {
643 break end;
644 }
645 let mut chunk = [0; 16_384];
646 let read = stream.read(&mut chunk).await.ok()?;
647 if read == 0 {
648 return None;
649 }
650 buffer.extend_from_slice(&chunk[..read]);
651 };
652 let head = String::from_utf8_lossy(&buffer[..head_end]).to_string();
653 let mut lines = head.lines();
654 let mut first = lines.next()?.split(' ');
655 let (method, path) = (first.next()?.to_string(), first.next()?.to_string());
656 let headers: HashMap<String, String> = lines
657 .filter_map(|line| line.split_once(':'))
658 .map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_string()))
659 .collect();
660 let length: usize = headers.get("content-length").and_then(|length| length.parse().ok()).unwrap_or(0);
661 let mut body = buffer[head_end + 4..].to_vec();
662 while body.len() < length {
663 let mut chunk = [0; 16_384];
664 let read = stream.read(&mut chunk).await.ok()?;
665 if read == 0 {
666 break;
667 }
668 body.extend_from_slice(&chunk[..read]);
669 }
670 Some(Asked { method, path, headers, body })
671 }
672
673 fn answer_to(manner: Manner, base: &Url, asked: &Asked) -> (u16, Option<&'static str>, String) {
675 let Some(token) = asked.headers.get("authorization").and_then(|said| said.strip_prefix("Nostr ")) else {
676 return (401, Some("no authorization"), String::new());
677 };
678 if manner.reads_the_old_way && STANDARD.decode(token).is_err() {
679 return (401, Some("the authorization could not be read"), String::new());
680 }
681 let descriptor =
682 |hash: &str| format!(r#"{{"url":"{base}{hash}.png","sha256":"{hash}","size":1,"type":"image/png","uploaded":1}}"#);
683 match (asked.method.as_str(), asked.path.as_str(), manner.refuses) {
684 ("HEAD", "/upload", _) if manner.asked_nothing => (404, None, String::new()),
685 ("HEAD", "/upload", Some(status)) => (status, Some("it is too large"), String::new()),
686 ("HEAD", "/upload", None) => (200, None, String::new()),
687 ("PUT", "/upload", Some(status)) => (status, None, r#"{"message":"it is too large, said again"}"#.to_string()),
689 ("PUT", "/upload", None) if asked.headers.contains_key("transfer-encoding") => {
690 (411, Some("no length"), String::new())
691 }
692 ("PUT", "/upload", None) if manner.changes => (201, None, descriptor(&hash_of(b"another file"))),
693 ("PUT", "/upload", None) => (201, None, descriptor(&hash_of(&asked.body))),
694 ("PUT", "/mirror", Some(status)) => (status, Some("it is too large"), String::new()),
695 ("PUT", "/mirror", None) => (200, None, descriptor("mirrored")),
696 _ => (404, None, String::new()),
697 }
698 }
699
700 async fn serve(manner: Manner) -> Server {
702 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
703 let url = url(&format!("http://{}/", listener.local_addr().unwrap()));
704 let asked: Arc<Mutex<Vec<Asked>>> = Arc::default();
705 let (base, log) = (url.clone(), asked.clone());
706 tokio::spawn(async move {
707 while let Ok((mut stream, _)) = listener.accept().await {
708 let Some(request) = read_request(&mut stream).await else {
709 continue;
710 };
711 let (status, reason, body) = answer_to(manner, &base, &request);
712 let body = if request.method == "HEAD" { String::new() } else { body };
713 log.lock().unwrap().push(request);
714 let reason = reason.map(|reason| format!("x-reason: {reason}\r\n")).unwrap_or_default();
715 let head =
716 format!("HTTP/1.1 {status} Said\r\n{reason}content-length: {}\r\nconnection: close\r\n\r\n", body.len());
717 let _ = stream.write_all(format!("{head}{body}").as_bytes()).await;
718 let _ = stream.shutdown().await;
719 }
720 });
721 Server { url, asked }
722 }
723
724 fn plain_http() -> reqwest::Client {
727 let _ = rustls::crypto::ring::default_provider().install_default();
728 reqwest::Client::new()
729 }
730
731 fn sending(media: &Media, manners: &[Manner]) -> (Result<Attachment, Vec<(Url, UploadError)>>, Vec<Server>, Event, usize) {
735 let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
736 runtime.block_on(async {
737 let mut started = Vec::new();
738 for manner in manners {
739 started.push(serve(*manner).await);
740 }
741 let hash = hash_of(&media.bytes);
742 let keys = Keys::generate();
743 let authorizing = |name: &str| upload_auth(name, &hash, Timestamp::now()).finalize(&keys).unwrap();
744 let auth = Some(authorizing(&media.name)).filter(|auth| auth.as_json().len() % 3 != 0);
747 let auth = auth.unwrap_or_else(|| authorizing(&format!("{}.", media.name)));
748 let addresses: Vec<Url> = started.iter().map(|server| server.url.clone()).collect();
749 let http = plain_http();
750 let sent = Sent::default();
751 let sending = send(&http, &addresses, &auth, media.clone(), &hash, &sent);
752 let result = tokio::time::timeout(Duration::from_secs(30), sending).await.unwrap();
753 (result, started, auth, sent.load(Ordering::Relaxed))
754 })
755 }
756
757 #[test]
758 fn a_file_goes_to_the_first_server_and_the_others_fetch_it_from_there() {
759 let media = picture();
760 let hash = hash_of(&media.bytes);
761 let (result, servers, auth, sent) = sending(&media, &[Manner::default(); 3]);
762
763 let attachment = result.unwrap();
764 let address = format!("{}{hash}.png", servers[0].url);
765 assert_eq!(attachment.url, address);
766 assert_eq!(attachment.server, servers[0].url);
767 assert_eq!(attachment.mirrored, [servers[1].url.clone(), servers[2].url.clone()]);
768 assert_eq!(attachment.imeta, imeta(&address, &media, &hash));
769 assert_eq!(sent, media.bytes.len(), "all of it was counted as it went");
770
771 assert_eq!(servers[0].requests(), ["HEAD /upload", "PUT /upload"]);
773 let asked = servers[0].asked();
774 let said = |request: &super::tests::Asked, name: &str| request.headers.get(name).cloned().unwrap_or_default();
775 assert_eq!(said(&asked[0], "x-sha-256"), hash);
776 assert_eq!(said(&asked[0], "x-content-length"), "200000");
777 assert_eq!(said(&asked[0], "x-content-type"), "image/png");
778 assert!(asked[0].body.is_empty());
779 assert_eq!(asked[1].body, media.bytes, "the file arrived as it was");
780 assert_eq!(said(&asked[1], "content-length"), "200000");
781 assert_eq!(said(&asked[1], "content-type"), "image/png");
782 assert_eq!(said(&asked[1], "x-sha-256"), hash);
783 assert!(!asked[1].headers.contains_key("transfer-encoding"));
784 for request in &asked {
786 assert_eq!(said(request, "authorization"), authorization(&auth, false));
787 }
788
789 for other in &servers[1..] {
791 let asked = other.asked();
792 assert_eq!(other.requests(), ["PUT /mirror"]);
793 assert_eq!(String::from_utf8_lossy(&asked[0].body), format!(r#"{{"url":"{address}"}}"#));
794 assert_eq!(said(&asked[0], "content-type"), "application/json");
795 assert_eq!(said(&asked[0], "authorization"), authorization(&auth, false));
796 }
797 }
798
799 #[test]
800 fn a_server_that_would_not_take_a_file_is_not_sent_it_and_the_next_one_is() {
801 let refusing = Manner { refuses: Some(413), ..Manner::default() };
802 let (result, servers, _, _) = sending(&picture(), &[refusing, Manner::default(), Manner::default()]);
803
804 let attachment = result.unwrap();
805 assert_eq!(attachment.server, servers[1].url);
806 assert_eq!(attachment.mirrored, [servers[2].url.clone()]);
807 assert_eq!(servers[0].requests(), ["HEAD /upload"], "it said no to the question, and was asked no more");
808 assert_eq!(servers[1].requests(), ["HEAD /upload", "PUT /upload"]);
809 assert_eq!(servers[2].requests(), ["PUT /mirror"]);
810 }
811
812 #[test]
813 fn a_server_that_does_not_know_the_question_is_sent_the_file() {
814 let unasked = Manner { asked_nothing: true, ..Manner::default() };
815 let (result, servers, _, _) = sending(&picture(), &[unasked]);
816 assert_eq!(result.unwrap().server, servers[0].url);
817 assert_eq!(servers[0].requests(), ["HEAD /upload", "PUT /upload"]);
818
819 let (result, servers, _, _) = sending(&picture(), &[Manner { refuses: Some(402), ..unasked }]);
821 let why = UploadError::Refused { status: 402, reason: "it is too large, said again".into() };
822 assert_eq!(result, Err(vec![(servers[0].url.clone(), why)]));
823 }
824
825 #[test]
826 fn a_server_that_reads_the_authorization_the_old_way_is_asked_again_that_way() {
827 let old = Manner { reads_the_old_way: true, ..Manner::default() };
828 let (result, servers, auth, _) = sending(&picture(), &[old, old]);
829
830 let attachment = result.unwrap();
831 assert_eq!(attachment.mirrored, [servers[1].url.clone()]);
832 assert_eq!(servers[0].requests(), ["HEAD /upload", "HEAD /upload", "PUT /upload"]);
834 let written: Vec<String> = servers[0].asked().iter().map(|asked| asked.headers["authorization"].clone()).collect();
835 assert_eq!(written, [authorization(&auth, false), authorization(&auth, true), authorization(&auth, true)]);
836 assert_eq!(servers[1].requests(), ["PUT /mirror", "PUT /mirror"]);
837 assert_eq!(servers[1].asked()[1].headers["authorization"], authorization(&auth, true));
838 }
839
840 #[test]
841 fn when_no_server_takes_a_file_each_says_why() {
842 let refusing = Manner { refuses: Some(413), ..Manner::default() };
843 let gone = {
845 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
846 url(&format!("http://{}/", listener.local_addr().unwrap()))
847 };
848 let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
849 let (result, there) = runtime.block_on(async {
850 let there = serve(refusing).await;
851 let media = picture();
852 let hash = hash_of(&media.bytes);
853 let auth = upload_auth(&media.name, &hash, Timestamp::now()).finalize(&Keys::generate()).unwrap();
854 let servers = [gone.clone(), there.url.clone()];
855 (send(&plain_http(), &servers, &auth, media, &hash, &Sent::default()).await, there)
856 });
857
858 let refused = result.unwrap_err();
859 assert_eq!(refused.len(), 2);
860 assert!(matches!(&refused[0], (server, UploadError::Unreachable(_)) if *server == gone), "{refused:?}");
861 assert_eq!(refused[1], (there.url.clone(), UploadError::Refused { status: 413, reason: "it is too large".into() }));
862 }
863
864 #[test]
865 fn a_file_the_server_changed_is_another_file_and_no_other_server_is_asked_for_it() {
866 let changing = Manner { changes: true, ..Manner::default() };
867 let media = picture();
868 let (result, servers, _, _) = sending(&media, &[changing, Manner::default()]);
869
870 let attachment = result.unwrap();
871 let kept = hash_of(b"another file");
872 assert_eq!(attachment.imeta, imeta(&attachment.url, &media, &kept), "the note says which file is there");
873 assert!(attachment.mirrored.is_empty());
874 assert!(servers[1].requests().is_empty());
875 }
876}