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