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