1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
//! Contains the structs and traits that define a filesystem backend.
//!
//! You only need this if you are going to implement your own
//! filesystem backend. Otherwise, just use 'LocalFs' or 'MemFs'.
//!
use std::fmt::Debug;
use std::io::SeekFrom;
use std::pin::Pin;
use std::time::{SystemTime, UNIX_EPOCH};
use futures_util::{future, Future, FutureExt, Stream, TryFutureExt};
use http::StatusCode;
use crate::davpath::DavPath;
macro_rules! notimplemented {
($method:expr) => {
Err(FsError::NotImplemented)
};
}
macro_rules! notimplemented_fut {
($method:expr) => {
Box::pin(future::ready(Err(FsError::NotImplemented)))
};
}
/// Errors generated by a filesystem implementation.
///
/// These are more result-codes than errors, really.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FsError {
/// Operation not implemented (501)
NotImplemented,
/// Something went wrong (500)
GeneralFailure,
/// tried to create something, but it existed (405 / 412) (yes, 405. RFC4918 says so)
Exists,
/// File / Directory not found (404)
NotFound,
/// Not allowed (403)
Forbidden,
/// Out of space (507)
InsufficientStorage,
/// Symbolic link loop detected (ELOOP) (508)
LoopDetected,
/// The path is too long (ENAMETOOLONG) (414)
PathTooLong,
/// The file being PUT is too large (413)
TooLarge,
/// Trying to MOVE over a mount boundary (EXDEV) (502)
IsRemote,
}
/// The Result type.
pub type FsResult<T> = std::result::Result<T, FsError>;
#[cfg(any(feature = "memfs", feature = "localfs"))]
impl From<&std::io::Error> for FsError {
fn from(e: &std::io::Error) -> Self {
use std::io::ErrorKind;
if let Some(errno) = e.raw_os_error() {
// specific errors.
match errno {
#[cfg(unix)]
libc::EMLINK | libc::ENOSPC | libc::EDQUOT => return FsError::InsufficientStorage,
#[cfg(windows)]
libc::EMLINK | libc::ENOSPC => return FsError::InsufficientStorage,
libc::EFBIG => return FsError::TooLarge,
libc::EACCES | libc::EPERM => return FsError::Forbidden,
libc::ENOTEMPTY | libc::EEXIST => return FsError::Exists,
libc::ELOOP => return FsError::LoopDetected,
libc::ENAMETOOLONG => return FsError::PathTooLong,
libc::ENOTDIR => return FsError::Forbidden,
libc::EISDIR => return FsError::Forbidden,
libc::EROFS => return FsError::Forbidden,
libc::ENOENT => return FsError::NotFound,
libc::ENOSYS => return FsError::NotImplemented,
libc::EXDEV => return FsError::IsRemote,
_ => {}
}
} else {
// not an OS error - must be "not implemented"
// (e.g. metadata().created() on systems without st_crtime)
return FsError::NotImplemented;
}
// generic mappings for-whatever is left.
match e.kind() {
ErrorKind::NotFound => FsError::NotFound,
ErrorKind::PermissionDenied => FsError::Forbidden,
_ => FsError::GeneralFailure,
}
}
}
#[cfg(any(feature = "memfs", feature = "localfs"))]
impl From<std::io::Error> for FsError {
fn from(e: std::io::Error) -> Self {
(&e).into()
}
}
/// A webdav property.
#[derive(Debug, Clone)]
pub struct DavProp {
/// Name of the property.
pub name: String,
/// XML prefix.
pub prefix: Option<String>,
/// XML namespace.
pub namespace: Option<String>,
/// Value of the property as raw XML.
pub xml: Option<Vec<u8>>,
}
/// Future returned by almost all of the DavFileSystem methods.
pub type FsFuture<'a, T> = Pin<Box<dyn Future<Output = FsResult<T>> + Send + 'a>>;
/// Convenience alias for a boxed Stream.
pub type FsStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
/// Used as argument to the read_dir() method.
/// It is:
///
/// - an optimization hint (the implementation may call metadata() and
/// store the result in the returned directory entry)
/// - a way to get metadata instead of symlink_metadata from
/// the directory entry.
///
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadDirMeta {
/// DavDirEntry.metadata() behaves as metadata()
Data,
/// DavDirEntry.metadata() behaves as symlink_metadata()
DataSymlink,
/// No optimizations, otherwise like DataSymlink.
None,
}
/// The trait that defines a filesystem.
pub trait DavFileSystem: Sync + Send + BoxCloneFs {
/// Open a file.
fn open<'a>(&'a self, path: &'a DavPath, options: OpenOptions) -> FsFuture<Box<dyn DavFile>>;
/// Perform read_dir.
fn read_dir<'a>(
&'a self,
path: &'a DavPath,
meta: ReadDirMeta,
) -> FsFuture<FsStream<Box<dyn DavDirEntry>>>;
/// Return the metadata of a file or directory.
fn metadata<'a>(&'a self, path: &'a DavPath) -> FsFuture<Box<dyn DavMetaData>>;
/// Return the metadata of a file, directory or symbolic link.
///
/// Differs from metadata() that if the path is a symbolic link,
/// it return the metadata for the link itself, not for the thing
/// it points to.
///
/// The default implementation returns FsError::NotImplemented.
#[allow(unused_variables)]
fn symlink_metadata<'a>(&'a self, path: &'a DavPath) -> FsFuture<Box<dyn DavMetaData>> {
self.metadata(path)
}
/// Create a directory.
///
/// The default implementation returns FsError::NotImplemented.
#[allow(unused_variables)]
fn create_dir<'a>(&'a self, path: &'a DavPath) -> FsFuture<()> {
notimplemented_fut!("create_dir")
}
/// Remove a directory.
///
/// The default implementation returns FsError::NotImplemented.
#[allow(unused_variables)]
fn remove_dir<'a>(&'a self, path: &'a DavPath) -> FsFuture<()> {
notimplemented_fut!("remove_dir")
}
/// Remove a file.
///
/// The default implementation returns FsError::NotImplemented.
#[allow(unused_variables)]
fn remove_file<'a>(&'a self, path: &'a DavPath) -> FsFuture<()> {
notimplemented_fut!("remove_file")
}
/// Rename a file or directory.
///
/// Source and destination must be the same type (file/dir).
/// If the destination already exists and is a file, it
/// should be replaced. If it is a directory it should give
/// an error.
///
/// The default implementation returns FsError::NotImplemented.
#[allow(unused_variables)]
fn rename<'a>(&'a self, from: &'a DavPath, to: &'a DavPath) -> FsFuture<()> {
notimplemented_fut!("rename")
}
/// Copy a file
///
/// Should also copy the DAV properties, if properties
/// are implemented.
///
/// The default implementation returns FsError::NotImplemented.
#[allow(unused_variables)]
fn copy<'a>(&'a self, from: &'a DavPath, to: &'a DavPath) -> FsFuture<()> {
notimplemented_fut!("copy")
}
/// Set the access time of a file / directory.
///
/// The default implementation returns FsError::NotImplemented.
#[doc(hidden)]
#[allow(unused_variables)]
fn set_accessed<'a>(&'a self, path: &'a DavPath, tm: SystemTime) -> FsFuture<()> {
notimplemented_fut!("set_accessed")
}
/// Set the modified time of a file / directory.
///
/// The default implementation returns FsError::NotImplemented.
#[doc(hidden)]
#[allow(unused_variables)]
fn set_modified<'a>(&'a self, path: &'a DavPath, tm: SystemTime) -> FsFuture<()> {
notimplemented_fut!("set_mofified")
}
/// Indicator that tells if this filesystem driver supports DAV properties.
///
/// The default implementation returns `false`.
#[allow(unused_variables)]
fn have_props<'a>(
&'a self,
path: &'a DavPath,
) -> Pin<Box<dyn Future<Output = bool> + Send + 'a>> {
Box::pin(future::ready(false))
}
/// Patch the DAV properties of a node (add/remove props)
///
/// The default implementation returns FsError::NotImplemented.
#[allow(unused_variables)]
fn patch_props<'a>(
&'a self,
path: &'a DavPath,
patch: Vec<(bool, DavProp)>,
) -> FsFuture<Vec<(StatusCode, DavProp)>> {
notimplemented_fut!("patch_props")
}
/// List/get the DAV properties of a node.
///
/// The default implementation returns FsError::NotImplemented.
#[allow(unused_variables)]
fn get_props<'a>(&'a self, path: &'a DavPath, do_content: bool) -> FsFuture<Vec<DavProp>> {
notimplemented_fut!("get_props")
}
/// Get one specific named property of a node.
///
/// The default implementation returns FsError::NotImplemented.
#[allow(unused_variables)]
fn get_prop<'a>(&'a self, path: &'a DavPath, prop: DavProp) -> FsFuture<Vec<u8>> {
notimplemented_fut!("get_prop`")
}
/// Get quota of this filesystem (used/total space).
///
/// The first value returned is the amount of space used,
/// the second optional value is the total amount of space
/// (used + available).
///
/// The default implementation returns FsError::NotImplemented.
#[allow(unused_variables)]
fn get_quota(&self) -> FsFuture<(u64, Option<u64>)> {
notimplemented_fut!("get_quota`")
}
}
// BoxClone trait.
#[doc(hidden)]
pub trait BoxCloneFs {
fn box_clone(&self) -> Box<dyn DavFileSystem>;
}
// generic Clone, calls implementation-specific box_clone().
impl Clone for Box<dyn DavFileSystem> {
fn clone(&self) -> Box<dyn DavFileSystem> {
self.box_clone()
}
}
// implementation-specific clone.
#[doc(hidden)]
impl<FS: Clone + DavFileSystem + 'static> BoxCloneFs for FS {
fn box_clone(&self) -> Box<dyn DavFileSystem> {
Box::new((*self).clone())
}
}
/// One directory entry (or child node).
pub trait DavDirEntry: Send + Sync {
/// Name of the entry.
fn name(&self) -> Vec<u8>;
/// Metadata of the entry.
fn metadata(&self) -> FsFuture<Box<dyn DavMetaData>>;
/// Default implementation of `is_dir` just returns `metadata()?.is_dir()`.
/// Implementations can override this if their `metadata()` method is
/// expensive and there is a cheaper way to provide the same info
/// (e.g. dirent.d_type in unix filesystems).
fn is_dir(&self) -> FsFuture<bool> {
Box::pin(self.metadata().and_then(|meta| future::ok(meta.is_dir())))
}
/// Likewise. Default: `!is_dir()`.
fn is_file(&self) -> FsFuture<bool> {
Box::pin(self.metadata().and_then(|meta| future::ok(meta.is_file())))
}
/// Likewise. Default: `false`.
fn is_symlink(&self) -> FsFuture<bool> {
Box::pin(
self.metadata()
.and_then(|meta| future::ok(meta.is_symlink())),
)
}
}
/// A `DavFile` is the equivalent of `std::fs::File`, should be
/// readable/writeable/seekable, and be able to return its metadata.
pub trait DavFile: Debug + Send + Sync {
fn metadata(&mut self) -> FsFuture<Box<dyn DavMetaData>>;
fn write_buf(&mut self, buf: Box<dyn bytes::Buf + Send>) -> FsFuture<()>;
fn write_bytes(&mut self, buf: bytes::Bytes) -> FsFuture<()>;
fn read_bytes(&mut self, count: usize) -> FsFuture<bytes::Bytes>;
fn seek(&mut self, pos: SeekFrom) -> FsFuture<u64>;
fn flush(&mut self) -> FsFuture<()>;
fn redirect_url(&mut self) -> FsFuture<Option<String>> {
future::ready(Ok(None)).boxed()
}
}
/// File metadata. Basically type, length, and some timestamps.
pub trait DavMetaData: Debug + BoxCloneMd + Send + Sync {
/// Size of the file.
fn len(&self) -> u64;
/// `Modified` timestamp.
fn modified(&self) -> FsResult<SystemTime>;
/// File or directory (aka collection).
fn is_dir(&self) -> bool;
/// Simplistic implementation of `etag()`
///
/// Returns a simple etag that basically is `\<length\>-\<timestamp_in_ms\>`
/// with the numbers in hex. Enough for most implementations.
fn etag(&self) -> Option<String> {
if let Ok(t) = self.modified() {
if let Ok(t) = t.duration_since(UNIX_EPOCH) {
let t = t.as_secs() * 1000000 + t.subsec_nanos() as u64 / 1000;
let tag = if self.is_file() && self.len() > 0 {
format!("{:x}-{:x}", self.len(), t)
} else {
format!("{:x}", t)
};
return Some(tag);
}
}
None
}
/// Is this a file and not a directory. Default: `!s_dir()`.
fn is_file(&self) -> bool {
!self.is_dir()
}
/// Is this a symbolic link. Default: false.
fn is_symlink(&self) -> bool {
false
}
/// Last access time. Default: `FsError::NotImplemented`.
fn accessed(&self) -> FsResult<SystemTime> {
notimplemented!("access time")
}
/// Creation time. Default: `FsError::NotImplemented`.
fn created(&self) -> FsResult<SystemTime> {
notimplemented!("creation time")
}
/// Inode change time (ctime). Default: `FsError::NotImplemented`.
fn status_changed(&self) -> FsResult<SystemTime> {
notimplemented!("status change time")
}
/// Is file executable (unix: has "x" mode bit). Default: `FsError::NotImplemented`.
fn executable(&self) -> FsResult<bool> {
notimplemented!("executable")
}
// Is empty file
fn is_empty(&self) -> bool {
self.len() == 0
}
}
// generic Clone, calls implementation-specific box_clone().
impl Clone for Box<dyn DavMetaData> {
fn clone(&self) -> Box<dyn DavMetaData> {
self.box_clone()
}
}
// BoxCloneMd trait.
#[doc(hidden)]
pub trait BoxCloneMd {
fn box_clone(&self) -> Box<dyn DavMetaData>;
}
// implementation-specific clone.
#[doc(hidden)]
impl<MD: Clone + DavMetaData + 'static> BoxCloneMd for MD {
fn box_clone(&self) -> Box<dyn DavMetaData> {
Box::new((*self).clone())
}
}
/// OpenOptions for `open()`.
#[derive(Debug, Clone, Default)]
pub struct OpenOptions {
/// open for reading
pub read: bool,
/// open for writing
pub write: bool,
/// open in write-append mode
pub append: bool,
/// truncate file first when writing
pub truncate: bool,
/// create file if it doesn't exist
pub create: bool,
/// must create new file, fail if it already exists.
pub create_new: bool,
/// write file total size
pub size: Option<u64>,
/// checksum, owncloud extension
pub checksum: Option<String>,
}
impl OpenOptions {
#[allow(dead_code)]
pub(crate) fn new() -> OpenOptions {
OpenOptions {
read: false,
write: false,
append: false,
truncate: false,
create: false,
create_new: false,
size: None,
checksum: None,
}
}
pub(crate) fn read() -> OpenOptions {
OpenOptions {
read: true,
write: false,
append: false,
truncate: false,
create: false,
create_new: false,
size: None,
checksum: None,
}
}
pub(crate) fn write() -> OpenOptions {
OpenOptions {
read: false,
write: true,
append: false,
truncate: false,
create: false,
create_new: false,
size: None,
checksum: None,
}
}
}
impl std::error::Error for FsError {
fn description(&self) -> &str {
"DavFileSystem error"
}
fn cause(&self) -> Option<&dyn std::error::Error> {
None
}
}
impl std::fmt::Display for FsError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}