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 Some((user_id, principal)) = authenticate(&state, req.headers()).await else {
60 return challenge();
61 };
62 let Ok(roots) = state.db.user_roots(user_id).await else {
63 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
64 };
65 // The admin pseudo-root (the whole server root, read-only) is deliberately
66 // not mounted: `session_auth` does not add it, and a mount that silently
67 // contained a second copy of every other root would be confusing.
68 let mount = Mount {
69 roots: Arc::new(root_segments(&state, roots)),
70 flat: false,
71 };
72 serve(state, req, DAV.to_string(), principal, mount).await
73}
74
75/// `{DAV_SHARE}/{token}` and everything under it: one public share.
76///
77/// Folder shares only. A file share has no collection to mount, and its one
78/// file is already a plain `GET` away on the share page.
79pub async fn share(State(state): State<Arc<AppState>>, req: Request<Body>) -> Response<Body> {
80 let Some(token) = share_token(req.uri().path()) else {
81 return StatusCode::NOT_FOUND.into_response();
82 };
83 let row = match state.db.share_by_token(&token).await {
84 Ok(Some(row)) => row,
85 Ok(None) => return StatusCode::NOT_FOUND.into_response(),
86 Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
87 };
88 if row.is_expired() {
89 return StatusCode::GONE.into_response();
90 }
91 if row.is_file {
92 return StatusCode::NOT_FOUND.into_response();
93 }
94 // A protected share takes its password over Basic, with the user name
95 // ignored. There is no account behind a share link to name.
96 if let Some(hash) = row.password_hash.clone() {
97 let Some((_, password)) = auth::basic_credentials(req.headers()) else {
98 return challenge();
99 };
100 let (pw, id, tok) = (password.clone(), row.id, token.clone());
101 let ok = auth::verify_cached(row.id, "", &password, move || async move {
102 // Throttled like `POST /api/share/{token}/unlock`, keyed the same
103 // way, so a mount client is not the cheap way to guess.
104 auth::throttle(&tok).await;
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.
251pub(crate) fn 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 user id and name.
264pub(crate) async fn authenticate(state: &AppState, headers: &HeaderMap) -> Option<(i64, String)> {
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, _)) = session_auth(headers, state).await
269 {
270 return Some((user.id, user.name));
271 }
272
273 let (name, password) = auth::basic_credentials(headers)?;
274
275 // The Basic user name is ignored: the secret already names the account.
276 match state
277 .db
278 .user_by_app_password(&auth::app_password_hash(&password))
279 .await
280 {
281 Ok(Some(user)) => return Some((user.id, user.name)),
282 Ok(None) => {}
283 // A lookup error 401s a valid app password and counts as a failed
284 // login for that name below. Nothing else records that.
285 Err(e) => tracing::warn!(error = %e, "app password lookup failed"),
286 }
287
288 let id = auth::verify_cached(0, &name, &password, || {
289 let (state, name, password) = (state, name.clone(), password.clone());
290 async move {
291 // The login route's throttle, keyed the same way, so guessing over
292 // WebDAV is no cheaper than guessing over the login form.
293 auth::throttle(&name).await;
294 let verified = state.db.verify_password(&name, &password).await.ok()?;
295 // Record what the password did, not what the rule below decides.
296 // A mount on an account that requires a passkey keeps retrying,
297 // and counting each retry as a failed guess would pin that name's
298 // delay and lock the person out of the web login too.
299 auth::record_login(&name, verified.is_some());
300 // Basic carries a password and nothing else, so accepting the
301 // account password here would downgrade an account that asks for
302 // a passkey too. Such an account mounts with an app password,
303 // which the lookup above already handled.
304 verified
305 .filter(|u| u.auth_mode == AuthMode::Either)
306 .map(|u| u.id)
307 }
308 })
309 .await?;
310 Some((id, name))
311}
312
313// ---------------------------------------------------------------------------
314// Locking
315// ---------------------------------------------------------------------------
316
317/// One lock tree per principal.
318///
319/// A lock is keyed by DAV URL, and a URL segment is a root's display name, so a
320/// single shared tree lets two users whose roots are both named `Documents`
321/// reach each other's locks. One could block the other, and `PROPFIND` hands
322/// back the holder's lock token, which is enough to release that lock or write
323/// through it.
324///
325/// The cost is that two principals sharing one physical folder do not
326/// coordinate through WebDAV locks. Byte-level safety does not rest on this:
327/// [`WRITE_LOCKS`] keys on the resolved path and covers every writer.
328///
329/// `MemLs` keeps its state in an `Arc`, so a clone shares that principal's
330/// tree. Locks live in memory only, and a restart drops them all, which is
331/// what a client already sees when a lock times out.
332static LOCKS: LazyLock<Mutex<HashMap<String, ExpiringLs>>> =
333 LazyLock::new(|| Mutex::new(HashMap::new()));
334
335fn locks_for(principal: &str) -> ExpiringLs {
336 let mut g = LOCKS.lock().unwrap_or_else(|e| e.into_inner());
337 g.entry(principal.to_string())
338 .or_insert_with(|| ExpiringLs(*MemLs::new()))
339 .clone()
340}
341
342/// Longest lock handed out, and so the longest an abandoned one blocks a file.
343/// A client that still wants the file refreshes; one that crashed does not.
344///
345/// Matches `dav-server`'s own ceiling for an exclusive lock. It caps only the
346/// two cases that arrive here uncapped, both as `None` meaning "never
347/// expires": a LOCK with no `Timeout` header, and a refresh asking for
348/// `Infinite`.
349const LOCK_TIMEOUT: Duration = Duration::from_secs(600);
350
351/// [`MemLs`] with lock expiry actually applied.
352///
353/// `MemLs` records a lock's `timeout_at` and then never looks at it again, and
354/// it honours an infinite timeout request. Left alone, a client that died
355/// holding an exclusive lock would block that file until the process restarts.
356/// Every call here first drops the expired locks covering the path it touches,
357/// and no lock is granted for longer than [`LOCK_TIMEOUT`].
358#[derive(Debug, Clone)]
359struct ExpiringLs(MemLs);
360
361impl ExpiringLs {
362 /// Drop the expired locks on `path` and its ancestors.
363 ///
364 /// Only the locks that could block an operation *on this path*. A lock on
365 /// a descendant is not swept, so a deep operation can still be refused by
366 /// a stale lock below it until something touches that path directly.
367 async fn sweep(&self, path: &DavPath) {
368 let now = SystemTime::now();
369 for lock in self.0.discover(path).await {
370 if lock.timeout_at.is_some_and(|t| t <= now) {
371 let _ = self.0.unlock(&lock.path, &lock.token).await;
372 }
373 }
374 }
375
376 /// Never `None`, never longer than [`LOCK_TIMEOUT`]. `None` would mean a
377 /// lock that [`sweep`](Self::sweep) can never clear.
378 fn capped(timeout: Option<Duration>) -> Option<Duration> {
379 Some(timeout.unwrap_or(LOCK_TIMEOUT).min(LOCK_TIMEOUT))
380 }
381}
382
383impl DavLockSystem for ExpiringLs {
384 fn lock(
385 &self,
386 path: &DavPath,
387 principal: Option<&str>,
388 owner: Option<&xmltree::Element>,
389 timeout: Option<Duration>,
390 shared: bool,
391 deep: bool,
392 ) -> LsFuture<'_, Result<DavLock, DavLock>> {
393 // The borrows end with the call, not with the future, so clone into it.
394 let (path, principal) = (path.clone(), principal.map(str::to_string));
395 let owner = owner.cloned();
396 Box::pin(async move {
397 self.sweep(&path).await;
398 self.0
399 .lock(
400 &path,
401 principal.as_deref(),
402 owner.as_ref(),
403 Self::capped(timeout),
404 shared,
405 deep,
406 )
407 .await
408 })
409 }
410
411 fn unlock(&self, path: &DavPath, token: &str) -> LsFuture<'_, Result<(), ()>> {
412 let (path, token) = (path.clone(), token.to_string());
413 Box::pin(async move { self.0.unlock(&path, &token).await })
414 }
415
416 fn refresh(
417 &self,
418 path: &DavPath,
419 token: &str,
420 timeout: Option<Duration>,
421 ) -> LsFuture<'_, Result<DavLock, ()>> {
422 let (path, token) = (path.clone(), token.to_string());
423 Box::pin(async move {
424 // Swept first: a client refreshing a lock it let expire must be
425 // told, not silently handed the file back.
426 self.sweep(&path).await;
427 self.0.refresh(&path, &token, Self::capped(timeout)).await
428 })
429 }
430
431 fn check(
432 &self,
433 path: &DavPath,
434 principal: Option<&str>,
435 ignore_principal: bool,
436 deep: bool,
437 submitted_tokens: &[String],
438 ) -> LsFuture<'_, Result<(), DavLock>> {
439 let (path, principal) = (path.clone(), principal.map(str::to_string));
440 let tokens = submitted_tokens.to_vec();
441 Box::pin(async move {
442 self.sweep(&path).await;
443 self.0
444 .check(&path, principal.as_deref(), ignore_principal, deep, &tokens)
445 .await
446 })
447 }
448
449 fn discover(&self, path: &DavPath) -> LsFuture<'_, Vec<DavLock>> {
450 let path = path.clone();
451 Box::pin(async move {
452 self.sweep(&path).await;
453 self.0.discover(&path).await
454 })
455 }
456
457 fn delete(&self, path: &DavPath) -> LsFuture<'_, Result<(), ()>> {
458 let path = path.clone();
459 Box::pin(async move { self.0.delete(&path).await })
460 }
461}
462
463/// One mutex per path with a writer on it.
464///
465/// WebDAV locking does not cover this: a lock is only consulted for a client
466/// that sends LOCK, and a plain PUT never does. Two concurrent PUTs otherwise
467/// interleave into a byte-level splice of both bodies, with both clients told
468/// 2xx. Serializing the write open makes the outcome last-writer-wins.
469///
470/// Keyed by the resolved absolute path, so two mounts onto the same file share
471/// one mutex. The lock tree cannot do that: it keys on the URL, and the same
472/// file has a different URL in a user mount and in a share.
473static WRITE_LOCKS: LazyLock<Mutex<HashMap<PathBuf, Weak<tokio::sync::Mutex<()>>>>> =
474 LazyLock::new(|| Mutex::new(HashMap::new()));
475
476fn write_lock(path: &Path) -> Arc<tokio::sync::Mutex<()>> {
477 let mut map = WRITE_LOCKS.lock().unwrap_or_else(|e| e.into_inner());
478 // Drop entries whose last writer finished, so the map holds in-flight
479 // writes and not every file ever written.
480 map.retain(|_, w| w.strong_count() > 0);
481 if let Some(m) = map.get(path).and_then(Weak::upgrade) {
482 return m;
483 }
484 let m = Arc::new(tokio::sync::Mutex::new(()));
485 map.insert(path.to_path_buf(), Arc::downgrade(&m));
486 m
487}
488
489// ---------------------------------------------------------------------------
490// Mount: which roots a request sees, and where in the URL they live
491// ---------------------------------------------------------------------------
492
493/// The credentials `dav-server` carries through to [`FbFs`]: the roots this
494/// request may touch, and how they are laid out under the mount point.
495#[derive(Clone)]
496pub struct Mount {
497 /// URL segment → root. The segment is empty when `flat`.
498 roots: Arc<Vec<(String, RootRow)>>,
499 /// One root mounted directly at the mount point (a share), rather than as
500 /// a child of a synthetic collection.
501 flat: bool,
502}
503
504/// What a dav path addresses.
505enum Target {
506 /// The synthetic collection at the mount point that lists the roots.
507 Roots,
508 Item {
509 root: RootRow,
510 rel: String,
511 },
512}
513
514/// The URL segment for each root: its display name, disambiguated with the
515/// root id when two roots would otherwise claim the same one.
516fn root_segments(state: &AppState, roots: Vec<RootRow>) -> Vec<(String, RootRow)> {
517 let names: Vec<String> = roots.iter().map(|r| display_name(state, &r.path)).collect();
518 roots
519 .into_iter()
520 .zip(&names)
521 .map(|(r, name)| {
522 let taken = names.iter().filter(|n| *n == name).count() > 1;
523 let seg = match taken {
524 true => format!("{name}-{}", r.id),
525 false => name.clone(),
526 };
527 (seg, r)
528 })
529 .collect()
530}
531
532fn target(path: &DavPath, mount: &Mount) -> FsResult<Target> {
533 let rel = path.as_rel_ospath();
534 if mount.flat {
535 let (_, root) = mount.roots.first().ok_or(FsError::NotFound)?;
536 return Ok(Target::Item {
537 root: root.clone(),
538 rel: rel.to_string_lossy().into_owned(),
539 });
540 }
541 let mut parts = rel.components();
542 let Some(first) = parts.next() else {
543 return Ok(Target::Roots);
544 };
545 let seg = first.as_os_str().to_string_lossy();
546 let (_, root) = mount
547 .roots
548 .iter()
549 .find(|(s, _)| s.as_str() == seg)
550 .ok_or(FsError::NotFound)?;
551 Ok(Target::Item {
552 root: root.clone(),
553 rel: parts.collect::<PathBuf>().to_string_lossy().into_owned(),
554 })
555}
556
557/// [`target`], rejecting the synthetic collection.
558fn item(path: &DavPath, mount: &Mount) -> FsResult<(RootRow, String)> {
559 match target(path, mount)? {
560 Target::Roots => Err(FsError::Forbidden),
561 Target::Item { root, rel } => Ok((root, rel)),
562 }
563}
564
565fn writable(root: &RootRow) -> FsResult<()> {
566 match root.mode {
567 Mode::Rw => Ok(()),
568 Mode::Ro => Err(FsError::Forbidden),
569 }
570}
571
572// ---------------------------------------------------------------------------
573// The filesystem
574// ---------------------------------------------------------------------------
575
576#[derive(Clone)]
577struct FbFs {
578 state: Arc<AppState>,
579}
580
581impl GuardedFileSystem<Mount> for FbFs {
582 fn open<'a>(
583 &'a self,
584 path: &'a DavPath,
585 options: OpenOptions,
586 mount: &'a Mount,
587 ) -> FsFuture<'a, Box<dyn DavFile>> {
588 Box::pin(async move {
589 let (root, rel) = item(path, mount)?;
590 if options.write || options.append || options.truncate || options.create {
591 writable(&root)?;
592 }
593 let creating = options.create || options.create_new;
594 let full = self
595 .resolve(&root, rel, move |server_root, root_rel, rel| {
596 use crate::fs::FsError as E;
597 // Strict first, so a write lands on the file the path
598 // really names.
599 match crate::fs::resolve_path(server_root, root_rel, rel) {
600 Err(E::NotFound) if creating => {
601 let p = crate::fs::resolve_entry(server_root, root_rel, rel)?;
602 // Nothing resolved, yet the name is taken: a
603 // dangling symlink. Opening that with `create`
604 // would write wherever it points, which may be
605 // outside the root.
606 if std::fs::symlink_metadata(&p).is_ok() {
607 return Err(E::Forbidden);
608 }
609 Ok(p)
610 }
611 other => other,
612 }
613 })
614 .await?;
615 // Taken before the open, so the truncate happens under it too,
616 // and held until the `DavFile` is dropped, which is after the last
617 // byte of the body has landed.
618 let writing = options.write || options.append || options.truncate;
619 let _write = match writing {
620 true => Some(write_lock(&full).lock_owned().await),
621 false => None,
622 };
623 let file = tokio::fs::OpenOptions::new()
624 .read(options.read)
625 .write(options.write)
626 .append(options.append)
627 .truncate(options.truncate)
628 .create(options.create)
629 .create_new(options.create_new)
630 .open(&full)
631 .await
632 .map_err(|e| io_error(&e))?;
633 Ok(Box::new(File { file, _write }) as Box<dyn DavFile>)
634 })
635 }
636
637 /// `meta` decides whether a symlink is described as itself or as what it
638 /// points at, and `dav-server` picks it per operation: `Data` for a
639 /// listing, `DataSymlink` for the walk behind a recursive DELETE or COPY.
640 /// Answering both with followed metadata makes a recursive DELETE descend
641 /// into a linked directory and empty it.
642 fn read_dir<'a>(
643 &'a self,
644 path: &'a DavPath,
645 meta: ReadDirMeta,
646 mount: &'a Mount,
647 ) -> FsFuture<'a, FsStream<Box<dyn DavDirEntry>>> {
648 Box::pin(async move {
649 let listing = matches!(meta, ReadDirMeta::Data);
650 let entries = match target(path, mount)? {
651 Target::Roots => {
652 // That walk deletes the children before it asks to remove
653 // the collection, so refusing the mount point at
654 // `remove_dir` would come after every root was emptied.
655 // Refusing the listing stops it before anything is touched.
656 if !listing {
657 return Err(FsError::Forbidden);
658 }
659 self.root_entries(mount).await
660 }
661 Target::Item { root, rel } => {
662 // Same for a root's own top. It is a mount point, not a
663 // folder inside one. A whole root cannot be deleted, moved
664 // onto, or copied through the mount.
665 if rel.is_empty() && !listing {
666 return Err(FsError::Forbidden);
667 }
668 let full = self.resolve(&root, rel, crate::fs::resolve_path).await?;
669 // No `MAX_LIST_ENTRIES` cap here, on purpose. PROPFIND has
670 // no way to say "this listing was cut", so a sync client
671 // would read a truncated listing as "the rest was deleted"
672 // and mirror that.
673 blocking(move || {
674 let rd = std::fs::read_dir(&full).map_err(|e| io_error(&e))?;
675 Ok(rd
676 .flatten()
677 .filter_map(|e| {
678 // A link out of the root is still listed. It
679 // refuses to open.
680 let meta = match listing {
681 true => match std::fs::metadata(e.path()) {
682 Ok(m) => Meta::of(&m),
683 // No target to stat: a dangling link.
684 Err(_) => Meta::broken_link(
685 &std::fs::symlink_metadata(e.path()).ok()?,
686 ),
687 },
688 false => Meta::of(&std::fs::symlink_metadata(e.path()).ok()?),
689 };
690 Some(Entry {
691 name: e.file_name().to_string_lossy().into_owned().into_bytes(),
692 meta,
693 })
694 })
695 .collect())
696 })
697 .await?
698 }
699 };
700 let stream = futures_util::stream::iter(
701 entries
702 .into_iter()
703 .map(|e| Ok(Box::new(e) as Box<dyn DavDirEntry>)),
704 );
705 Ok(Box::pin(stream) as FsStream<Box<dyn DavDirEntry>>)
706 })
707 }
708
709 fn metadata<'a>(
710 &'a self,
711 path: &'a DavPath,
712 mount: &'a Mount,
713 ) -> FsFuture<'a, Box<dyn DavMetaData>> {
714 Box::pin(self.stat(path, mount, crate::fs::resolve_path, |p| {
715 std::fs::metadata(p)
716 }))
717 }
718
719 /// Metadata of the entry itself. `dav-server` asks this before a DELETE,
720 /// a MOVE, and before overwriting a destination, precisely so it can act
721 /// on a link rather than on what it names.
722 fn symlink_metadata<'a>(
723 &'a self,
724 path: &'a DavPath,
725 mount: &'a Mount,
726 ) -> FsFuture<'a, Box<dyn DavMetaData>> {
727 Box::pin(self.stat(path, mount, crate::fs::resolve_entry, |p| {
728 std::fs::symlink_metadata(p)
729 }))
730 }
731
732 fn create_dir<'a>(&'a self, path: &'a DavPath, mount: &'a Mount) -> FsFuture<'a, ()> {
733 Box::pin(async move {
734 let (root, rel) = item(path, mount)?;
735 writable(&root)?;
736 let (server_root, root_rel) = (self.state.root.clone(), root.path.clone());
737 blocking(move || crate::fs::mkdir(&server_root, &root_rel, &rel).map_err(fs_error))
738 .await
739 })
740 }
741
742 /// Only ever called on an empty directory: `dav-server` walks a tree
743 /// itself and removes the children first.
744 fn remove_dir<'a>(&'a self, path: &'a DavPath, mount: &'a Mount) -> FsFuture<'a, ()> {
745 Box::pin(async move {
746 let (root, rel) = item(path, mount)?;
747 writable(&root)?;
748 let full = self.resolve(&root, rel, crate::fs::resolve_entry).await?;
749 blocking(move || {
750 // A symlink to a directory is listed as a collection, so this
751 // is where DELETE lands on one. Unlink it rather than letting
752 // `remove_dir` fail on a path that is not a directory.
753 let meta = std::fs::symlink_metadata(&full).map_err(|e| io_error(&e))?;
754 match meta.file_type().is_symlink() {
755 true => std::fs::remove_file(&full),
756 false => std::fs::remove_dir(&full),
757 }
758 .map_err(|e| io_error(&e))
759 })
760 .await
761 })
762 }
763
764 fn remove_file<'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 // Not followed: deleting a symlink removes the link, not the file
769 // it names.
770 let full = self.resolve(&root, rel, crate::fs::resolve_entry).await?;
771 blocking(move || std::fs::remove_file(&full).map_err(|e| io_error(&e))).await
772 })
773 }
774
775 fn rename<'a>(
776 &'a self,
777 from: &'a DavPath,
778 to: &'a DavPath,
779 mount: &'a Mount,
780 ) -> FsFuture<'a, ()> {
781 Box::pin(async move {
782 let (src, dst) = (item(from, mount)?, item(to, mount)?);
783 // A move takes the item out of the source root, so that root has
784 // to be writable too.
785 writable(&src.0)?;
786 writable(&dst.0)?;
787 let server_root = self.state.root.clone();
788 blocking(move || {
789 crate::fs::move_to(&server_root, &src.0.path, &src.1, &dst.0.path, &dst.1)
790 .map_err(fs_error)
791 })
792 .await
793 })
794 }
795
796 /// Files only: `dav-server` walks a directory tree itself.
797 fn copy<'a>(
798 &'a self,
799 from: &'a DavPath,
800 to: &'a DavPath,
801 mount: &'a Mount,
802 ) -> FsFuture<'a, ()> {
803 Box::pin(async move {
804 let (src, dst) = (item(from, mount)?, item(to, mount)?);
805 // Only the destination is written. Copying *out of* a read-only
806 // root is fine, and is how a user gets a read-only folder's
807 // contents into a writable one.
808 writable(&dst.0)?;
809 // The same mutex a PUT to this path would take, or a COPY and a
810 // PUT racing for it interleave. Both resolve to the canonical
811 // parent plus the name, so the keys agree.
812 let full = self
813 .resolve(&dst.0, dst.1.clone(), crate::fs::resolve_entry)
814 .await?;
815 let _write = write_lock(&full).lock_owned().await;
816 let server_root = self.state.root.clone();
817 blocking(move || {
818 crate::fs::copy_file_to(&server_root, &src.0.path, &src.1, &dst.0.path, &dst.1)
819 .map_err(fs_error)
820 })
821 .await
822 })
823 }
824}
825
826impl FbFs {
827 /// Metadata of `path`, resolved by `resolve` and read by `stat`.
828 async fn stat(
829 &self,
830 path: &DavPath,
831 mount: &Mount,
832 resolve: fn(&Path, &str, &str) -> Result<PathBuf, crate::fs::FsError>,
833 stat: fn(&Path) -> std::io::Result<std::fs::Metadata>,
834 ) -> FsResult<Box<dyn DavMetaData>> {
835 let (root, rel) = match target(path, mount)? {
836 Target::Roots => return Ok(Box::new(Meta::synthetic_dir())),
837 Target::Item { root, rel } => (root, rel),
838 };
839 let full = self.resolve(&root, rel, resolve).await?;
840 let meta = blocking(move || stat(&full).map_err(|e| io_error(&e))).await?;
841 Ok(Box::new(Meta::of(&meta)))
842 }
843
844 /// Run one of the [`crate::fs`] resolvers on the blocking pool.
845 async fn resolve(
846 &self,
847 root: &RootRow,
848 rel: String,
849 f: impl FnOnce(&std::path::Path, &str, &str) -> Result<PathBuf, crate::fs::FsError>
850 + Send
851 + 'static,
852 ) -> FsResult<PathBuf> {
853 let (server_root, root_rel) = (self.state.root.clone(), root.path.clone());
854 blocking(move || f(&server_root, &root_rel, &rel).map_err(fs_error)).await
855 }
856
857 /// The synthetic top-level listing: one entry per mounted root.
858 async fn root_entries(&self, mount: &Mount) -> Vec<Entry> {
859 let mut out = Vec::with_capacity(mount.roots.len());
860 for (seg, root) in mount.roots.iter() {
861 // A root that no longer resolves is skipped rather than reported
862 // as broken: the JSON API hides it the same way.
863 let (server_root, root_rel) = (self.state.root.clone(), root.path.clone());
864 let Ok(full) = blocking(move || {
865 crate::fs::resolve_root(&server_root, &root_rel).map_err(fs_error)
866 })
867 .await
868 else {
869 continue;
870 };
871 let meta = tokio::fs::metadata(&full)
872 .await
873 .map(|m| Meta::of(&m))
874 .unwrap_or_else(|_| Meta::synthetic_dir());
875 out.push(Entry {
876 name: seg.clone().into_bytes(),
877 meta,
878 });
879 }
880 out
881 }
882}
883
884// ---------------------------------------------------------------------------
885// Filesystem value types
886// ---------------------------------------------------------------------------
887
888#[derive(Debug, Clone)]
889struct Meta {
890 len: u64,
891 modified: SystemTime,
892 is_dir: bool,
893 is_symlink: bool,
894}
895
896impl Meta {
897 fn of(m: &std::fs::Metadata) -> Self {
898 Meta {
899 len: m.len(),
900 modified: m.modified().unwrap_or(UNIX_EPOCH),
901 is_dir: m.is_dir(),
902 is_symlink: m.file_type().is_symlink(),
903 }
904 }
905
906 /// A listing entry whose target could not be stat'd: a dangling symlink.
907 ///
908 /// Described as an empty file, not as a link: `dav-server` drops any entry
909 /// a listing reports as a symlink, and a sync client reads a file missing
910 /// from PROPFIND as a deletion to mirror.
911 fn broken_link(m: &std::fs::Metadata) -> Self {
912 Meta {
913 len: 0,
914 is_dir: false,
915 is_symlink: false,
916 ..Meta::of(m)
917 }
918 }
919
920 /// The mount point itself, which is not a directory on disk.
921 fn synthetic_dir() -> Self {
922 Meta {
923 len: 0,
924 modified: UNIX_EPOCH,
925 is_dir: true,
926 is_symlink: false,
927 }
928 }
929}
930
931impl DavMetaData for Meta {
932 fn len(&self) -> u64 {
933 self.len
934 }
935
936 fn modified(&self) -> FsResult<SystemTime> {
937 Ok(self.modified)
938 }
939
940 fn is_dir(&self) -> bool {
941 self.is_dir
942 }
943
944 fn is_symlink(&self) -> bool {
945 self.is_symlink
946 }
947}
948
949#[derive(Debug)]
950struct Entry {
951 name: Vec<u8>,
952 meta: Meta,
953}
954
955impl DavDirEntry for Entry {
956 fn name(&self) -> Vec<u8> {
957 self.name.clone()
958 }
959
960 fn metadata(&self) -> FsFuture<'_, Box<dyn DavMetaData>> {
961 let meta = self.meta.clone();
962 Box::pin(std::future::ready(Ok(
963 Box::new(meta) as Box<dyn DavMetaData>
964 )))
965 }
966}
967
968/// An open file. Plain async I/O: the path was already resolved and checked,
969/// so nothing here needs the blocking pool.
970#[derive(Debug)]
971struct File {
972 file: tokio::fs::File,
973 /// Held for the life of a writable handle. See [`WRITE_LOCKS`].
974 _write: Option<tokio::sync::OwnedMutexGuard<()>>,
975}
976
977/// Ceiling on one `read_bytes` allocation. `dav-server` asks for its own read
978/// buffer size, but the count reaches us from the request, and a short read is
979/// always a valid answer.
980const MAX_READ: usize = 64 * 1024;
981
982impl DavFile for File {
983 fn metadata(&mut self) -> FsFuture<'_, Box<dyn DavMetaData>> {
984 Box::pin(async move {
985 let m = self.file.metadata().await.map_err(|e| io_error(&e))?;
986 Ok(Box::new(Meta::of(&m)) as Box<dyn DavMetaData>)
987 })
988 }
989
990 fn write_buf(&mut self, mut buf: Box<dyn Buf + Send>) -> FsFuture<'_, ()> {
991 Box::pin(async move {
992 self.file
993 .write_all_buf(&mut buf)
994 .await
995 .map_err(|e| io_error(&e))
996 })
997 }
998
999 fn write_bytes(&mut self, buf: Bytes) -> FsFuture<'_, ()> {
1000 Box::pin(async move { self.file.write_all(&buf).await.map_err(|e| io_error(&e)) })
1001 }
1002
1003 fn read_bytes(&mut self, count: usize) -> FsFuture<'_, Bytes> {
1004 Box::pin(async move {
1005 let mut b = vec![0u8; count.min(MAX_READ)];
1006 let n = self.file.read(&mut b).await.map_err(|e| io_error(&e))?;
1007 b.truncate(n);
1008 Ok(Bytes::from(b))
1009 })
1010 }
1011
1012 fn seek(&mut self, pos: SeekFrom) -> FsFuture<'_, u64> {
1013 Box::pin(async move { self.file.seek(pos).await.map_err(|e| io_error(&e)) })
1014 }
1015
1016 fn flush(&mut self) -> FsFuture<'_, ()> {
1017 Box::pin(async move { self.file.flush().await.map_err(|e| io_error(&e)) })
1018 }
1019}
1020
1021// ---------------------------------------------------------------------------
1022// Errors and blocking work
1023// ---------------------------------------------------------------------------
1024
1025/// Run blocking filesystem work, mapping a panic or a shut-down runtime onto
1026/// a 500.
1027async fn blocking<T: Send + 'static>(
1028 f: impl FnOnce() -> FsResult<T> + Send + 'static,
1029) -> FsResult<T> {
1030 tokio::task::spawn_blocking(f)
1031 .await
1032 .map_err(|_| FsError::GeneralFailure)?
1033}
1034
1035fn fs_error(e: crate::fs::FsError) -> FsError {
1036 use crate::fs::FsError as E;
1037 match e {
1038 E::NotFound | E::RootMissing => FsError::NotFound,
1039 E::Conflict => FsError::Exists,
1040 // `Invalid` is a rejected name, which is a refusal, not a 400 here:
1041 // WebDAV has no status for "that name is not allowed".
1042 E::NotADirectory | E::Forbidden | E::Invalid(_) => FsError::Forbidden,
1043 }
1044}
1045
1046/// `dav-server` only derives this from `std::io::Error` when its own `localfs`
1047/// backend is compiled in, which it is not.
1048fn io_error(e: &std::io::Error) -> FsError {
1049 use std::io::ErrorKind as K;
1050 match e.kind() {
1051 K::NotFound => FsError::NotFound,
1052 K::PermissionDenied => FsError::Forbidden,
1053 K::AlreadyExists => FsError::Exists,
1054 K::CrossesDevices => FsError::IsRemote,
1055 // `read_dir` on a file. A refusal, not a server fault.
1056 K::NotADirectory => FsError::Forbidden,
1057 _ => FsError::GeneralFailure,
1058 }
1059}
1060