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