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