1use fuser::{
4 BsdFileFlags, Errno, FileHandle, FileType, FopenFlags, INodeNo, RenameFlags, ReplyAttr,
5 ReplyCreate, ReplyData, ReplyDirectory, ReplyEmpty, ReplyEntry, ReplyWrite, TimeOrNow,
6};
7use std::ffi::OsStr;
8use std::fs;
9use std::os::unix::fs::MetadataExt;
10use std::time::SystemTime;
11use tracing::{info, warn};
12
13use super::{GENERATION, RagFs, TTL, reply_file_bytes};
14use crate::inode::{FIRST_REAL_INO, InodeKind, RAGFS_DIR_INO, ROOT_INO};
15
16impl RagFs {
17 pub(crate) fn lookup_root(&self, name_str: &str, reply: ReplyEntry) {
18 if name_str == ".ragfs" {
19 let attr = self.make_attr(RAGFS_DIR_INO, FileType::Directory, 0);
20 reply.entry(&TTL, &attr, GENERATION);
21 return;
22 }
23
24 let real_path = self.source.join(name_str);
25 if real_path.exists() {
26 let metadata = if let Ok(m) = fs::metadata(&real_path) {
27 m
28 } else {
29 reply.error(Errno::ENOENT);
30 return;
31 };
32
33 let mut inodes = self.runtime.block_on(self.inodes.write());
34 let ino = inodes.get_or_create_real(real_path.clone(), metadata.ino());
35 drop(inodes);
36
37 if let Some(attr) = self.real_path_to_attr(&real_path, ino) {
38 reply.entry(&TTL, &attr, GENERATION);
39 return;
40 }
41 }
42
43 reply.error(Errno::ENOENT);
44 }
45
46 pub(crate) fn lookup_passthrough(&self, parent: u64, name_str: &str, reply: ReplyEntry) {
47 let inodes = self.runtime.block_on(self.inodes.read());
48 if let Some(entry) = inodes.get(parent)
49 && let InodeKind::Real { path, .. } = &entry.kind
50 {
51 let real_path = path.join(name_str);
52 if real_path.exists() {
53 drop(inodes);
54 let metadata = if let Ok(m) = fs::metadata(&real_path) {
55 m
56 } else {
57 reply.error(Errno::ENOENT);
58 return;
59 };
60
61 let mut inodes = self.runtime.block_on(self.inodes.write());
62 let ino = inodes.get_or_create_real(real_path.clone(), metadata.ino());
63 drop(inodes);
64
65 if let Some(attr) = self.real_path_to_attr(&real_path, ino) {
66 reply.entry(&TTL, &attr, GENERATION);
67 return;
68 }
69 }
70 }
71
72 reply.error(Errno::ENOENT);
73 }
74
75 pub(crate) fn getattr_cached_or_passthrough(&self, ino: u64, reply: ReplyAttr) {
76 let cache = self.runtime.block_on(self.content_cache.read());
77 if let Some(content) = cache.get(&ino) {
78 let attr = self.make_attr(ino, FileType::RegularFile, content.len() as u64);
79 reply.attr(&TTL, &attr);
80 return;
81 }
82 drop(cache);
83
84 let inodes = self.runtime.block_on(self.inodes.read());
85 if let Some(entry) = inodes.get(ino)
86 && let InodeKind::Real { path, .. } = &entry.kind
87 && let Some(attr) = self.real_path_to_attr(path, ino)
88 {
89 reply.attr(&TTL, &attr);
90 return;
91 }
92 reply.error(Errno::ENOENT);
93 }
94
95 pub(crate) fn read_passthrough(&self, ino: u64, offset: u64, size: u32, reply: ReplyData) {
96 let inodes = self.runtime.block_on(self.inodes.read());
97 if let Some(entry) = inodes.get(ino)
98 && let InodeKind::Real { path, .. } = &entry.kind
99 {
100 let path = path.clone();
101 drop(inodes);
102
103 match fs::read(&path) {
104 Ok(content) => {
105 reply_file_bytes(reply, &content, offset, size);
106 return;
107 }
108 Err(e) => {
109 warn!("Failed to read file {:?}: {}", path, e);
110 reply.error(Errno::EIO);
111 return;
112 }
113 }
114 }
115
116 reply.error(Errno::ENOENT);
117 }
118
119 pub(crate) fn readdir_root(&self, offset: u64, mut reply: ReplyDirectory) {
120 let mut entries = vec![
121 (ROOT_INO, FileType::Directory, ".".to_string()),
122 (ROOT_INO, FileType::Directory, "..".to_string()),
123 (RAGFS_DIR_INO, FileType::Directory, ".ragfs".to_string()),
124 ];
125
126 if let Ok(read_dir) = fs::read_dir(&self.source) {
127 for entry in read_dir.flatten() {
128 let name = entry.file_name().to_string_lossy().to_string();
129 if name.starts_with('.') {
130 continue;
131 }
132 let file_type = if entry.path().is_dir() {
133 FileType::Directory
134 } else {
135 FileType::RegularFile
136 };
137
138 let metadata = match entry.metadata() {
139 Ok(m) => m,
140 Err(_) => continue,
141 };
142
143 let mut inodes = self.runtime.block_on(self.inodes.write());
144 let entry_ino = inodes.get_or_create_real(entry.path(), metadata.ino());
145 entries.push((entry_ino, file_type, name));
146 }
147 }
148
149 for (i, (ino, kind, name)) in entries.iter().enumerate().skip(offset as usize) {
150 if reply.add(INodeNo(*ino), (i + 1) as u64, *kind, name) {
151 break;
152 }
153 }
154 reply.ok();
155 }
156
157 pub(crate) fn readdir_passthrough(&self, ino: u64, offset: u64, mut reply: ReplyDirectory) {
158 let inodes = self.runtime.block_on(self.inodes.read());
159 if let Some(entry) = inodes.get(ino)
160 && let InodeKind::Real { path, .. } = &entry.kind
161 {
162 let path = path.clone();
163 let parent_ino = entry.parent;
164 drop(inodes);
165
166 if path.is_dir() {
167 let mut entries = vec![
168 (ino, FileType::Directory, ".".to_string()),
169 (parent_ino, FileType::Directory, "..".to_string()),
170 ];
171
172 if let Ok(read_dir) = fs::read_dir(&path) {
173 for dir_entry in read_dir.flatten() {
174 let name = dir_entry.file_name().to_string_lossy().to_string();
175 if name.starts_with('.') {
176 continue;
177 }
178 let file_type = if dir_entry.path().is_dir() {
179 FileType::Directory
180 } else {
181 FileType::RegularFile
182 };
183
184 let metadata = match dir_entry.metadata() {
185 Ok(m) => m,
186 Err(_) => continue,
187 };
188
189 let mut inodes = self.runtime.block_on(self.inodes.write());
190 let entry_ino = inodes.get_or_create_real(dir_entry.path(), metadata.ino());
191 entries.push((entry_ino, file_type, name));
192 }
193 }
194
195 for (i, (entry_ino, kind, name)) in entries.iter().enumerate().skip(offset as usize)
196 {
197 if reply.add(INodeNo(*entry_ino), (i + 1) as u64, *kind, name) {
198 break;
199 }
200 }
201 reply.ok();
202 return;
203 }
204 }
205 reply.error(Errno::ENOENT);
206 }
207
208 pub(crate) fn write_passthrough(&self, ino: u64, data: &[u8], reply: ReplyWrite) {
209 let inodes = self.runtime.block_on(self.inodes.read());
210 if let Some(entry) = inodes.get(ino)
211 && let InodeKind::Real { path, .. } = &entry.kind
212 {
213 let path = path.clone();
214 drop(inodes);
215
216 match fs::write(&path, data) {
217 Ok(()) => {
218 reply.written(data.len() as u32);
219 return;
220 }
221 Err(e) => {
222 warn!("Failed to write file {:?}: {}", path, e);
223 reply.error(Errno::EIO);
224 return;
225 }
226 }
227 }
228
229 reply.error(Errno::ENOSYS);
230 }
231
232 pub(crate) fn create_passthrough(
233 &self,
234 parent: u64,
235 name: &OsStr,
236 mode: u32,
237 _umask: u32,
238 flags: i32,
239 reply: ReplyCreate,
240 ) {
241 let name_str = name.to_string_lossy();
242 tracing::debug!(
243 "create: parent={}, name={}, mode={:o}",
244 parent,
245 name_str,
246 mode
247 );
248
249 if parent < FIRST_REAL_INO && parent != ROOT_INO {
250 reply.error(Errno::EPERM);
251 return;
252 }
253
254 let Some(parent_path) = self.resolve_parent_path(parent) else {
255 reply.error(Errno::ENOENT);
256 return;
257 };
258
259 let new_path = parent_path.join(&*name_str);
260
261 if new_path.exists() {
262 reply.error(Errno::EEXIST);
263 return;
264 }
265
266 match fs::File::create(&new_path) {
267 Ok(_) => {
268 let metadata = match fs::metadata(&new_path) {
269 Ok(m) => m,
270 Err(e) => {
271 warn!("Failed to get metadata for new file {:?}: {}", new_path, e);
272 reply.error(Errno::EIO);
273 return;
274 }
275 };
276
277 let mut inodes = self.runtime.block_on(self.inodes.write());
278 let ino = inodes.get_or_create_real(new_path.clone(), metadata.ino());
279 drop(inodes);
280
281 if let Some(ref sender) = self.reindex_sender {
282 let sender = sender.clone();
283 let path_to_send = new_path.clone();
284 self.runtime.spawn(async move {
285 if let Err(e) = sender.send(path_to_send).await {
286 warn!("Failed to send reindex request: {}", e);
287 }
288 });
289 }
290
291 if let Some(attr) = self.real_path_to_attr(&new_path, ino) {
292 reply.created(
293 &TTL,
294 &attr,
295 GENERATION,
296 FileHandle(0),
297 FopenFlags::from_bits_retain(flags as u32),
298 );
299 } else {
300 reply.error(Errno::EIO);
301 }
302 }
303 Err(e) => {
304 warn!("Failed to create file {:?}: {}", new_path, e);
305 reply.error(Errno::EIO);
306 }
307 }
308 }
309
310 pub(crate) fn unlink_passthrough(&self, parent: u64, name: &OsStr, reply: ReplyEmpty) {
311 let name_str = name.to_string_lossy();
312 tracing::debug!("unlink: parent={}, name={}", parent, name_str);
313
314 if parent < FIRST_REAL_INO && parent != ROOT_INO {
315 reply.error(Errno::EPERM);
316 return;
317 }
318
319 let Some(parent_path) = self.resolve_parent_path(parent) else {
320 reply.error(Errno::ENOENT);
321 return;
322 };
323
324 let file_path = parent_path.join(&*name_str);
325
326 if !file_path.exists() {
327 reply.error(Errno::ENOENT);
328 return;
329 }
330
331 if file_path.is_dir() {
332 reply.error(Errno::EISDIR);
333 return;
334 }
335
336 if let Some(ref store) = self.store {
337 let store = store.clone();
338 let path_for_delete = file_path.clone();
339 let result = self
340 .runtime
341 .block_on(async move { store.delete_by_file_path(&path_for_delete).await });
342 if let Err(e) = result {
343 warn!("Failed to delete from store {:?}: {}", file_path, e);
344 }
345 }
346
347 match fs::remove_file(&file_path) {
348 Ok(()) => {
349 let mut inodes = self.runtime.block_on(self.inodes.write());
350 if let Some(ino) = inodes.get_by_path(&file_path) {
351 inodes.remove(ino);
352 }
353 info!("Deleted file: {:?}", file_path);
354 reply.ok();
355 }
356 Err(e) => {
357 warn!("Failed to delete file {:?}: {}", file_path, e);
358 reply.error(Errno::EIO);
359 }
360 }
361 }
362
363 pub(crate) fn mkdir_passthrough(
364 &self,
365 parent: u64,
366 name: &OsStr,
367 mode: u32,
368 _umask: u32,
369 reply: ReplyEntry,
370 ) {
371 let name_str = name.to_string_lossy();
372 tracing::debug!(
373 "mkdir: parent={}, name={}, mode={:o}",
374 parent,
375 name_str,
376 mode
377 );
378
379 if parent < FIRST_REAL_INO && parent != ROOT_INO {
380 reply.error(Errno::EPERM);
381 return;
382 }
383
384 let Some(parent_path) = self.resolve_parent_path(parent) else {
385 reply.error(Errno::ENOENT);
386 return;
387 };
388
389 let new_path = parent_path.join(&*name_str);
390
391 if new_path.exists() {
392 reply.error(Errno::EEXIST);
393 return;
394 }
395
396 match fs::create_dir(&new_path) {
397 Ok(()) => {
398 let metadata = match fs::metadata(&new_path) {
399 Ok(m) => m,
400 Err(e) => {
401 warn!("Failed to get metadata for new dir {:?}: {}", new_path, e);
402 reply.error(Errno::EIO);
403 return;
404 }
405 };
406
407 let mut inodes = self.runtime.block_on(self.inodes.write());
408 let ino = inodes.get_or_create_real(new_path.clone(), metadata.ino());
409 drop(inodes);
410
411 if let Some(attr) = self.real_path_to_attr(&new_path, ino) {
412 info!("Created directory: {:?}", new_path);
413 reply.entry(&TTL, &attr, GENERATION);
414 } else {
415 reply.error(Errno::EIO);
416 }
417 }
418 Err(e) => {
419 warn!("Failed to create directory {:?}: {}", new_path, e);
420 reply.error(Errno::EIO);
421 }
422 }
423 }
424
425 pub(crate) fn rmdir_passthrough(&self, parent: u64, name: &OsStr, reply: ReplyEmpty) {
426 let name_str = name.to_string_lossy();
427 tracing::debug!("rmdir: parent={}, name={}", parent, name_str);
428
429 if parent < FIRST_REAL_INO && parent != ROOT_INO {
430 reply.error(Errno::EPERM);
431 return;
432 }
433
434 let Some(parent_path) = self.resolve_parent_path(parent) else {
435 reply.error(Errno::ENOENT);
436 return;
437 };
438
439 let dir_path = parent_path.join(&*name_str);
440
441 if !dir_path.exists() {
442 reply.error(Errno::ENOENT);
443 return;
444 }
445
446 if !dir_path.is_dir() {
447 reply.error(Errno::ENOTDIR);
448 return;
449 }
450
451 match fs::remove_dir(&dir_path) {
452 Ok(()) => {
453 let mut inodes = self.runtime.block_on(self.inodes.write());
454 if let Some(ino) = inodes.get_by_path(&dir_path) {
455 inodes.remove(ino);
456 }
457 info!("Removed directory: {:?}", dir_path);
458 reply.ok();
459 }
460 Err(e) => {
461 if e.kind() == std::io::ErrorKind::DirectoryNotEmpty
462 || e.raw_os_error() == Some(libc::ENOTEMPTY)
463 {
464 reply.error(Errno::ENOTEMPTY);
465 } else {
466 warn!("Failed to remove directory {:?}: {}", dir_path, e);
467 reply.error(Errno::EIO);
468 }
469 }
470 }
471 }
472
473 pub(crate) fn rename_passthrough(
474 &self,
475 parent: u64,
476 name: &OsStr,
477 newparent: u64,
478 newname: &OsStr,
479 _flags: RenameFlags,
480 reply: ReplyEmpty,
481 ) {
482 let name_str = name.to_string_lossy();
483 let newname_str = newname.to_string_lossy();
484 tracing::debug!(
485 "rename: parent={}, name={}, newparent={}, newname={}",
486 parent,
487 name_str,
488 newparent,
489 newname_str
490 );
491
492 if (parent < FIRST_REAL_INO && parent != ROOT_INO)
493 || (newparent < FIRST_REAL_INO && newparent != ROOT_INO)
494 {
495 reply.error(Errno::EPERM);
496 return;
497 }
498
499 let Some(src_parent_path) = self.resolve_parent_path(parent) else {
500 reply.error(Errno::ENOENT);
501 return;
502 };
503
504 let Some(dst_parent_path) = self.resolve_parent_path(newparent) else {
505 reply.error(Errno::ENOENT);
506 return;
507 };
508
509 let src_path = src_parent_path.join(&*name_str);
510 let dst_path = dst_parent_path.join(&*newname_str);
511
512 if !src_path.exists() {
513 reply.error(Errno::ENOENT);
514 return;
515 }
516
517 match fs::rename(&src_path, &dst_path) {
518 Ok(()) => {
519 if let Some(ref store) = self.store {
520 let store = store.clone();
521 let src = src_path.clone();
522 let dst = dst_path.clone();
523 let result = self
524 .runtime
525 .block_on(async move { store.update_file_path(&src, &dst).await });
526 if let Err(e) = result {
527 warn!(
528 "Failed to update store path {:?} -> {:?}: {}",
529 src_path, dst_path, e
530 );
531 }
532 }
533
534 let mut inodes = self.runtime.block_on(self.inodes.write());
535 if let Some(ino) = inodes.get_by_path(&src_path) {
536 inodes.update_path(ino, dst_path.clone());
537 }
538 drop(inodes);
539
540 info!("Renamed: {:?} -> {:?}", src_path, dst_path);
541 reply.ok();
542 }
543 Err(e) => {
544 warn!("Failed to rename {:?} -> {:?}: {}", src_path, dst_path, e);
545 reply.error(Errno::EIO);
546 }
547 }
548 }
549
550 pub(crate) fn setattr_passthrough(
551 &self,
552 ino: u64,
553 _mode: Option<u32>,
554 _uid: Option<u32>,
555 _gid: Option<u32>,
556 size: Option<u64>,
557 _atime: Option<TimeOrNow>,
558 _mtime: Option<TimeOrNow>,
559 _ctime: Option<SystemTime>,
560 _fh: Option<FileHandle>,
561 _crtime: Option<SystemTime>,
562 _chgtime: Option<SystemTime>,
563 _bkuptime: Option<SystemTime>,
564 _flags: Option<BsdFileFlags>,
565 reply: ReplyAttr,
566 ) {
567 tracing::debug!("setattr: ino={}, size={:?}", ino, size);
568
569 if ino < FIRST_REAL_INO {
570 reply.error(Errno::EPERM);
571 return;
572 }
573
574 let inodes = self.runtime.block_on(self.inodes.read());
575 let Some(entry) = inodes.get(ino) else {
576 drop(inodes);
577 reply.error(Errno::ENOENT);
578 return;
579 };
580 let InodeKind::Real { path, .. } = &entry.kind else {
581 drop(inodes);
582 reply.error(Errno::EINVAL);
583 return;
584 };
585 let path = path.clone();
586 drop(inodes);
587
588 if let Some(new_size) = size {
589 match fs::OpenOptions::new().write(true).open(&path) {
590 Ok(file) => {
591 if let Err(e) = file.set_len(new_size) {
592 warn!("Failed to truncate {:?}: {}", path, e);
593 reply.error(Errno::EIO);
594 return;
595 }
596
597 if let Some(ref sender) = self.reindex_sender {
598 let sender = sender.clone();
599 let path_to_send = path.clone();
600 self.runtime.spawn(async move {
601 if let Err(e) = sender.send(path_to_send).await {
602 warn!("Failed to send reindex request: {}", e);
603 }
604 });
605 }
606 }
607 Err(e) => {
608 warn!("Failed to open {:?} for truncate: {}", path, e);
609 reply.error(Errno::EIO);
610 return;
611 }
612 }
613 }
614
615 if let Some(attr) = self.real_path_to_attr(&path, ino) {
616 reply.attr(&TTL, &attr);
617 } else {
618 reply.error(Errno::EIO);
619 }
620 }
621}