1use std::path::PathBuf;
5
6use axum::{
7 body::Body,
8 extract::{Path as AxumPath, Query, State},
9 http::{header, HeaderMap, StatusCode},
10 response::{IntoResponse, Json, Response},
11};
12use serde_json::json;
13use tokio::io::{AsyncReadExt, AsyncSeekExt};
14
15use crate::backend::base::expand_home_dir_safe;
16use crate::backend::{docsite, schema};
17
18use super::AppState;
19
20#[derive(serde::Deserialize)]
21pub(super) struct FileQueryParams {
22 zoneid: Option<String>,
23 name: Option<String>,
24 #[serde(default)]
25 offset: i64,
26}
27
28#[derive(serde::Deserialize)]
29pub(super) struct LocalFileQueryParams {
30 path: Option<String>,
31 block_id: Option<String>,
33}
34
35const STREAM_LOCAL_FILE_MAX_BYTES: u64 = 500_000_000;
41
42pub(super) async fn handle_mux_file(
43 State(state): State<AppState>,
44 Query(params): Query<FileQueryParams>,
45) -> Response {
46 let zone_id = match ¶ms.zoneid {
47 Some(z) if !z.is_empty() => z.as_str(),
48 _ => {
49 return (
50 StatusCode::BAD_REQUEST,
51 Json(json!({"error": "missing zoneid"})),
52 )
53 .into_response()
54 }
55 };
56 let name = match ¶ms.name {
57 Some(n) if !n.is_empty() => n.as_str(),
58 _ => {
59 return (
60 StatusCode::BAD_REQUEST,
61 Json(json!({"error": "missing name"})),
62 )
63 .into_response()
64 }
65 };
66
67 let file_info = match state.filestore.stat(zone_id, name) {
69 Ok(Some(info)) => info,
70 Ok(None) => {
71 return (
72 StatusCode::NOT_FOUND,
73 Json(json!({"error": "file not found"})),
74 )
75 .into_response()
76 }
77 Err(e) => {
78 return (
79 StatusCode::INTERNAL_SERVER_ERROR,
80 Json(json!({"error": e.to_string()})),
81 )
82 .into_response()
83 }
84 };
85
86 let (data_offset, data) = match state.filestore.read_at(zone_id, name, params.offset, 0) {
88 Ok(result) => result,
89 Err(e) => {
90 return (
91 StatusCode::INTERNAL_SERVER_ERROR,
92 Json(json!({"error": e.to_string()})),
93 )
94 .into_response()
95 }
96 };
97
98 let file_info_json = serde_json::to_string(&file_info).unwrap_or_default();
100 let file_info_b64 =
101 base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &file_info_json);
102
103 Response::builder()
104 .status(StatusCode::OK)
105 .header("Content-Type", "application/octet-stream")
106 .header("X-ZoneFileInfo", file_info_b64)
107 .header("X-ZoneFileOffset", data_offset.to_string())
110 .body(Body::from(data))
111 .unwrap_or_else(|_| {
112 (
113 StatusCode::INTERNAL_SERVER_ERROR,
114 "failed to build response",
115 )
116 .into_response()
117 })
118}
119
120pub(super) async fn handle_schema(
121 State(state): State<AppState>,
122 AxumPath(path): AxumPath<String>,
123) -> Response {
124 let app_path = if state.app_path.is_empty() {
125 return (
126 StatusCode::NOT_FOUND,
127 Json(json!({"error": "app path not configured"})),
128 )
129 .into_response();
130 } else {
131 PathBuf::from(&state.app_path)
132 };
133
134 let schema_dir = schema::get_schema_dir(&app_path);
135 let name = match schema::normalize_schema_request(&path) {
136 Some(n) => n,
137 None => {
138 return (
139 StatusCode::BAD_REQUEST,
140 Json(json!({"error": "invalid schema path"})),
141 )
142 .into_response()
143 }
144 };
145
146 match schema::resolve_schema_path(&schema_dir, &name) {
147 Some(file_path) => match std::fs::read(&file_path) {
148 Ok(data) => Response::builder()
149 .status(StatusCode::OK)
150 .header("Content-Type", schema::SCHEMA_CONTENT_TYPE)
151 .body(Body::from(data))
152 .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()),
153 Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
154 },
155 None => StatusCode::NOT_FOUND.into_response(),
156 }
157}
158
159pub(super) async fn handle_docsite(AxumPath(path): AxumPath<String>) -> Response {
160 match docsite::resolve_docsite_path(&path) {
161 Some(file_path) => {
162 let content_type = mime_from_path(&file_path);
163 match std::fs::read(&file_path) {
164 Ok(data) => Response::builder()
165 .status(StatusCode::OK)
166 .header("Content-Type", content_type)
167 .body(Body::from(data))
168 .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()),
169 Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
170 }
171 }
172 None => StatusCode::NOT_FOUND.into_response(),
173 }
174}
175
176fn mime_from_path(path: &std::path::Path) -> &'static str {
177 match path.extension().and_then(|e| e.to_str()).map(|e| e.to_lowercase()).as_deref() {
178 Some("html") => "text/html; charset=utf-8",
179 Some("css") => "text/css; charset=utf-8",
180 Some("js") => "application/javascript; charset=utf-8",
181 Some("json") => "application/json; charset=utf-8",
182 Some("png") => "image/png",
183 Some("jpg") | Some("jpeg") => "image/jpeg",
184 Some("svg") => "image/svg+xml",
185 Some("gif") => "image/gif",
186 Some("webp") => "image/webp",
187 Some("webm") => "video/webm",
188 Some("mp4") => "video/mp4",
189 Some("mov") => "video/quicktime",
190 Some("wav") => "audio/wav",
191 Some("woff2") => "font/woff2",
192 Some("woff") => "font/woff",
193 Some("avif") => "image/avif",
195 Some("apng") => "image/apng",
196 Some("bmp") => "image/bmp",
197 Some("ico") => "image/x-icon",
198 Some("pdf") => "application/pdf",
199 Some("mp3") => "audio/mpeg",
200 Some("ogg") | Some("oga") | Some("opus") => "audio/ogg",
201 Some("flac") => "audio/flac",
202 Some("m4a") => "audio/mp4",
203 Some("aac") => "audio/aac",
204 Some("m4v") => "video/mp4",
205 Some("mjs") => "application/javascript; charset=utf-8",
206 Some("wasm") => "application/wasm",
207 _ => "application/octet-stream",
208 }
209}
210
211pub(super) async fn handle_stream_local_file(
224 State(state): State<AppState>,
225 Query(params): Query<LocalFileQueryParams>,
226 headers: HeaderMap,
227) -> Response {
228 let raw_path = match ¶ms.path {
229 Some(p) if !p.is_empty() => p.as_str(),
230 _ => {
231 return (
232 StatusCode::BAD_REQUEST,
233 Json(json!({"error": "missing path"})),
234 )
235 .into_response()
236 }
237 };
238
239 let (path_buf, opened) = match local_file_source(&state, params.block_id.as_deref(), raw_path).await {
240 Ok(source) => source,
241 Err(refused) => return refused,
242 };
243 let path = path_buf.as_path();
244
245 let metadata = match &opened {
252 Some(file) => file.metadata(),
253 None => tokio::fs::metadata(path).await,
254 };
255 let metadata = match metadata {
256 Ok(m) => m,
257 Err(e) => return failed(StatusCode::NOT_FOUND, e),
258 };
259 if !metadata.is_file() {
260 return (
261 StatusCode::BAD_REQUEST,
262 Json(json!({"error": "stream-local-file: not a file"})),
263 )
264 .into_response();
265 }
266
267 let total = metadata.len();
268 let range = headers
269 .get(header::RANGE)
270 .and_then(|v| v.to_str().ok())
271 .map_or(ByteRange::Full, |h| parse_byte_range(h, total));
272 if bytes_asked(&range, total) > STREAM_LOCAL_FILE_MAX_BYTES {
275 return too_much_at_once();
276 }
277 if range == ByteRange::Unsatisfiable {
278 return Response::builder()
279 .status(StatusCode::RANGE_NOT_SATISFIABLE)
280 .header(header::CONTENT_RANGE, format!("bytes */{total}"))
281 .header(header::ACCEPT_RANGES, "bytes")
282 .body(Body::empty())
283 .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response());
284 }
285
286 let mut file = match opened {
287 Some(file) => tokio::fs::File::from_std(file),
288 None => match tokio::fs::File::open(path).await {
289 Ok(f) => f,
290 Err(e) => return failed(StatusCode::INTERNAL_SERVER_ERROR, e),
291 },
292 };
293 let builder = Response::builder()
294 .header(header::CONTENT_TYPE, mime_from_path(path))
295 .header(header::ACCEPT_RANGES, "bytes");
296 let response = match range {
297 ByteRange::Partial(start, end) => {
301 if let Err(e) = file.seek(std::io::SeekFrom::Start(start)).await {
302 return failed(StatusCode::INTERNAL_SERVER_ERROR, e);
303 }
304 let len = end - start + 1;
305 builder
306 .status(StatusCode::PARTIAL_CONTENT)
307 .header(header::CONTENT_RANGE, format!("bytes {start}-{end}/{total}"))
308 .header(header::CONTENT_LENGTH, len.to_string())
309 .body(Body::from_stream(tokio_util::io::ReaderStream::new(file.take(len))))
310 }
311 _ => builder
312 .status(StatusCode::OK)
313 .header(header::CONTENT_LENGTH, total.to_string())
314 .body(Body::from_stream(tokio_util::io::ReaderStream::new(file))),
315 };
316 response.unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
317}
318
319fn failed(status: StatusCode, e: impl std::fmt::Display) -> Response {
320 (status, Json(json!({"error": format!("stream-local-file: {e}")}))).into_response()
321}
322
323async fn local_file_source(
327 state: &AppState,
328 block_id: Option<&str>,
329 raw_path: &str,
330) -> Result<(PathBuf, Option<std::fs::File>), Response> {
331 if let Some(meta) = block_id.and_then(|b| super::agent_media_files::pane_meta(state, b)) {
332 let asked = raw_path.to_string();
333 return match tokio::task::spawn_blocking(move || super::agent_media_files::open(&meta, &asked)).await {
334 Ok(Ok((file, found))) => Ok((found.file, Some(file))),
335 Ok(Err(message)) => Err((StatusCode::FORBIDDEN, Json(json!({"error": message}))).into_response()),
336 Err(e) => Err(failed(StatusCode::INTERNAL_SERVER_ERROR, e)),
337 };
338 }
339 match super::files_root::bound_path(state, block_id, raw_path).await {
340 Ok(bound) => Ok((expand_home_dir_safe(&bound), None)),
341 Err(message) => Err((StatusCode::FORBIDDEN, Json(json!({"error": message}))).into_response()),
342 }
343}
344
345#[derive(Debug, PartialEq, Eq)]
347pub(super) enum ByteRange {
348 Full,
350 Partial(u64, u64),
352 Unsatisfiable,
354}
355
356fn too_much_at_once() -> Response {
358 (
359 StatusCode::PAYLOAD_TOO_LARGE,
360 Json(json!({"error": "stream-local-file: more than 500 MB asked for at once; ask for a part of the file with a Range"})),
361 )
362 .into_response()
363}
364
365pub(super) fn bytes_asked(range: &ByteRange, total: u64) -> u64 {
367 match range {
368 ByteRange::Partial(start, end) => end - start + 1,
369 ByteRange::Full => total,
370 ByteRange::Unsatisfiable => 0,
371 }
372}
373
374pub(super) fn parse_byte_range(header: &str, total: u64) -> ByteRange {
379 let Some(spec) = header.trim().strip_prefix("bytes=") else {
380 return ByteRange::Full;
381 };
382 if spec.contains(',') {
383 return ByteRange::Full;
384 }
385 let Some((a, b)) = spec.split_once('-') else {
386 return ByteRange::Full;
387 };
388 let (a, b) = (a.trim(), b.trim());
389 if a.is_empty() {
390 let Ok(n) = b.parse::<u64>() else {
391 return ByteRange::Full;
392 };
393 if n == 0 || total == 0 {
394 return ByteRange::Unsatisfiable;
395 }
396 return ByteRange::Partial(total.saturating_sub(n), total - 1);
397 }
398 let Ok(start) = a.parse::<u64>() else {
399 return ByteRange::Full;
400 };
401 let end = if b.is_empty() {
402 None
403 } else {
404 match b.parse::<u64>() {
405 Ok(e) if e >= start => Some(e),
406 _ => return ByteRange::Full,
407 }
408 };
409 if start >= total {
410 return ByteRange::Unsatisfiable;
411 }
412 ByteRange::Partial(start, end.map_or(total - 1, |e| e.min(total - 1)))
413}
414
415#[cfg(test)]
416mod stream_local_file_range_tests {
417 use super::*;
418 use axum::http::{header, HeaderMap, HeaderValue};
419
420 #[test]
423 fn a_closed_range_is_partial() {
424 assert_eq!(parse_byte_range("bytes=0-99", 1000), ByteRange::Partial(0, 99));
425 assert_eq!(parse_byte_range("bytes=100-199", 1000), ByteRange::Partial(100, 199));
426 }
427
428 #[test]
429 fn an_end_past_the_file_is_clamped() {
430 assert_eq!(parse_byte_range("bytes=900-5000", 1000), ByteRange::Partial(900, 999));
431 }
432
433 #[test]
434 fn an_open_range_runs_to_the_end() {
435 assert_eq!(parse_byte_range("bytes=500-", 1000), ByteRange::Partial(500, 999));
436 }
437
438 #[test]
439 fn a_suffix_range_is_the_last_n_bytes() {
440 assert_eq!(parse_byte_range("bytes=-100", 1000), ByteRange::Partial(900, 999));
441 assert_eq!(parse_byte_range("bytes=-5000", 1000), ByteRange::Partial(0, 999));
442 }
443
444 #[test]
445 fn a_start_past_the_end_is_unsatisfiable() {
446 assert_eq!(parse_byte_range("bytes=1000-", 1000), ByteRange::Unsatisfiable);
447 assert_eq!(parse_byte_range("bytes=0-0", 0), ByteRange::Unsatisfiable);
448 assert_eq!(parse_byte_range("bytes=-0", 1000), ByteRange::Unsatisfiable);
449 }
450
451 #[test]
452 fn anything_else_serves_the_whole_file() {
453 for h in ["bytes=5-2", "bytes=abc-", "items=0-1", "bytes=0-1,5-9", "bytes=-", ""] {
454 assert_eq!(parse_byte_range(h, 1000), ByteRange::Full, "{h:?}");
455 }
456 }
457
458 #[test]
463 fn the_cap_counts_the_bytes_asked_for_not_the_file() {
464 let big = STREAM_LOCAL_FILE_MAX_BYTES * 8;
465 assert_eq!(bytes_asked(&parse_byte_range("bytes=0-65535", big), big), 65536);
466 assert_eq!(bytes_asked(&parse_byte_range("bytes=-16", big), big), 16);
467 assert!(bytes_asked(&ByteRange::Full, big) > STREAM_LOCAL_FILE_MAX_BYTES);
468 assert!(bytes_asked(&parse_byte_range("bytes=0-", big), big) > STREAM_LOCAL_FILE_MAX_BYTES);
469 assert_eq!(bytes_asked(&ByteRange::Unsatisfiable, big), 0);
470 assert_eq!(bytes_asked(&ByteRange::Full, 10), 10);
471 }
472
473 fn file_with(bytes: &[u8]) -> tempfile::NamedTempFile {
476 let f = tempfile::Builder::new().suffix(".webm").tempfile().unwrap();
477 std::fs::write(f.path(), bytes).unwrap();
478 f
479 }
480
481 async fn get(path: &std::path::Path, range: Option<&str>) -> (StatusCode, HeaderMap, Vec<u8>) {
482 let mut headers = HeaderMap::new();
483 if let Some(r) = range {
484 headers.insert(header::RANGE, HeaderValue::from_str(r).unwrap());
485 }
486 let params = LocalFileQueryParams { path: Some(path.to_string_lossy().into_owned()), block_id: None };
487 let resp = handle_stream_local_file(State(crate::server::tests::test_state()), Query(params), headers).await;
488 let status = resp.status();
489 let hdrs = resp.headers().clone();
490 let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap().to_vec();
491 (status, hdrs, body)
492 }
493
494 #[tokio::test]
496 async fn a_confined_pane_is_served_only_files_inside_its_folder() {
497 let top = tempfile::tempdir().unwrap();
498 let (root, outside) = (top.path().join("ws"), top.path().join("private"));
499 std::fs::create_dir_all(&root).unwrap();
500 std::fs::create_dir_all(&outside).unwrap();
501 std::fs::write(root.join("a.txt"), "inside").unwrap();
502 std::fs::write(outside.join("b.txt"), "outside").unwrap();
503 let state = crate::server::tests::test_state();
504 let mut meta = crate::backend::obj::MetaMapType::default();
505 meta.insert(crate::server::files_root::FILES_ROOT_META_KEY.into(), root.to_string_lossy().into_owned().into());
506 let mut block = crate::backend::obj::Block { oid: "confined".into(), meta, ..Default::default() };
507 state.mstore.insert(&mut block).unwrap();
508 let ask = |file: std::path::PathBuf, block_id: Option<&str>| {
509 let params = LocalFileQueryParams {
510 path: Some(file.to_string_lossy().into_owned()),
511 block_id: block_id.map(str::to_string),
512 };
513 handle_stream_local_file(State(state.clone()), Query(params), HeaderMap::new())
514 };
515 assert_eq!(ask(root.join("a.txt"), Some("confined")).await.status(), StatusCode::OK);
516 assert_eq!(ask(outside.join("b.txt"), Some("confined")).await.status(), StatusCode::FORBIDDEN);
517 assert_eq!(ask(outside.join("b.txt"), None).await.status(), StatusCode::OK);
518 }
519
520 #[tokio::test]
523 async fn a_container_agents_message_is_served_only_files_of_its_own_folders() {
524 let top = tempfile::tempdir().unwrap();
525 let (ws, private) = (top.path().join("ws"), top.path().join("private"));
526 std::fs::create_dir_all(ws.join("img")).unwrap();
527 std::fs::create_dir_all(&private).unwrap();
528 std::fs::write(ws.join("img").join("a.png"), "the agent's picture").unwrap();
529 std::fs::write(private.join("photo.png"), "the person's photo").unwrap();
530 let state = crate::server::tests::test_state();
531 let pane = |oid: &str, mode: &str| {
532 let mut meta = crate::backend::obj::MetaMapType::default();
533 meta.insert("agentMode".into(), mode.into());
534 meta.insert(crate::backend::blockcontroller::META_KEY_CMD_CWD.into(), ws.to_string_lossy().into_owned().into());
535 let mut block = crate::backend::obj::Block { oid: oid.into(), meta, ..Default::default() };
536 state.mstore.insert(&mut block).unwrap();
537 };
538 pane("container-pane", "container");
539 pane("native-pane", "host");
540 let ask = |path: String, block_id: Option<&str>, range: Option<&str>| {
541 let params = LocalFileQueryParams { path: Some(path), block_id: block_id.map(str::to_string) };
542 let mut headers = HeaderMap::new();
543 if let Some(r) = range {
544 headers.insert(header::RANGE, r.parse().unwrap());
545 }
546 handle_stream_local_file(State(state.clone()), Query(params), headers)
547 };
548 let body = |resp: Response| async move { String::from_utf8(axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap().to_vec()).unwrap() };
549 let host = |p: &std::path::Path| p.to_string_lossy().into_owned();
550
551 for asked in ["/workspace/img/a.png".to_string(), host(&ws.join("img").join("a.png"))] {
553 let resp = ask(asked.clone(), Some("container-pane"), None).await;
554 assert_eq!(resp.status(), StatusCode::OK, "{asked}");
555 assert_eq!(body(resp).await, "the agent's picture");
556 }
557 let part = ask("/workspace/img/a.png".into(), Some("container-pane"), Some("bytes=4-8")).await;
559 assert_eq!(part.status(), StatusCode::PARTIAL_CONTENT);
560 assert_eq!(body(part).await, "agent");
561
562 for asked in [host(&private.join("photo.png")), "/workspace/../private/photo.png".to_string(), "~/photo.png".to_string(), "//host/share/photo.png".to_string(), "C:/Users/me/photo.png".to_string()] {
564 let resp = ask(asked.clone(), Some("container-pane"), None).await;
565 assert_eq!(resp.status(), StatusCode::FORBIDDEN, "{asked}");
566 let text = body(resp).await;
567 assert!(text.contains("isn't in a folder the agent shares") && !text.contains("the person's photo"), "{asked}: {text}");
568 }
569
570 assert_eq!(ask(host(&private.join("photo.png")), Some("native-pane"), None).await.status(), StatusCode::OK);
572 assert_eq!(ask(host(&private.join("photo.png")), None, None).await.status(), StatusCode::OK);
573 }
574
575 #[tokio::test]
576 async fn no_range_serves_the_whole_file_and_advertises_ranges() {
577 let f = file_with(b"0123456789");
578 let (status, h, body) = get(f.path(), None).await;
579 assert_eq!(status, StatusCode::OK);
580 assert_eq!(body, b"0123456789");
581 assert_eq!(h[header::ACCEPT_RANGES], "bytes");
582 assert_eq!(h[header::CONTENT_LENGTH], "10");
583 }
584
585 #[tokio::test]
586 async fn a_range_returns_206_with_just_those_bytes() {
587 let f = file_with(b"0123456789");
588 let (status, h, body) = get(f.path(), Some("bytes=2-5")).await;
589 assert_eq!(status, StatusCode::PARTIAL_CONTENT);
590 assert_eq!(body, b"2345");
591 assert_eq!(h[header::CONTENT_RANGE], "bytes 2-5/10");
592 assert_eq!(h[header::CONTENT_LENGTH], "4");
593 assert_eq!(h[header::CONTENT_TYPE], "video/webm");
594 }
595
596 #[tokio::test]
597 async fn an_unsatisfiable_range_is_416_with_the_size() {
598 let f = file_with(b"0123456789");
599 let (status, h, _) = get(f.path(), Some("bytes=50-")).await;
600 assert_eq!(status, StatusCode::RANGE_NOT_SATISFIABLE);
601 assert_eq!(h[header::CONTENT_RANGE], "bytes */10");
602 }
603}