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
use crate::storage::{Error, ErrorKind, Fileinfo, Metadata, Result, StorageBackend};
use async_trait::async_trait;
use futures::prelude::*;
use std::{
fmt::Debug,
path::{Path, PathBuf},
time::SystemTime,
};
#[derive(Debug)]
pub struct Filesystem {
root: PathBuf,
}
fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
use path_abs::PathAbs;
let p = PathAbs::new(path).map_err(|_| Error::from(ErrorKind::FileNameNotAllowedError))?;
Ok(p.as_path().to_path_buf())
}
impl Filesystem {
pub fn new<P: Into<PathBuf>>(root: P) -> Self {
let path = root.into();
Filesystem {
root: canonicalize(&path).unwrap_or(path),
}
}
async fn full_path<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf> {
let path = path.as_ref();
let full_path = if path.starts_with("/") {
self.root.join(path.strip_prefix("/").unwrap())
} else {
self.root.join(path)
};
let real_full_path = tokio::task::spawn_blocking(move || canonicalize(full_path))
.await
.map_err(|e| Error::new(ErrorKind::LocalError, e))??;
if real_full_path.starts_with(&self.root) {
Ok(real_full_path)
} else {
Err(Error::from(ErrorKind::PermanentFileNotAvailable))
}
}
}
#[async_trait]
impl<U: Send + Sync + Debug> StorageBackend<U> for Filesystem {
type Metadata = std::fs::Metadata;
fn supported_features(&self) -> u32 {
crate::storage::FEATURE_RESTART
}
#[tracing_attributes::instrument]
async fn metadata<P: AsRef<Path> + Send + Debug>(&self, _user: &Option<U>, path: P) -> Result<Self::Metadata> {
let full_path = self.full_path(path).await?;
tokio::fs::symlink_metadata(full_path)
.await
.map_err(|_| Error::from(ErrorKind::PermanentFileNotAvailable))
}
#[allow(clippy::type_complexity)]
#[tracing_attributes::instrument]
async fn list<P>(&self, _user: &Option<U>, path: P) -> Result<Vec<Fileinfo<std::path::PathBuf, Self::Metadata>>>
where
P: AsRef<Path> + Send + Debug,
<Self as StorageBackend<U>>::Metadata: Metadata,
{
let full_path: PathBuf = self.full_path(path).await?;
let prefix: PathBuf = self.root.clone();
let mut rd: tokio::fs::ReadDir = tokio::fs::read_dir(full_path).await?;
let mut fis: Vec<Fileinfo<std::path::PathBuf, Self::Metadata>> = vec![];
while let Ok(Some(dir_entry)) = rd.next_entry().await {
let prefix = prefix.clone();
let path = dir_entry.path();
let relpath = path.strip_prefix(prefix).unwrap();
let relpath: PathBuf = std::path::PathBuf::from(relpath);
let meta: Self::Metadata = tokio::fs::symlink_metadata(dir_entry.path()).await?;
fis.push(Fileinfo { path: relpath, metadata: meta })
}
Ok(fis)
}
async fn get<P: AsRef<Path> + Send + Debug>(
&self,
_user: &Option<U>,
path: P,
start_pos: u64,
) -> Result<Box<dyn tokio::io::AsyncRead + Send + Sync + Unpin>> {
use tokio::io::AsyncSeekExt;
let full_path = self.full_path(path).await?;
async move {
let mut file = tokio::fs::File::open(full_path).await?;
if start_pos > 0 {
file.seek(std::io::SeekFrom::Start(start_pos)).await?;
}
Ok(Box::new(tokio::io::BufReader::with_capacity(4096, file)) as Box<dyn tokio::io::AsyncRead + Send + Sync + Unpin>)
}
.map_err(|error: std::io::Error| error.into())
.await
}
async fn put<P: AsRef<Path> + Send, R: tokio::io::AsyncRead + Send + Sync + 'static + Unpin>(
&self,
_user: &Option<U>,
bytes: R,
path: P,
start_pos: u64,
) -> Result<u64> {
use tokio::io::AsyncSeekExt;
let path = path.as_ref();
let full_path = if path.starts_with("/") {
self.root.join(path.strip_prefix("/").unwrap())
} else {
self.root.join(path)
};
let mut file = tokio::fs::OpenOptions::new().write(true).create(true).open(full_path).await?;
file.set_len(start_pos).await?;
file.seek(std::io::SeekFrom::Start(start_pos)).await?;
let mut reader = tokio::io::BufReader::with_capacity(4096, bytes);
let mut writer = tokio::io::BufWriter::with_capacity(4096, file);
let bytes_copied = tokio::io::copy(&mut reader, &mut writer).await?;
Ok(bytes_copied)
}
#[tracing_attributes::instrument]
async fn del<P: AsRef<Path> + Send + Debug>(&self, _user: &Option<U>, path: P) -> Result<()> {
let full_path = self.full_path(path).await?;
tokio::fs::remove_file(full_path).await.map_err(|error: std::io::Error| error.into())
}
#[tracing_attributes::instrument]
async fn rmd<P: AsRef<Path> + Send + Debug>(&self, _user: &Option<U>, path: P) -> Result<()> {
let full_path = self.full_path(path).await?;
tokio::fs::remove_dir(full_path).await.map_err(|error: std::io::Error| error.into())
}
#[tracing_attributes::instrument]
async fn mkd<P: AsRef<Path> + Send + Debug>(&self, _user: &Option<U>, path: P) -> Result<()> {
tokio::fs::create_dir(self.full_path(path).await?)
.await
.map_err(|error: std::io::Error| error.into())
}
#[tracing_attributes::instrument]
async fn rename<P: AsRef<Path> + Send + Debug>(&self, _user: &Option<U>, from: P, to: P) -> Result<()> {
let from = self.full_path(from).await?;
let to = self.full_path(to).await?;
let from_rename = from.clone();
let r = tokio::fs::symlink_metadata(from).await;
match r {
Ok(metadata) => {
if metadata.is_file() || metadata.is_dir() {
let r = tokio::fs::rename(from_rename, to).await;
match r {
Ok(_) => Ok(()),
Err(e) => Err(Error::new(ErrorKind::PermanentFileNotAvailable, e)),
}
} else {
Err(Error::from(ErrorKind::PermanentFileNotAvailable))
}
}
Err(e) => Err(Error::new(ErrorKind::PermanentFileNotAvailable, e)),
}
}
#[tracing_attributes::instrument]
async fn cwd<P: AsRef<Path> + Send + Debug>(&self, _user: &Option<U>, path: P) -> Result<()> {
let full_path = self.full_path(path).await?;
tokio::fs::read_dir(full_path).await.map_err(|error: std::io::Error| error.into()).map(|_| ())
}
}
impl Metadata for std::fs::Metadata {
fn len(&self) -> u64 {
self.len()
}
fn is_dir(&self) -> bool {
self.is_dir()
}
fn is_file(&self) -> bool {
self.is_file()
}
fn is_symlink(&self) -> bool {
self.file_type().is_symlink()
}
fn modified(&self) -> Result<SystemTime> {
self.modified().map_err(|e| e.into())
}
fn gid(&self) -> u32 {
0
}
fn uid(&self) -> u32 {
0
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::DefaultUser;
use pretty_assertions::assert_eq;
use std::fs::File;
use std::io::prelude::*;
use std::io::Write;
use tokio::runtime::Runtime;
#[test]
fn fs_stat() {
let root = std::env::temp_dir();
let file = tempfile::NamedTempFile::new_in(&root).unwrap();
let path = file.path();
let file = file.as_file();
let meta = file.metadata().unwrap();
let fs = Filesystem::new(&root);
let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
let filename = path.file_name().unwrap();
let my_meta = rt.block_on(fs.metadata(&Some(DefaultUser {}), filename)).unwrap();
assert_eq!(meta.is_dir(), my_meta.is_dir());
assert_eq!(meta.is_file(), my_meta.is_file());
assert_eq!(meta.is_symlink(), my_meta.is_symlink());
assert_eq!(meta.len(), my_meta.len());
assert_eq!(meta.modified().unwrap(), my_meta.modified().unwrap());
}
#[test]
fn fs_list() {
let root = tempfile::tempdir().unwrap();
let file = tempfile::NamedTempFile::new_in(&root.path()).unwrap();
let path = file.path();
let relpath = path.strip_prefix(&root.path()).unwrap();
let file = file.as_file();
let meta = file.metadata().unwrap();
let fs = Filesystem::new(&root.path());
let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
let my_list = rt.block_on(fs.list(&Some(DefaultUser {}), "/")).unwrap();
assert_eq!(my_list.len(), 1);
let my_fileinfo = &my_list[0];
assert_eq!(my_fileinfo.path, relpath);
assert_eq!(my_fileinfo.metadata.is_dir(), meta.is_dir());
assert_eq!(my_fileinfo.metadata.is_file(), meta.is_file());
assert_eq!(my_fileinfo.metadata.is_symlink(), meta.is_symlink());
assert_eq!(my_fileinfo.metadata.len(), meta.len());
assert_eq!(my_fileinfo.metadata.modified().unwrap(), meta.modified().unwrap());
}
#[test]
fn fs_list_fmt() {
let root = tempfile::tempdir().unwrap();
let file = tempfile::NamedTempFile::new_in(&root.path()).unwrap();
let path = file.path();
let relpath = path.strip_prefix(&root.path()).unwrap();
let fs = Filesystem::new(&root.path());
let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
let my_list = rt.block_on(fs.list_fmt(&Some(DefaultUser {}), "/")).unwrap();
let my_list = std::string::String::from_utf8(my_list.into_inner()).unwrap();
assert!(my_list.contains(relpath.to_str().unwrap()));
}
#[test]
fn fs_get() {
let root = std::env::temp_dir();
let mut file = tempfile::NamedTempFile::new_in(&root).unwrap();
let path = file.path().to_owned();
let data = b"Koen was here\n";
file.write_all(data).unwrap();
let filename = path.file_name().unwrap();
let fs = Filesystem::new(&root);
let rt = Runtime::new().unwrap();
let mut my_file = rt.block_on(fs.get(&Some(DefaultUser {}), filename, 0)).unwrap();
let mut my_content = Vec::new();
rt.block_on(async move {
let r = tokio::io::copy(&mut my_file, &mut my_content).await;
if r.is_err() {
return Err(());
}
assert_eq!(data.as_ref(), &*my_content);
if true {
Ok(())
} else {
Err(())
}
})
.unwrap();
}
#[test]
fn fs_put() {
let root = std::env::temp_dir();
let orig_content = b"hallo";
let fs = Filesystem::new(&root);
let rt = Runtime::new().unwrap();
rt.block_on(fs.put(&Some(DefaultUser {}), orig_content.as_ref(), "greeting.txt", 0))
.expect("Failed to `put` file");
let mut written_content = Vec::new();
let mut f = File::open(root.join("greeting.txt")).unwrap();
f.read_to_end(&mut written_content).unwrap();
assert_eq!(orig_content, written_content.as_slice());
}
#[test]
fn fileinfo_fmt() {
struct MockMetadata {};
impl Metadata for MockMetadata {
fn len(&self) -> u64 {
5
}
fn is_empty(&self) -> bool {
false
}
fn is_dir(&self) -> bool {
false
}
fn is_file(&self) -> bool {
true
}
fn is_symlink(&self) -> bool {
false
}
fn modified(&self) -> Result<SystemTime> {
Ok(std::time::SystemTime::UNIX_EPOCH)
}
fn uid(&self) -> u32 {
0
}
fn gid(&self) -> u32 {
0
}
}
let dir = std::env::temp_dir();
let meta = MockMetadata {};
let fileinfo = Fileinfo {
path: dir.to_str().unwrap(),
metadata: meta,
};
let my_format = format!("{}", fileinfo);
let basename = std::path::Path::new(&dir).file_name().unwrap().to_string_lossy();
let format = format!("-rwxr-xr-x 0 0 5 Jan 01 00:00 {}", basename);
assert_eq!(my_format, format);
}
#[test]
fn fs_mkd() {
let root = tempfile::TempDir::new().unwrap().into_path();
let fs = Filesystem::new(&root);
let new_dir_name = "bla";
let rt = Runtime::new().unwrap();
rt.block_on(fs.mkd(&Some(DefaultUser {}), new_dir_name)).expect("Failed to mkd");
let full_path = root.join(new_dir_name);
let metadata = std::fs::symlink_metadata(full_path).unwrap();
assert!(metadata.is_dir());
}
#[test]
fn fs_rename_file() {
let root = tempfile::TempDir::new().unwrap().into_path();
let file = tempfile::NamedTempFile::new_in(&root).unwrap();
let old_filename = file.path().file_name().unwrap().to_str().unwrap();
let new_filename = "hello.txt";
let rt = Runtime::new().unwrap();
let fs = Filesystem::new(&root);
let r = rt.block_on(fs.rename(&Some(DefaultUser {}), &old_filename, &new_filename));
assert!(r.is_ok());
let new_full_path = root.join(new_filename);
assert!(std::fs::metadata(new_full_path).expect("new filename not found").is_file());
let old_full_path = root.join(old_filename);
std::fs::symlink_metadata(old_full_path).expect_err("Old filename should not exists anymore");
}
#[test]
fn fs_rename_dir() {
let root = tempfile::TempDir::new().unwrap().into_path();
let dir = tempfile::TempDir::new_in(&root).unwrap();
let old_dir = dir.path().file_name().unwrap().to_str().unwrap();
let new_dir = "new-dir";
let rt = Runtime::new().unwrap();
let fs = Filesystem::new(&root);
let r = rt.block_on(fs.rename(&Some(DefaultUser {}), &old_dir, &new_dir));
assert!(r.is_ok());
let new_full_path = root.join(new_dir);
assert!(std::fs::metadata(new_full_path).expect("new directory not found").is_dir());
let old_full_path = root.join(old_dir);
std::fs::symlink_metadata(old_full_path).expect_err("Old directory should not exists anymore");
}
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Self {
match err.kind() {
std::io::ErrorKind::NotFound => Error::from(ErrorKind::PermanentFileNotAvailable),
std::io::ErrorKind::PermissionDenied => Error::from(ErrorKind::PermissionDenied),
_ => Error::new(ErrorKind::LocalError, err),
}
}
}