dav.rs
⎇
Raw
1//! WebDAV endpoint.
2//!
3//! Two mounts, both served by the same [`FbFs`]:
4//!
5//! * `{DAV}` — a signed-in user's roots. Each root is a child collection of a
6//! synthetic top-level directory, so one mount covers every root the user
7//! has.
8//! * `{DAV_SHARE}/{token}` — one public share, mounted at its own root.
9//!
10//! All filesystem access goes through [`crate::fs`], so a mount inherits the
11//! same containment and the same symlink handling the JSON API has.
12//!
13//! The protocol itself (PROPFIND, the 207 multistatus, `Depth`, `Destination`,
14//! `Overwrite`, conditional headers) is `dav-server`'s job. This module only
15//! authenticates the request, decides which roots it may see, and maps dav
16//! paths onto real ones.
17
18use std::collections::HashMap;
19use std::io::SeekFrom;
20use std::path::{Path, PathBuf};
21use std::sync::{Arc, LazyLock, Mutex, Weak};
22use std::time::{Duration, SystemTime, UNIX_EPOCH};
23
24use api_types::{DAV, DAV_SHARE, Mode};
25use axum::body::Body;
26use axum::extract::State;
27use axum::http::header::{HeaderMap, WWW_AUTHENTICATE};
28use axum::http::{Request, Response, StatusCode};
29use axum::response::IntoResponse;
30use bytes::{Buf, Bytes};
31use dav_server::DavConfig;
32use dav_server::davpath::{DavPath, ParseError};
33use dav_server::fs::{
34 DavDirEntry, DavFile, DavMetaData, FsError, FsFuture, FsResult, FsStream, GuardedFileSystem,
35 OpenOptions, ReadDirMeta,
36};
37use dav_server::ls::{DavLock, DavLockSystem, LsFuture};
38use dav_server::memls::MemLs;
39use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
40
41use crate::api::common::{display_name, session_auth};
42use crate::auth;
43use crate::db::RootRow;
44use crate::error::AppState;
45
46/// The `WWW-Authenticate` realm. Clients show it in their password prompt.
47const REALM: &str = "filebrowser-ng";
48
49// ---------------------------------------------------------------------------
50// Routes
51// ---------------------------------------------------------------------------
52
53/// `{DAV}` and everything under it: the signed-in user's roots.
54///
55/// A browser session cookie is accepted, but the usual caller is a mount
56/// client, which only speaks HTTP Basic.
57pub async fn user(State(state): State<Arc<AppState>>, req: Request<Body>) -> Response<Body> {
58 let (principal, roots) = match authenticate(&state, req.headers()).await {
59 Some(v) => v,
60 None => return challenge(),
61 };
62 // The admin pseudo-root (the whole server root, read-only) is deliberately
63 // not mounted: `session_auth` does not add it, and a mount that silently
64 // contained a second copy of every other root would be confusing.
65 let mount = Mount {
66 roots: Arc::new(root_segments(&state, roots)),
67 flat: false,
68 };
69 serve(state, req, DAV.to_string(), principal, mount).await
70}
71
72/// `{DAV_SHARE}/{token}` and everything under it: one public share.
73///
74/// Folder shares only. A file share has no collection to mount, and its one
75/// file is already a plain `GET` away on the share page.
76pub async fn share(State(state): State<Arc<AppState>>, req: Request<Body>) -> Response<Body> {
77 let Some(token) = share_token(req.uri().path()) else {
78 return StatusCode::NOT_FOUND.into_response();
79 };
80 let row = match state.db.share_by_token(&token).await {
81 Ok(Some(row)) => row,
82 Ok(None) => return StatusCode::NOT_FOUND.into_response(),
83 Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
84 };
85 if row.is_expired() {
86 return StatusCode::GONE.into_response();
87 }
88 if row.is_file {
89 return StatusCode::NOT_FOUND.into_response();
90 }
91 // A protected share takes its password over Basic, with the user name
92 // ignored. There is no account behind a share link to name.
93 if let Some(hash) = row.password_hash.clone() {
94 let Some((_, password)) = auth::basic_credentials(req.headers()) else {
95 return challenge();
96 };
97 let (pw, id, tok) = (password.clone(), row.id, token.clone());
98 let ok = auth::verify_cached(row.id, "", &password, move || async move {
99 // Throttled like `POST /api/share/{token}/unlock`, keyed the same
100 // way, so a mount client is not the cheap way to guess.
101 let delay = auth::login_delay(&tok);
102 if !delay.is_zero() {
103 tokio::time::sleep(delay).await;
104 }
105 let ok = auth::verify_password_async(&pw, &hash).await;
106 auth::record_login(&tok, ok);
107 ok.then_some(id)
108 })
109 .await;
110 if ok.is_none() {
111 return challenge();
112 }
113 }
114 let root = RootRow {
115 id: row.id,
116 path: row.target.clone(),
117 mode: row.mode,
118 };
119 let mount = Mount {
120 roots: Arc::new(vec![(String::new(), root)]),
121 flat: true,
122 };
123 let prefix = format!("{DAV_SHARE}/{token}");
124 serve(state, req, prefix, format!("share-{}", row.id), mount).await
125}
126
127/// Whether the request path still addresses this mount after `dav-server` has
128/// normalized it: percent-decoded, `.` and `..` resolved, slashes merged.
129///
130/// Runs the same two steps as the handler, so it rejects nothing the handler
131/// would accept. The other parse errors (`InvalidPath`, `ForbiddenPath`) are
132/// left to the handler, which answers those with a 4xx of its own.
133fn path_in_mount(path: &str, prefix: &str) -> bool {
134 // `OPTIONS *` has no leading slash. The handler answers it.
135 if !path.starts_with('/') {
136 return true;
137 }
138 !matches!(
139 DavPath::new(path).and_then(|mut p| p.set_prefix(prefix)),
140 Err(ParseError::PrefixMismatch)
141 )
142}
143
144/// The `Destination` header as a URL path, the way `dav-server`'s private
145/// header parser reads it: a path as-is, a full URL (what mount clients send)
146/// reduced to its path. `None` for a missing or unparseable header.
147fn destination_path(headers: &HeaderMap) -> Option<String> {
148 let raw = headers.get("destination")?.to_str().ok()?;
149 if raw.starts_with('/') {
150 return Some(raw.to_string());
151 }
152 raw.parse::<axum::http::Uri>()
153 .ok()
154 .map(|u| u.path().to_string())
155}
156
157/// The token out of the *raw* URL path.
158///
159/// Not axum's decoded wildcard: `DavPath` keeps the raw path, and
160/// `strip_prefix` byte-compares against it. A decoded `<token>%2Fx` would
161/// yield a prefix that the dav path does not start with.
162fn share_token(path: &str) -> Option<String> {
163 let rest = path.strip_prefix(DAV_SHARE)?.strip_prefix('/')?;
164 let token = rest.split('/').next().unwrap_or_default();
165 (!token.is_empty()).then(|| token.to_string())
166}
167
168/// Hand the request to `dav-server` and, afterwards, keep the share table in
169/// step with the filesystem.
170///
171/// The handler is built here rather than once at startup because `prefix`
172/// differs per share mount, and `dav-server` only allows a per-request config
173/// override on the unguarded handler. Building it is cheap: an `Arc::new` and
174/// two `Arc`-backed trait-object clones.
175async fn serve(
176 state: Arc<AppState>,
177 req: Request<Body>,
178 prefix: String,
179 principal: String,
180 mount: Mount,
181) -> Response<Body> {
182 // `dav-server` refuses an escaping path too, but with `502 Bad Gateway`
183 // (`DavError::IllegalPath`), which reads as a broken upstream. A `..` that
184 // stays inside the mount is already a `403`, so answer this the same way.
185 // The same for a COPY or MOVE `Destination`, which the handler normalizes
186 // the same way. A missing or malformed header stays with the handler.
187 let dest_in_mount =
188 destination_path(req.headers()).is_none_or(|dest| path_in_mount(&dest, &prefix));
189 if !path_in_mount(req.uri().path(), &prefix) || !dest_in_mount {
190 return StatusCode::FORBIDDEN.into_response();
191 }
192
193 // Resolved *before* the operation, while the item still exists: once
194 // DELETE or MOVE has run there is no path left to look a share up by.
195 let vacating = matches!(req.method().as_str(), "DELETE" | "MOVE");
196 let vacated = if vacating {
197 dav_target(&state, &mount, &prefix, &req)
198 } else {
199 None
200 };
201
202 let handler = DavConfig::<Mount>::new()
203 .filesystem(Box::new(FbFs {
204 state: state.clone(),
205 }))
206 // The handler is rebuilt per request, the lock tree must not be.
207 .locksystem(Box::new(locks_for(&principal)))
208 // Its only effect in `dav-server` is picking the `ReadDirMeta` for
209 // PROPFIND. `false` keeps listings on the followed metadata.
210 .hide_symlinks(false)
211 // Off by default in `dav-server`: without it a plain `GET` of any
212 // collection answers 405, so the mount is unreadable in a browser.
213 .autoindex(true)
214 .strip_prefix(prefix)
215 .build_handler();
216
217 let mut resp = handler.handle_guarded(req, principal, mount).await;
218 crate::api::sandbox_scriptable(&mut resp);
219
220 // One revoke for the whole request. Doing it inside the filesystem would
221 // fire a query per removed item, and a recursive DELETE walks the tree.
222 if let Some(abs) = vacated
223 && resp.status().is_success()
224 {
225 crate::api::files::revoke_shares_at(&state, &abs).await;
226 }
227 resp.map(Body::new)
228}
229
230/// The absolute path a request addresses, if it resolves to one today.
231fn dav_target(
232 state: &AppState,
233 mount: &Mount,
234 prefix: &str,
235 req: &Request<Body>,
236) -> Option<PathBuf> {
237 // `DavPath::new`, not `from_uri`: the latter keeps the raw bytes, so an
238 // encoded path (`a%20b.txt`) would never resolve and the share would
239 // outlive the file it named.
240 let mut path = DavPath::new(req.uri().path()).ok()?;
241 path.set_prefix(prefix).ok()?;
242 let (root, rel) = item(&path, mount).ok()?;
243 // `resolve_entry`, matching the operations this is predicting. Following
244 // the last component would name a symlink's target, so deleting a link
245 // would revoke a share on a file that is still there.
246 crate::fs::resolve_entry(&state.root, &root.path, &rel).ok()
247}
248
249/// 401 with the Basic challenge every mount client needs to see before it
250/// will send credentials at all.
251fn challenge() -> Response<Body> {
252 (
253 StatusCode::UNAUTHORIZED,
254 [(WWW_AUTHENTICATE, format!("Basic realm=\"{REALM}\""))],
255 )
256 .into_response()
257}
258
259// ---------------------------------------------------------------------------
260// Authentication
261// ---------------------------------------------------------------------------
262
263/// Resolve the caller to a principal name and the roots they may mount.
264async fn authenticate(state: &AppState, headers: &HeaderMap) -> Option<(String, Vec<RootRow>)> {
265 // A browser hitting the mount already has a session; take it and skip
266 // Argon2 entirely.
267 if auth::parse_session_cookie(headers).is_some()
268 && let Ok((user, roots)) = session_auth(headers, state).await
269 {
270 return Some((user.name, roots));
271 }
272
273 let (name, password) = auth::basic_credentials(headers)?;
274 let id = auth::verify_cached(0, &name, &password, || {
275 let (state, name, password) = (state, name.clone(), password.clone());
276 async move {
277 // The login route's throttle, keyed the same way, so guessing over
278 // WebDAV is no cheaper than guessing over the login form.
279 let delay = auth::login_delay(&name);
280 if !delay.is_zero() {
281 tokio::time::sleep(delay).await;
282 }
283 let user = state.db.verify_password(&name, &password).await.ok()?;
284 auth::record_login(&name, user.is_some());
285 user.map(|u| u.id)
286 }
287 })
288 .await?;
289 let roots = state.db.user_roots(id).await.ok()?;
290 Some((name, roots))
291}
292
293// ---------------------------------------------------------------------------
294// Locking
295// ---------------------------------------------------------------------------
296
297/// One lock tree per principal.
298///
299/// A lock is keyed by DAV URL, and a URL segment is a root's display name, so a
300/// single shared tree lets two users whose roots are both named `Documents`
301/// reach each other's locks. One could block the other, and `PROPFIND` hands
302/// back the holder's lock token, which is enough to release that lock or write
303/// through it.
304///
305/// The cost is that two principals sharing one physical folder do not
306/// coordinate through WebDAV locks. Byte-level safety does not rest on this:
307/// [`WRITE_LOCKS`] keys on the resolved path and covers every writer.
308///
309/// `MemLs` keeps its state in an `Arc`, so a clone shares that principal's
310/// tree. Locks live in memory only, and a restart drops them all, which is
311/// what a client already sees when a lock times out.
312static LOCKS: LazyLock<Mutex<HashMap<String, ExpiringLs>>> =
313 LazyLock::new(|| Mutex::new(HashMap::new()));
314
315fn locks_for(principal: &str) -> ExpiringLs {
316 let mut g = LOCKS.lock().unwrap_or_else(|e| e.into_inner());
317 g.entry(principal.to_string())
318 .or_insert_with(|| ExpiringLs(*MemLs::new()))
319 .clone()
320}
321
322/// Longest lock handed out, and so the longest an abandoned one blocks a file.
323/// A client that still wants the file refreshes; one that crashed does not.
324///
325/// Matches `dav-server`'s own ceiling for an exclusive lock. It caps only the
326/// two cases that arrive here uncapped, both as `None` meaning "never
327/// expires": a LOCK with no `Timeout` header, and a refresh asking for
328/// `Infinite`.
329const LOCK_TIMEOUT: Duration = Duration::from_secs(600);
330
331/// [`MemLs`] with lock expiry actually applied.
332///
333/// `MemLs` records a lock's `timeout_at` and then never looks at it again, and
334/// it honours an infinite timeout request. Left alone, a client that died
335/// holding an exclusive lock would block that file until the process restarts.
336/// Every call here first drops the expired locks covering the path it touches,
337/// and no lock is granted for longer than [`LOCK_TIMEOUT`].
338#[derive(Debug, Clone)]
339struct ExpiringLs(MemLs);
340
341impl ExpiringLs {
342 /// Drop the expired locks on `path` and its ancestors.
343 ///
344 /// Only the locks that could block an operation *on this path*. A lock on
345 /// a descendant is not swept, so a deep operation can still be refused by
346 /// a stale lock below it until something touches that path directly.
347 async fn sweep(&self, path: &DavPath) {
348 let now = SystemTime::now();
349 for lock in self.0.discover(path).await {
350 if lock.timeout_at.is_some_and(|t| t <= now) {
351 let _ = self.0.unlock(&lock.path, &lock.token).await;
352 }
353 }
354 }
355
356 /// Never `None`, never longer than [`LOCK_TIMEOUT`]. `None` would mean a
357 /// lock that [`sweep`](Self::sweep) can never clear.
358 fn capped(timeout: Option<Duration>) -> Option<Duration> {
359 Some(timeout.unwrap_or(LOCK_TIMEOUT).min(LOCK_TIMEOUT))
360 }
361}
362
363impl DavLockSystem for ExpiringLs {
364 fn lock(
365 &self,
366 path: &DavPath,
367 principal: Option<&str>,
368 owner: Option<&xmltree::Element>,
369 timeout: Option<Duration>,
370 shared: bool,
371 deep: bool,
372 ) -> LsFuture<'_, Result<DavLock, DavLock>> {
373 // The borrows end with the call, not with the future, so clone into it.
374 let (path, principal) = (path.clone(), principal.map(str::to_string));
375 let owner = owner.cloned();
376 Box::pin(async move {
377 self.sweep(&path).await;
378 self.0
379 .lock(
380 &path,
381 principal.as_deref(),
382 owner.as_ref(),
383 Self::capped(timeout),
384 shared,
385 deep,
386 )
387 .await
388 })
389 }
390
391 fn unlock(&self, path: &DavPath, token: &str) -> LsFuture<'_, Result<(), ()>> {
392 let (path, token) = (path.clone(), token.to_string());
393 Box::pin(async move { self.0.unlock(&path, &token).await })
394 }
395
396 fn refresh(
397 &self,
398 path: &DavPath,
399 token: &str,
400 timeout: Option<Duration>,
401 ) -> LsFuture<'_, Result<DavLock, ()>> {
402 let (path, token) = (path.clone(), token.to_string());
403 Box::pin(async move {
404 // Swept first: a client refreshing a lock it let expire must be
405 // told, not silently handed the file back.
406 self.sweep(&path).await;
407 self.0.refresh(&path, &token, Self::capped(timeout)).await
408 })
409 }
410
411 fn check(
412 &self,
413 path: &DavPath,
414 principal: Option<&str>,
415 ignore_principal: bool,
416 deep: bool,
417 submitted_tokens: &[String],
418 ) -> LsFuture<'_, Result<(), DavLock>> {
419 let (path, principal) = (path.clone(), principal.map(str::to_string));
420 let tokens = submitted_tokens.to_vec();
421 Box::pin(async move {
422 self.sweep(&path).await;
423 self.0
424 .check(&path, principal.as_deref(), ignore_principal, deep, &tokens)
425 .await
426 })
427 }
428
429 fn discover(&self, path: &DavPath) -> LsFuture<'_, Vec<DavLock>> {
430 let path = path.clone();
431 Box::pin(async move {
432 self.sweep(&path).await;
433 self.0.discover(&path).await
434 })
435 }
436
437 fn delete(&self, path: &DavPath) -> LsFuture<'_, Result<(), ()>> {
438 let path = path.clone();
439 Box::pin(async move { self.0.delete(&path).await })
440 }
441}
442
443/// One mutex per path with a writer on it.
444///
445/// WebDAV locking does not cover this: a lock is only consulted for a client
446/// that sends LOCK, and a plain PUT never does. Two concurrent PUTs otherwise
447/// interleave into a byte-level splice of both bodies, with both clients told
448/// 2xx. Serializing the write open makes the outcome last-writer-wins.
449///
450/// Keyed by the resolved absolute path, so two mounts onto the same file share
451/// one mutex. The lock tree cannot do that: it keys on the URL, and the same
452/// file has a different URL in a user mount and in a share.
453static WRITE_LOCKS: LazyLock<Mutex<HashMap<PathBuf, Weak<tokio::sync::Mutex<()>>>>> =
454 LazyLock::new(|| Mutex::new(HashMap::new()));
455
456fn write_lock(path: &Path) -> Arc<tokio::sync::Mutex<()>> {
457 let mut map = WRITE_LOCKS.lock().unwrap_or_else(|e| e.into_inner());
458 // Drop entries whose last writer finished, so the map holds in-flight
459 // writes and not every file ever written.
460 map.retain(|_, w| w.strong_count() > 0);
461 if let Some(m) = map.get(path).and_then(Weak::upgrade) {
462 return m;
463 }
464 let m = Arc::new(tokio::sync::Mutex::new(()));
465 map.insert(path.to_path_buf(), Arc::downgrade(&m));
466 m
467}
468
469// ---------------------------------------------------------------------------
470// Mount: which roots a request sees, and where in the URL they live
471// ---------------------------------------------------------------------------
472
473/// The credentials `dav-server` carries through to [`FbFs`]: the roots this
474/// request may touch, and how they are laid out under the mount point.
475#[derive(Clone)]
476pub struct Mount {
477 /// URL segment → root. The segment is empty when `flat`.
478 roots: Arc<Vec<(String, RootRow)>>,
479 /// One root mounted directly at the mount point (a share), rather than as
480 /// a child of a synthetic collection.
481 flat: bool,
482}
483
484/// What a dav path addresses.
485enum Target {
486 /// The synthetic collection at the mount point that lists the roots.
487 Roots,
488 Item {
489 root: RootRow,
490 rel: String,
491 },
492}
493
494/// The URL segment for each root: its display name, disambiguated with the
495/// root id when two roots would otherwise claim the same one.
496fn root_segments(state: &AppState, roots: Vec<RootRow>) -> Vec<(String, RootRow)> {
497 let names: Vec<String> = roots.iter().map(|r| display_name(state, &r.path)).collect();
498 roots
499 .into_iter()
500 .zip(&names)
501 .map(|(r, name)| {
502 let taken = names.iter().filter(|n| *n == name).count() > 1;
503 let seg = match taken {
504 true => format!("{name}-{}", r.id),
505 false => name.clone(),
506 };
507 (seg, r)
508 })
509 .collect()
510}
511
512fn target(path: &DavPath, mount: &Mount) -> FsResult<Target> {
513 let rel = path.as_rel_ospath();
514 if mount.flat {
515 let (_, root) = mount.roots.first().ok_or(FsError::NotFound)?;
516 return Ok(Target::Item {
517 root: root.clone(),
518 rel: rel.to_string_lossy().into_owned(),
519 });
520 }
521 let mut parts = rel.components();
522 let Some(first) = parts.next() else {
523 return Ok(Target::Roots);
524 };
525 let seg = first.as_os_str().to_string_lossy();
526 let (_, root) = mount
527 .roots
528 .iter()
529 .find(|(s, _)| s.as_str() == seg)
530 .ok_or(FsError::NotFound)?;
531 Ok(Target::Item {
532 root: root.clone(),
533 rel: parts.collect::<PathBuf>().to_string_lossy().into_owned(),
534 })
535}
536
537/// [`target`], rejecting the synthetic collection.
538fn item(path: &DavPath, mount: &Mount) -> FsResult<(RootRow, String)> {
539 match target(path, mount)? {
540 Target::Roots => Err(FsError::Forbidden),
541 Target::Item { root, rel } => Ok((root, rel)),
542 }
543}
544
545fn writable(root: &RootRow) -> FsResult<()> {
546 match root.mode {
547 Mode::Rw => Ok(()),
548 Mode::Ro => Err(FsError::Forbidden),
549 }
550}
551
552// ---------------------------------------------------------------------------
553// The filesystem
554// ---------------------------------------------------------------------------
555
556#[derive(Clone)]
557struct FbFs {
558 state: Arc<AppState>,
559}
560
561impl GuardedFileSystem<Mount> for FbFs {
562 fn open<'a>(
563 &'a self,
564 path: &'a DavPath,
565 options: OpenOptions,
566 mount: &'a Mount,
567 ) -> FsFuture<'a, Box<dyn DavFile>> {
568 Box::pin(async move {
569 let (root, rel) = item(path, mount)?;
570 if options.write || options.append || options.truncate || options.create {
571 writable(&root)?;
572 }
573 let creating = options.create || options.create_new;
574 let full = self
575 .resolve(&root, rel, move |server_root, root_rel, rel| {
576 use crate::fs::FsError as E;
577 // Strict first, so a write lands on the file the path
578 // really names.
579 match crate::fs::resolve_path(server_root, root_rel, rel) {
580 Err(E::NotFound) if creating => {
581 let p = crate::fs::resolve_entry(server_root, root_rel, rel)?;
582 // Nothing resolved, yet the name is taken: a
583 // dangling symlink. Opening that with `create`
584 // would write wherever it points, which may be
585 // outside the root.
586 if std::fs::symlink_metadata(&p).is_ok() {
587 return Err(E::Forbidden);
588 }
589 Ok(p)
590 }
591 other => other,
592 }
593 })
594 .await?;
595 // Taken before the open, so the truncate happens under it too,
596 // and held until the `DavFile` is dropped, which is after the last
597 // byte of the body has landed.
598 let writing = options.write || options.append || options.truncate;
599 let _write = match writing {
600 true => Some(write_lock(&full).lock_owned().await),
601 false => None,
602 };
603 let file = tokio::fs::OpenOptions::new()
604 .read(options.read)
605 .write(options.write)
606 .append(options.append)
607 .truncate(options.truncate)
608 .create(options.create)
609 .create_new(options.create_new)
610 .open(&full)
611 .await
612 .map_err(|e| io_error(&e))?;
613 Ok(Box::new(File { file, _write }) as Box<dyn DavFile>)
614 })
615 }
616
617 /// `meta` decides whether a symlink is described as itself or as what it
618 /// points at, and `dav-server` picks it per operation: `Data` for a
619 /// listing, `DataSymlink` for the walk behind a recursive DELETE or COPY.
620 /// Answering both with followed metadata makes a recursive DELETE descend
621 /// into a linked directory and empty it.
622 fn read_dir<'a>(
623 &'a self,
624 path: &'a DavPath,
625 meta: ReadDirMeta,
626 mount: &'a Mount,
627 ) -> FsFuture<'a, FsStream<Box<dyn DavDirEntry>>> {
628 Box::pin(async move {
629 let listing = matches!(meta, ReadDirMeta::Data);
630 let entries = match target(path, mount)? {
631 Target::Roots => {
632 // That walk deletes the children before it asks to remove
633 // the collection, so refusing the mount point at
634 // `remove_dir` would come after every root was emptied.
635 // Refusing the listing stops it before anything is touched.
636 if !listing {
637 return Err(FsError::Forbidden);
638 }
639 self.root_entries(mount).await
640 }
641 Target::Item { root, rel } => {
642 // Same for a root's own top. It is a mount point, not a
643 // folder inside one. A whole root cannot be deleted, moved
644 // onto, or copied through the mount.
645 if rel.is_empty() && !listing {
646 return Err(FsError::Forbidden);
647 }
648 let full = self.resolve(&root, rel, crate::fs::resolve_path).await?;
649 // No `MAX_LIST_ENTRIES` cap here, on purpose. PROPFIND has
650 // no way to say "this listing was cut", so a sync client
651 // would read a truncated listing as "the rest was deleted"
652 // and mirror that.
653 blocking(move || {
654 let rd = std::fs::read_dir(&full).map_err(|e| io_error(&e))?;
655 Ok(rd
656 .flatten()
657 .filter_map(|e| {
658 // A link out of the root is still listed. It
659 // refuses to open.
660 let meta = match listing {
661 true => match std::fs::metadata(e.path()) {
662 Ok(m) => Meta::of(&m),
663 // No target to stat: a dangling link.
664 Err(_) => Meta::broken_link(
665 &std::fs::symlink_metadata(e.path()).ok()?,
666 ),
667 },
668 false => Meta::of(&std::fs::symlink_metadata(e.path()).ok()?),
669 };
670 Some(Entry {
671 name: e.file_name().to_string_lossy().into_owned().into_bytes(),
672 meta,
673 })
674 })
675 .collect())
676 })
677 .await?
678 }
679 };
680 let stream = futures_util::stream::iter(
681 entries
682 .into_iter()
683 .map(|e| Ok(Box::new(e) as Box<dyn DavDirEntry>)),
684 );
685 Ok(Box::pin(stream) as FsStream<Box<dyn DavDirEntry>>)
686 })
687 }
688
689 fn metadata<'a>(
690 &'a self,
691 path: &'a DavPath,
692 mount: &'a Mount,
693 ) -> FsFuture<'a, Box<dyn DavMetaData>> {
694 Box::pin(async move {
695 let (root, rel) = match target(path, mount)? {
696 Target::Roots => return Ok(Box::new(Meta::synthetic_dir()) as Box<dyn DavMetaData>),
697 Target::Item { root, rel } => (root, rel),
698 };
699 let full = self.resolve(&root, rel, crate::fs::resolve_path).await?;
700 let meta = blocking(move || std::fs::metadata(&full).map_err(|e| io_error(&e))).await?;
701 Ok(Box::new(Meta::of(&meta)) as Box<dyn DavMetaData>)
702 })
703 }
704
705 /// Metadata of the entry itself. `dav-server` asks this before a DELETE,
706 /// a MOVE, and before overwriting a destination, precisely so it can act
707 /// on a link rather than on what it names.
708 fn symlink_metadata<'a>(
709 &'a self,
710 path: &'a DavPath,
711 mount: &'a Mount,
712 ) -> FsFuture<'a, Box<dyn DavMetaData>> {
713 Box::pin(async move {
714 let (root, rel) = match target(path, mount)? {
715 Target::Roots => return Ok(Box::new(Meta::synthetic_dir()) as Box<dyn DavMetaData>),
716 Target::Item { root, rel } => (root, rel),
717 };
718 let full = self.resolve(&root, rel, crate::fs::resolve_entry).await?;
719 let meta = blocking(move || std::fs::symlink_metadata(&full).map_err(|e| io_error(&e)))
720 .await?;
721 Ok(Box::new(Meta::of(&meta)) as Box<dyn DavMetaData>)
722 })
723 }
724
725 fn create_dir<'a>(&'a self, path: &'a DavPath, mount: &'a Mount) -> FsFuture<'a, ()> {
726 Box::pin(async move {
727 let (root, rel) = item(path, mount)?;
728 writable(&root)?;
729 let (server_root, root_rel) = (self.state.root.clone(), root.path.clone());
730 blocking(move || crate::fs::mkdir(&server_root, &root_rel, &rel).map_err(fs_error))
731 .await
732 })
733 }
734
735 /// Only ever called on an empty directory: `dav-server` walks a tree
736 /// itself and removes the children first.
737 fn remove_dir<'a>(&'a self, path: &'a DavPath, mount: &'a Mount) -> FsFuture<'a, ()> {
738 Box::pin(async move {
739 let (root, rel) = item(path, mount)?;
740 writable(&root)?;
741 let full = self.resolve(&root, rel, crate::fs::resolve_entry).await?;
742 blocking(move || {
743 // A symlink to a directory is listed as a collection, so this
744 // is where DELETE lands on one. Unlink it rather than letting
745 // `remove_dir` fail on a path that is not a directory.
746 let meta = std::fs::symlink_metadata(&full).map_err(|e| io_error(&e))?;
747 match meta.file_type().is_symlink() {
748 true => std::fs::remove_file(&full),
749 false => std::fs::remove_dir(&full),
750 }
751 .map_err(|e| io_error(&e))
752 })
753 .await
754 })
755 }
756
757 fn remove_file<'a>(&'a self, path: &'a DavPath, mount: &'a Mount) -> FsFuture<'a, ()> {
758 Box::pin(async move {
759 let (root, rel) = item(path, mount)?;
760 writable(&root)?;
761 // Not followed: deleting a symlink removes the link, not the file
762 // it names.
763 let full = self.resolve(&root, rel, crate::fs::resolve_entry).await?;
764 blocking(move || std::fs::remove_file(&full).map_err(|e| io_error(&e))).await
765 })
766 }
767
768 fn rename<'a>(
769 &'a self,
770 from: &'a DavPath,
771 to: &'a DavPath,
772 mount: &'a Mount,
773 ) -> FsFuture<'a, ()> {
774 Box::pin(async move {
775 let (src, dst) = (item(from, mount)?, item(to, mount)?);
776 // A move takes the item out of the source root, so that root has
777 // to be writable too.
778 writable(&src.0)?;
779 writable(&dst.0)?;
780 let server_root = self.state.root.clone();
781 blocking(move || {
782 crate::fs::move_to(&server_root, &src.0.path, &src.1, &dst.0.path, &dst.1)
783 .map_err(fs_error)
784 })
785 .await
786 })
787 }
788
789 /// Files only: `dav-server` walks a directory tree itself.
790 fn copy<'a>(
791 &'a self,
792 from: &'a DavPath,
793 to: &'a DavPath,
794 mount: &'a Mount,
795 ) -> FsFuture<'a, ()> {
796 Box::pin(async move {
797 let (src, dst) = (item(from, mount)?, item(to, mount)?);
798 // Only the destination is written. Copying *out of* a read-only
799 // root is fine, and is how a user gets a read-only folder's
800 // contents into a writable one.
801 writable(&dst.0)?;
802 // The same mutex a PUT to this path would take, or a COPY and a
803 // PUT racing for it interleave. Both resolve to the canonical
804 // parent plus the name, so the keys agree.
805 let full = self
806 .resolve(&dst.0, dst.1.clone(), crate::fs::resolve_entry)
807 .await?;
808 let _write = write_lock(&full).lock_owned().await;
809 let server_root = self.state.root.clone();
810 blocking(move || {
811 crate::fs::copy_file_to(&server_root, &src.0.path, &src.1, &dst.0.path, &dst.1)
812 .map_err(fs_error)
813 })
814 .await
815 })
816 }
817}
818
819impl FbFs {
820 /// Run one of the [`crate::fs`] resolvers on the blocking pool.
821 async fn resolve(
822 &self,
823 root: &RootRow,
824 rel: String,
825 f: impl FnOnce(&std::path::Path, &str, &str) -> Result<PathBuf, crate::fs::FsError>
826 + Send
827 + 'static,
828 ) -> FsResult<PathBuf> {
829 let (server_root, root_rel) = (self.state.root.clone(), root.path.clone());
830 blocking(move || f(&server_root, &root_rel, &rel).map_err(fs_error)).await
831 }
832
833 /// The synthetic top-level listing: one entry per mounted root.
834 async fn root_entries(&self, mount: &Mount) -> Vec<Entry> {
835 let mut out = Vec::with_capacity(mount.roots.len());
836 for (seg, root) in mount.roots.iter() {
837 // A root that no longer resolves is skipped rather than reported
838 // as broken: the JSON API hides it the same way.
839 let (server_root, root_rel) = (self.state.root.clone(), root.path.clone());
840 let Ok(full) = blocking(move || {
841 crate::fs::resolve_root(&server_root, &root_rel).map_err(fs_error)
842 })
843 .await
844 else {
845 continue;
846 };
847 let meta = tokio::fs::metadata(&full)
848 .await
849 .map(|m| Meta::of(&m))
850 .unwrap_or_else(|_| Meta::synthetic_dir());
851 out.push(Entry {
852 name: seg.clone().into_bytes(),
853 meta,
854 });
855 }
856 out
857 }
858}
859
860// ---------------------------------------------------------------------------
861// Filesystem value types
862// ---------------------------------------------------------------------------
863
864#[derive(Debug, Clone)]
865struct Meta {
866 len: u64,
867 modified: SystemTime,
868 is_dir: bool,
869 is_symlink: bool,
870}
871
872impl Meta {
873 fn of(m: &std::fs::Metadata) -> Self {
874 Meta {
875 len: m.len(),
876 modified: m.modified().unwrap_or(UNIX_EPOCH),
877 is_dir: m.is_dir(),
878 is_symlink: m.file_type().is_symlink(),
879 }
880 }
881
882 /// A listing entry whose target could not be stat'd: a dangling symlink.
883 ///
884 /// Described as an empty file, not as a link: `dav-server` drops any entry
885 /// a listing reports as a symlink, and a sync client reads a file missing
886 /// from PROPFIND as a deletion to mirror.
887 fn broken_link(m: &std::fs::Metadata) -> Self {
888 Meta {
889 len: 0,
890 is_dir: false,
891 is_symlink: false,
892 ..Meta::of(m)
893 }
894 }
895
896 /// The mount point itself, which is not a directory on disk.
897 fn synthetic_dir() -> Self {
898 Meta {
899 len: 0,
900 modified: UNIX_EPOCH,
901 is_dir: true,
902 is_symlink: false,
903 }
904 }
905}
906
907impl DavMetaData for Meta {
908 fn len(&self) -> u64 {
909 self.len
910 }
911
912 fn modified(&self) -> FsResult<SystemTime> {
913 Ok(self.modified)
914 }
915
916 fn is_dir(&self) -> bool {
917 self.is_dir
918 }
919
920 fn is_symlink(&self) -> bool {
921 self.is_symlink
922 }
923}
924
925#[derive(Debug)]
926struct Entry {
927 name: Vec<u8>,
928 meta: Meta,
929}
930
931impl DavDirEntry for Entry {
932 fn name(&self) -> Vec<u8> {
933 self.name.clone()
934 }
935
936 fn metadata(&self) -> FsFuture<'_, Box<dyn DavMetaData>> {
937 let meta = self.meta.clone();
938 Box::pin(std::future::ready(Ok(
939 Box::new(meta) as Box<dyn DavMetaData>
940 )))
941 }
942}
943
944/// An open file. Plain async I/O: the path was already resolved and checked,
945/// so nothing here needs the blocking pool.
946#[derive(Debug)]
947struct File {
948 file: tokio::fs::File,
949 /// Held for the life of a writable handle. See [`WRITE_LOCKS`].
950 _write: Option<tokio::sync::OwnedMutexGuard<()>>,
951}
952
953/// Ceiling on one `read_bytes` allocation. `dav-server` asks for its own read
954/// buffer size, but the count reaches us from the request, and a short read is
955/// always a valid answer.
956const MAX_READ: usize = 64 * 1024;
957
958impl DavFile for File {
959 fn metadata(&mut self) -> FsFuture<'_, Box<dyn DavMetaData>> {
960 Box::pin(async move {
961 let m = self.file.metadata().await.map_err(|e| io_error(&e))?;
962 Ok(Box::new(Meta::of(&m)) as Box<dyn DavMetaData>)
963 })
964 }
965
966 fn write_buf(&mut self, mut buf: Box<dyn Buf + Send>) -> FsFuture<'_, ()> {
967 Box::pin(async move {
968 while buf.has_remaining() {
969 let n = self
970 .file
971 .write(buf.chunk())
972 .await
973 .map_err(|e| io_error(&e))?;
974 buf.advance(n);
975 }
976 Ok(())
977 })
978 }
979
980 fn write_bytes(&mut self, buf: Bytes) -> FsFuture<'_, ()> {
981 Box::pin(async move { self.file.write_all(&buf).await.map_err(|e| io_error(&e)) })
982 }
983
984 fn read_bytes(&mut self, count: usize) -> FsFuture<'_, Bytes> {
985 Box::pin(async move {
986 let mut b = vec![0u8; count.min(MAX_READ)];
987 let n = self.file.read(&mut b).await.map_err(|e| io_error(&e))?;
988 b.truncate(n);
989 Ok(Bytes::from(b))
990 })
991 }
992
993 fn seek(&mut self, pos: SeekFrom) -> FsFuture<'_, u64> {
994 Box::pin(async move { self.file.seek(pos).await.map_err(|e| io_error(&e)) })
995 }
996
997 fn flush(&mut self) -> FsFuture<'_, ()> {
998 Box::pin(async move { self.file.flush().await.map_err(|e| io_error(&e)) })
999 }
1000}
1001
1002// ---------------------------------------------------------------------------
1003// Errors and blocking work
1004// ---------------------------------------------------------------------------
1005
1006/// Run blocking filesystem work, mapping a panic or a shut-down runtime onto
1007/// a 500.
1008async fn blocking<T: Send + 'static>(
1009 f: impl FnOnce() -> FsResult<T> + Send + 'static,
1010) -> FsResult<T> {
1011 tokio::task::spawn_blocking(f)
1012 .await
1013 .map_err(|_| FsError::GeneralFailure)?
1014}
1015
1016fn fs_error(e: crate::fs::FsError) -> FsError {
1017 use crate::fs::FsError as E;
1018 match e {
1019 E::NotFound | E::RootMissing => FsError::NotFound,
1020 E::Conflict => FsError::Exists,
1021 // `Invalid` is a rejected name, which is a refusal, not a 400 here:
1022 // WebDAV has no status for "that name is not allowed".
1023 E::NotADirectory | E::Forbidden | E::Invalid(_) => FsError::Forbidden,
1024 }
1025}
1026
1027/// `dav-server` only derives this from `std::io::Error` when its own `localfs`
1028/// backend is compiled in, which it is not.
1029fn io_error(e: &std::io::Error) -> FsError {
1030 use std::io::ErrorKind as K;
1031 match e.kind() {
1032 K::NotFound => FsError::NotFound,
1033 K::PermissionDenied => FsError::Forbidden,
1034 K::AlreadyExists => FsError::Exists,
1035 K::CrossesDevices => FsError::IsRemote,
1036 // `read_dir` on a file. A refusal, not a server fault.
1037 K::NotADirectory => FsError::Forbidden,
1038 _ => FsError::GeneralFailure,
1039 }
1040}
1041