| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use std::io::SeekFrom; |
| 6 | use std::path::Path; |
| 7 | use std::pin::Pin; |
| 8 | use std::sync::Arc; |
| 9 | use std::task::{Context, Poll}; |
| 10 | use std::time::Duration; |
| 11 | |
| 12 | use bytes::Bytes; |
| 13 | use http_body::Frame; |
| 14 | use tokio::io::{AsyncRead, AsyncSeekExt, AsyncWriteExt, ReadBuf}; |
| 15 | use tokio::sync::oneshot; |
| 16 | use topcoat::{ |
| 17 | Result, |
| 18 | context::{Cx, app_context}, |
| 19 | router::{ |
| 20 | Body, Method, StatusCode, header, path_param, query_params, |
| 21 | content::websocket::{Message, WebSocket, WebSocketUpgrade}, |
| 22 | error::{content_too_large, not_found}, |
| 23 | request::{headers, method}, |
| 24 | response::Response, |
| 25 | route, |
| 26 | }, |
| 27 | }; |
| 28 | |
| 29 | use crate::hub::{Attachment, Detach, Hub}; |
| 30 | use crate::media::{MAX_BYTES, Media, StoreError, content_type, ext_of, part_file, take_bytes, valid_name, valid_session}; |
| 31 | use crate::store::Store; |
| 32 | |
| 33 | |
| 34 | const CHUNK_SIZE: usize = 64 * 1024; |
| 35 | |
| 36 | const MAX_FRAME: usize = 16 << 20; |
| 37 | |
| 38 | const FRAME_WAIT: Duration = Duration::from_secs(5); |
| 39 | |
| 40 | const IMMUTABLE: &str = "public, max-age=31536000, immutable"; |
| 41 | |
| 42 | |
| 43 | #[query_params(error = bad_request)] |
| 44 | pub struct MediaQuery { |
| 45 | |
| 46 | pub name: Option<String>, |
| 47 | } |
| 48 | |
| 49 | |
| 50 | #[query_params(error = bad_request)] |
| 51 | pub struct LiveQuery { |
| 52 | |
| 53 | pub note: Option<String>, |
| 54 | |
| 55 | pub session: Option<String>, |
| 56 | |
| 57 | pub part: Option<String>, |
| 58 | } |
| 59 | |
| 60 | path_param!(file); |
| 61 | path_param!(session); |
| 62 | |
| 63 | |
| 64 | #[route(POST "/media")] |
| 65 | pub async fn upload_media(cx: &Cx, body: Body) -> Result<String> { |
| 66 | let media = app_context::<Arc<Media>>(cx); |
| 67 | let name = query_params::<MediaQuery>(cx)?.name.clone().unwrap_or_default(); |
| 68 | match media.store(&ext_of(&name), body).await { |
| 69 | Ok(file) => Ok(format!("/media/{file}")), |
| 70 | Err(StoreError::TooLarge) => Err(content_too_large().into()), |
| 71 | Err(StoreError::Failed(err)) => Err(topcoat::Error::from_anyhow(err)), |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | |
| 76 | |
| 77 | #[route(GET "/media/{file}")] |
| 78 | pub async fn serve_media(cx: &Cx) -> Result<Response> { |
| 79 | let media = app_context::<Arc<Media>>(cx); |
| 80 | let name = path_param::<File>(cx); |
| 81 | if !valid_name(name) { |
| 82 | return Err(not_found().into()); |
| 83 | } |
| 84 | let Some((_, ext)) = name.split_once('.') else { |
| 85 | return Err(not_found().into()); |
| 86 | }; |
| 87 | file_response(cx, &media.path(name), ext, IMMUTABLE, None).await |
| 88 | } |
| 89 | |
| 90 | |
| 91 | |
| 92 | #[route(GET "/media/rec/{session}")] |
| 93 | pub async fn serve_take(cx: &Cx) -> Result<Response> { |
| 94 | let media = app_context::<Arc<Media>>(cx); |
| 95 | let hub = app_context::<Arc<Hub>>(cx); |
| 96 | let id = path_param::<Session>(cx); |
| 97 | if !valid_session(id) { |
| 98 | return take_missing(); |
| 99 | } |
| 100 | let joined = media |
| 101 | .joined_take(id, &hub.attached(id)) |
| 102 | .await |
| 103 | .map_err(topcoat::Error::from_anyhow)?; |
| 104 | let Some((path, key)) = joined else { |
| 105 | return take_missing(); |
| 106 | }; |
| 107 | let etag = format!("\"{}\"", blake3::hash(key.as_bytes()).to_hex()); |
| 108 | if not_modified(cx, &etag) { |
| 109 | return Ok(Response::builder() |
| 110 | .status(StatusCode::NOT_MODIFIED) |
| 111 | .header(header::CACHE_CONTROL, "no-cache") |
| 112 | .header(header::ETAG, etag) |
| 113 | .body(Body::empty())?); |
| 114 | } |
| 115 | file_response(cx, &path, "weba", "no-cache", Some(&etag)).await |
| 116 | } |
| 117 | |
| 118 | |
| 119 | fn take_missing() -> Result<Response> { |
| 120 | Ok(Response::builder() |
| 121 | .status(StatusCode::NOT_FOUND) |
| 122 | .header(header::CACHE_CONTROL, "no-store") |
| 123 | .header("x-content-type-options", "nosniff") |
| 124 | .header("content-security-policy", "sandbox; default-src 'none'") |
| 125 | .body(Body::empty())?) |
| 126 | } |
| 127 | |
| 128 | |
| 129 | fn not_modified(cx: &Cx, etag: &str) -> bool { |
| 130 | headers(cx) |
| 131 | .get(header::IF_NONE_MATCH) |
| 132 | .and_then(|v| v.to_str().ok()) |
| 133 | .is_some_and(|list| list.split(',').map(str::trim).any(|tag| tag == etag || tag == "*")) |
| 134 | } |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | #[route(GET "/media/live")] |
| 140 | pub async fn recording_socket(cx: &Cx, upgrade: WebSocketUpgrade) -> Result<Response> { |
| 141 | let store = app_context::<Arc<Store>>(cx).clone(); |
| 142 | let hub = app_context::<Arc<Hub>>(cx).clone(); |
| 143 | let media = app_context::<Arc<Media>>(cx).clone(); |
| 144 | let (note, session, part) = { |
| 145 | let query = query_params::<LiveQuery>(cx)?; |
| 146 | (query.note.clone(), query.session.clone(), query.part.clone()) |
| 147 | }; |
| 148 | upgrade |
| 149 | .max_message_size(MAX_FRAME) |
| 150 | .max_frame_size(MAX_FRAME) |
| 151 | .on_upgrade(move |socket| async move { |
| 152 | serve_recording(store, hub, media, note, session, part, socket).await; |
| 153 | }) |
| 154 | } |
| 155 | |
| 156 | |
| 157 | async fn note_exists(store: &Store, note: &str) -> bool { |
| 158 | super::is_note_id(note) && matches!(store.get_note(note).await, Ok(Some(_))) |
| 159 | } |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | async fn recording_target( |
| 165 | store: &Store, |
| 166 | media: &Media, |
| 167 | note: Option<String>, |
| 168 | session: Option<String>, |
| 169 | part: Option<String>, |
| 170 | ) -> Option<(String, String, Option<u32>)> { |
| 171 | if let Some(session) = session { |
| 172 | if !valid_session(&session) { |
| 173 | return None; |
| 174 | } |
| 175 | let note = session.split('.').next()?.to_owned(); |
| 176 | if !note_exists(store, ¬e).await { |
| 177 | return None; |
| 178 | } |
| 179 | let part = part.map(|p| p.parse::<u32>()).transpose().ok()?; |
| 180 | return Some((note, session, part)); |
| 181 | } |
| 182 | let note = note?; |
| 183 | if !note_exists(store, ¬e).await { |
| 184 | return None; |
| 185 | } |
| 186 | let session = media.new_take(¬e).await.ok()?; |
| 187 | Some((note, session, None)) |
| 188 | } |
| 189 | |
| 190 | |
| 191 | async fn serve_recording( |
| 192 | store: Arc<Store>, |
| 193 | hub: Arc<Hub>, |
| 194 | media: Arc<Media>, |
| 195 | note: Option<String>, |
| 196 | session: Option<String>, |
| 197 | part: Option<String>, |
| 198 | mut socket: WebSocket, |
| 199 | ) { |
| 200 | let Some((note, session, part)) = recording_target(&store, &media, note, session, part).await else { |
| 201 | return refuse(socket).await; |
| 202 | }; |
| 203 | let dir = media.take_dir(&session); |
| 204 | let Attachment { part, token, mut stop } = match hub.attach(¬e, &session, part, &dir) { |
| 205 | Ok(Some(attachment)) => attachment, |
| 206 | _ => return refuse(socket).await, |
| 207 | }; |
| 208 | let (mut file, len) = match open_part(&part_file(&dir, part)).await { |
| 209 | Ok(opened) => opened, |
| 210 | Err(err) => { |
| 211 | eprintln!("opening part {part} of take {session} failed: {err:#}"); |
| 212 | hub.detach(¬e, &session, part, token, Detach::Lost); |
| 213 | return refuse(socket).await; |
| 214 | } |
| 215 | }; |
| 216 | if socket.send(Message::text(format!("ready {session} {part} {len}"))).await.is_err() { |
| 217 | hub.detach(¬e, &session, part, token, Detach::Lost); |
| 218 | return; |
| 219 | } |
| 220 | match receive_part(&mut socket, &mut file, &dir, len, &mut stop).await { |
| 221 | Exit::Ended => { |
| 222 | let _ = socket.send(Message::text("done")).await; |
| 223 | hub.detach(¬e, &session, part, token, Detach::Ended); |
| 224 | } |
| 225 | Exit::Refused => { |
| 226 | let _ = socket.send(Message::text("reject")).await; |
| 227 | hub.detach(¬e, &session, part, token, Detach::Lost); |
| 228 | } |
| 229 | |
| 230 | Exit::Lost | Exit::Taken => hub.detach(¬e, &session, part, token, Detach::Lost), |
| 231 | } |
| 232 | let _ = socket.close().await; |
| 233 | } |
| 234 | |
| 235 | |
| 236 | enum Exit { |
| 237 | |
| 238 | Ended, |
| 239 | |
| 240 | Lost, |
| 241 | |
| 242 | Taken, |
| 243 | |
| 244 | Refused, |
| 245 | } |
| 246 | |
| 247 | |
| 248 | async fn refuse(mut socket: WebSocket) { |
| 249 | let _ = socket.send(Message::text("reject")).await; |
| 250 | let _ = socket.close().await; |
| 251 | } |
| 252 | |
| 253 | |
| 254 | async fn open_part(path: &Path) -> std::io::Result<(tokio::fs::File, u64)> { |
| 255 | let file = tokio::fs::OpenOptions::new().write(true).open(path).await?; |
| 256 | let len = file.metadata().await?.len(); |
| 257 | Ok((file, len)) |
| 258 | } |
| 259 | |
| 260 | |
| 261 | |
| 262 | async fn receive_part( |
| 263 | socket: &mut WebSocket, |
| 264 | file: &mut tokio::fs::File, |
| 265 | dir: &Path, |
| 266 | mut len: u64, |
| 267 | stop: &mut oneshot::Receiver<()>, |
| 268 | ) -> Exit { |
| 269 | loop { |
| 270 | let message = tokio::select! { |
| 271 | _ = &mut *stop => return Exit::Taken, |
| 272 | message = tokio::time::timeout(FRAME_WAIT, socket.recv()) => message, |
| 273 | }; |
| 274 | let message = match message { |
| 275 | Ok(Some(Ok(message))) => message, |
| 276 | _ => return Exit::Lost, |
| 277 | }; |
| 278 | match message { |
| 279 | Message::Binary(chunk) => { |
| 280 | if write_chunk(file, dir, len, &chunk).await.is_err() { |
| 281 | return Exit::Refused; |
| 282 | } |
| 283 | len += chunk.len() as u64; |
| 284 | if socket.send(Message::text(format!("ack {len}"))).await.is_err() { |
| 285 | return Exit::Lost; |
| 286 | } |
| 287 | } |
| 288 | Message::Text(text) if text.as_str() == "end" => return Exit::Ended, |
| 289 | Message::Close(_) => return Exit::Lost, |
| 290 | _ => {} |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | |
| 296 | |
| 297 | async fn write_chunk(file: &mut tokio::fs::File, dir: &Path, len: u64, chunk: &[u8]) -> std::io::Result<()> { |
| 298 | if take_bytes(dir)? + chunk.len() as u64 > MAX_BYTES { |
| 299 | return Err(std::io::Error::other("the take is larger than the limit")); |
| 300 | } |
| 301 | let result = write_at(file, len, chunk).await; |
| 302 | if result.is_err() { |
| 303 | let _ = file.set_len(len).await; |
| 304 | } |
| 305 | result |
| 306 | } |
| 307 | |
| 308 | async fn write_at(file: &mut tokio::fs::File, len: u64, chunk: &[u8]) -> std::io::Result<()> { |
| 309 | file.seek(SeekFrom::Start(len)).await?; |
| 310 | file.write_all(chunk).await?; |
| 311 | file.sync_data().await |
| 312 | } |
| 313 | |
| 314 | |
| 315 | |
| 316 | async fn file_response(cx: &Cx, path: &Path, ext: &str, cache: &str, etag: Option<&str>) -> Result<Response> { |
| 317 | let mut file = match tokio::fs::File::open(path).await { |
| 318 | Ok(file) => file, |
| 319 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Err(not_found().into()), |
| 320 | Err(err) => return Err(topcoat::Error::from_anyhow(err.into())), |
| 321 | }; |
| 322 | let meta = file.metadata().await.map_err(|err| topcoat::Error::from_anyhow(err.into()))?; |
| 323 | if !meta.is_file() { |
| 324 | return Err(not_found().into()); |
| 325 | } |
| 326 | let len = meta.len(); |
| 327 | |
| 328 | let (status, start, count, content_range) = match headers(cx).get(header::RANGE).and_then(|v| v.to_str().ok()) { |
| 329 | Some(range) => match span(range, len) { |
| 330 | Span::Whole => (StatusCode::OK, 0, len, None), |
| 331 | Span::Part(start, end) => ( |
| 332 | StatusCode::PARTIAL_CONTENT, |
| 333 | start, |
| 334 | end - start + 1, |
| 335 | Some(format!("bytes {start}-{end}/{len}")), |
| 336 | ), |
| 337 | Span::Unsatisfiable => (StatusCode::RANGE_NOT_SATISFIABLE, 0, 0, Some(format!("bytes */{len}"))), |
| 338 | }, |
| 339 | None => (StatusCode::OK, 0, len, None), |
| 340 | }; |
| 341 | |
| 342 | let (mime, disposition) = match content_type(ext) { |
| 343 | Some(mime) => (mime, "inline"), |
| 344 | None => ("application/octet-stream", "attachment"), |
| 345 | }; |
| 346 | let mut builder = Response::builder() |
| 347 | .status(status) |
| 348 | .header(header::CONTENT_TYPE, mime) |
| 349 | .header(header::CONTENT_LENGTH, count.to_string()) |
| 350 | .header(header::CONTENT_DISPOSITION, disposition) |
| 351 | .header(header::ACCEPT_RANGES, "bytes") |
| 352 | .header(header::CACHE_CONTROL, cache) |
| 353 | .header("x-content-type-options", "nosniff"); |
| 354 | if let Some(etag) = etag { |
| 355 | builder = builder.header(header::ETAG, etag); |
| 356 | } |
| 357 | |
| 358 | if ext != "pdf" { |
| 359 | builder = builder.header("content-security-policy", "sandbox; default-src 'none'"); |
| 360 | } |
| 361 | if let Some(range) = content_range { |
| 362 | builder = builder.header(header::CONTENT_RANGE, range); |
| 363 | } |
| 364 | let body = if count == 0 || method(cx) == Method::HEAD { |
| 365 | Body::empty() |
| 366 | } else { |
| 367 | file.seek(SeekFrom::Start(start)) |
| 368 | .await |
| 369 | .map_err(|err| topcoat::Error::from_anyhow(err.into()))?; |
| 370 | Body::new(FileBody { file, remaining: count }) |
| 371 | }; |
| 372 | Ok(builder.body(body)?) |
| 373 | } |
| 374 | |
| 375 | |
| 376 | #[derive(Debug, PartialEq)] |
| 377 | enum Span { |
| 378 | |
| 379 | Whole, |
| 380 | |
| 381 | Part(u64, u64), |
| 382 | |
| 383 | Unsatisfiable, |
| 384 | } |
| 385 | |
| 386 | |
| 387 | |
| 388 | fn span(value: &str, len: u64) -> Span { |
| 389 | let Some((first, last)) = value.trim().strip_prefix("bytes=").and_then(|s| s.split_once('-')) else { |
| 390 | return Span::Whole; |
| 391 | }; |
| 392 | let (first, last) = (first.trim(), last.trim()); |
| 393 | if first.is_empty() { |
| 394 | |
| 395 | let Ok(n) = last.parse::<u64>() else { return Span::Whole }; |
| 396 | if n == 0 || len == 0 { |
| 397 | return Span::Unsatisfiable; |
| 398 | } |
| 399 | return Span::Part(len.saturating_sub(n), len - 1); |
| 400 | } |
| 401 | let Ok(start) = first.parse::<u64>() else { return Span::Whole }; |
| 402 | if start >= len { |
| 403 | return Span::Unsatisfiable; |
| 404 | } |
| 405 | let end = if last.is_empty() { |
| 406 | len - 1 |
| 407 | } else { |
| 408 | match last.parse::<u64>() { |
| 409 | Ok(end) if end >= start => end.min(len - 1), |
| 410 | _ => return Span::Whole, |
| 411 | } |
| 412 | }; |
| 413 | Span::Part(start, end) |
| 414 | } |
| 415 | |
| 416 | |
| 417 | struct FileBody { |
| 418 | file: tokio::fs::File, |
| 419 | remaining: u64, |
| 420 | } |
| 421 | |
| 422 | impl http_body::Body for FileBody { |
| 423 | type Data = Bytes; |
| 424 | type Error = std::io::Error; |
| 425 | |
| 426 | fn poll_frame(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<std::io::Result<Frame<Bytes>>>> { |
| 427 | let this = self.get_mut(); |
| 428 | if this.remaining == 0 { |
| 429 | return Poll::Ready(None); |
| 430 | } |
| 431 | let want = this.remaining.min(CHUNK_SIZE as u64) as usize; |
| 432 | let mut chunk = vec![0u8; want]; |
| 433 | let mut buf = ReadBuf::new(&mut chunk); |
| 434 | match Pin::new(&mut this.file).poll_read(cx, &mut buf) { |
| 435 | Poll::Pending => Poll::Pending, |
| 436 | Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))), |
| 437 | Poll::Ready(Ok(())) => { |
| 438 | let n = buf.filled().len(); |
| 439 | if n == 0 { |
| 440 | let err = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "media file is shorter than its length"); |
| 441 | return Poll::Ready(Some(Err(err))); |
| 442 | } |
| 443 | chunk.truncate(n); |
| 444 | this.remaining -= n as u64; |
| 445 | Poll::Ready(Some(Ok(Frame::data(Bytes::from(chunk))))) |
| 446 | } |
| 447 | } |
| 448 | } |
| 449 | } |