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