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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Filesystem mounting and management functionality.
//!
//! This module provides the core functionality for mounting and managing
//! filesystem bindings through the `FilesystemManager`.
use super::constants::BLOCK_SIZE;
use super::namespace::{BindMode, NamespaceEntry};
use super::proto::{BoundEntry, NineP};
use anyhow::{anyhow, Result};
use fuser::{FileAttr, FileType};
use libc::{SIGINT, SIGTERM};
use signal_hook::iterator::Signals;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::ffi::CString;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};
use std::thread;
use std::time::UNIX_EPOCH;
use log::{info, debug};
#[cfg(target_os = "macos")]
extern "C" {
/// Unmounts a filesystem on macOS.
///
/// # Arguments
/// * `path` - Path to unmount
/// * `flags` - Unmount flags
pub fn unmount(path: *const i8, flags: i32) -> i32;
}
#[cfg(target_os = "linux")]
extern "C" {
pub fn umount(path: *const i8) -> i32;
}
#[derive(Clone)]
struct DirectoryEntry {
name: String,
path: PathBuf,
metadata: fs::Metadata,
}
/// Manages filesystem mounting and binding operations.
#[derive(Clone)]
pub struct FilesystemManager {
/// The underlying 9P filesystem implementation.
pub fs: NineP,
}
impl FilesystemManager {
/// Creates a new filesystem manager.
///
/// # Arguments
///
/// * `fs` - The 9P filesystem implementation to manage
pub fn new(fs: NineP) -> Self {
Self { fs }
}
// Helper function to create FileAttr from metadata
fn create_file_attr(&self, inode: u64, metadata: &fs::Metadata) -> FileAttr {
FileAttr {
ino: inode,
size: metadata.len(),
blocks: (metadata.len() + BLOCK_SIZE - 1) / BLOCK_SIZE,
atime: metadata.accessed().unwrap_or(UNIX_EPOCH),
mtime: metadata.modified().unwrap_or(UNIX_EPOCH),
ctime: UNIX_EPOCH,
crtime: UNIX_EPOCH,
kind: if metadata.is_dir() {
FileType::Directory
} else {
FileType::RegularFile
},
perm: 0o755,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
flags: 0,
blksize: 512,
}
}
fn read_directory_entries_recursive(
&self,
base_path: &Path,
current_path: &Path,
parent_inode: u64,
next_inode: &mut u64,
bindings: &mut HashMap<u64, (OsString, BoundEntry)>,
) -> Result<()> {
println!("Reading directory recursively: {:?}", current_path);
let mut queue = VecDeque::new();
queue.push_back((current_path.to_path_buf(), parent_inode));
while let Some((path, parent)) = queue.pop_front() {
for entry in fs::read_dir(&path)? {
let entry = entry?;
let metadata = entry.metadata()?;
let entry_path = entry.path();
let relative_path = entry_path.strip_prefix(base_path)?;
// Skip if this is the root directory itself
if relative_path.as_os_str().is_empty() {
continue;
}
let inode = {
let current = *next_inode;
*next_inode += 1;
current
};
let file_name = entry.file_name();
println!("Adding binding for: {:?} with inode: {}", file_name, inode);
let file_attr = self.create_file_attr(inode, &metadata);
let content = if metadata.is_file() {
Some(fs::read(&entry_path)?)
} else {
None
};
bindings.insert(
inode,
(
file_name,
BoundEntry {
attr: file_attr,
content,
},
),
);
if metadata.is_dir() {
queue.push_back((entry_path, inode));
}
}
}
Ok(())
}
/// Binds a directory to a target location.
fn bind_directory(&self, dir_path: &str, source_path: &Path, mode: BindMode) -> Result<()> {
debug!("Binding directory: {} from source: {:?}", dir_path, source_path);
let mut bindings = self.fs.namespace_manager.bindings.lock().unwrap();
let mut next_inode = self.fs.namespace_manager.next_inode.lock().unwrap();
// Convert paths to absolute paths
let abs_source = fs::canonicalize(source_path)?;
let abs_target = fs::canonicalize(Path::new(dir_path))?;
println!(
"Resolved paths - source: {:?}, target: {:?}",
abs_source, abs_target
);
match mode {
BindMode::Replace => {
// Clear existing bindings but keep root
bindings.retain(|&ino, _| ino == 1);
// Read source directory recursively
self.read_directory_entries_recursive(
&abs_source,
&abs_source,
1,
&mut next_inode,
&mut bindings,
)?;
}
BindMode::Before => {
let mut new_bindings = HashMap::new();
// Read source directory recursively
self.read_directory_entries_recursive(
&abs_source,
&abs_source,
1,
&mut next_inode,
&mut new_bindings,
)?;
// Read target directory and add non-conflicting entries
let mut target_bindings = HashMap::new();
self.read_directory_entries_recursive(
&abs_target,
&abs_target,
1,
&mut next_inode,
&mut target_bindings,
)?;
for (inode, (path, entry)) in target_bindings {
if !new_bindings.values().any(|(p, _)| p == &path) {
new_bindings.insert(inode, (path, entry));
}
}
bindings.extend(new_bindings);
}
BindMode::After => {
// Read target directory first
let mut target_bindings = HashMap::new();
self.read_directory_entries_recursive(
&abs_target,
&abs_target,
1,
&mut next_inode,
&mut target_bindings,
)?;
bindings.extend(target_bindings);
// Add non-conflicting source entries
let mut source_bindings = HashMap::new();
self.read_directory_entries_recursive(
&abs_source,
&abs_source,
1,
&mut next_inode,
&mut source_bindings,
)?;
for (inode, (path, entry)) in source_bindings {
if !bindings.values().any(|(p, _)| p == &path) {
bindings.insert(inode, (path, entry));
}
}
}
BindMode::Create => {
// Clear existing bindings but keep root
bindings.retain(|&ino, _| ino == 1);
// Read source directory recursively
let mut new_bindings = HashMap::new();
self.read_directory_entries_recursive(
&abs_source,
&abs_source,
1,
&mut next_inode,
&mut new_bindings,
)?;
// Make all entries read-only
for (_, (_, entry)) in new_bindings.iter_mut() {
entry.attr.perm &= 0o555;
}
bindings.extend(new_bindings);
}
}
println!("Final bindings: {:?}", bindings.keys().collect::<Vec<_>>());
for (inode, (name, entry)) in bindings.iter() {
println!(
"inode: {}, name: {:?}, kind: {:?}",
inode, name, entry.attr.kind
);
}
Ok(())
}
/// Binds a source path to a target path with the specified mode.
///
/// This method creates a binding between two filesystem paths, allowing the contents
/// of the source path to be accessed through the target path. The behavior of the
/// binding is determined by the specified `BindMode`.
///
/// # Arguments
///
/// * `source` - The source path to bind from
/// * `target` - The target path to bind to
/// * `mode` - The binding mode to use:
/// - `Replace`: Replaces any existing content at the target
/// - `Before`: Adds content with higher priority than existing bindings
/// - `After`: Adds content with lower priority than existing bindings
/// - `Create`: Creates a new binding, failing if the target exists
///
/// # Returns
///
/// * `Ok(())` if the binding was successful
/// * `Err(...)` if the binding failed (e.g., invalid paths, permission issues)
pub fn bind(&self, source: &Path, target: &Path, mode: BindMode) -> Result<()> {
info!("Binding {:?} to {:?} with mode {:?}", source, target, mode);
let abs_source = fs::canonicalize(source)?;
let abs_target = fs::canonicalize(target)?;
if !abs_source.exists() {
return Err(anyhow!("Source path does not exist: {:?}", abs_source));
}
if !abs_target.exists() {
return Err(anyhow!("Target path does not exist: {:?}", abs_target));
}
let entry = NamespaceEntry {
source: abs_source.clone(),
target: abs_target.clone(),
bind_mode: mode.clone(),
remote_node: None,
};
let mut namespace = self.fs.namespace_manager.namespace.write().unwrap();
namespace
.entry(abs_target.clone())
.or_insert_with(Vec::new)
.push(entry);
self.bind_directory(abs_target.to_str().unwrap(), &abs_source, mode)?;
Ok(())
}
/// Mounts a filesystem at the specified path.
///
/// # Arguments
///
/// * `source` - The source path to mount
/// * `mount_point` - Where to mount the filesystem
/// * `node_id` - Optional remote node identifier
///
/// # Returns
///
/// A Result indicating success or failure
pub fn mount(&self, source: &Path, mount_point: &Path, node_id: &str) -> Result<()> {
let abs_local = fs::canonicalize(mount_point)?;
if !abs_local.exists() {
return Err(anyhow!("Local mount point does not exist"));
}
let entry = NamespaceEntry {
source: source.to_path_buf(),
target: abs_local.clone(),
bind_mode: BindMode::Replace,
remote_node: Some(node_id.to_string()),
};
let mut namespace = self.fs.namespace_manager.namespace.write().unwrap();
namespace
.entry(abs_local.clone())
.or_insert_with(Vec::new)
.push(entry);
let mount_thread = {
let remote_path_clone = source.to_path_buf();
let hello_fs_clone = self.fs.clone();
thread::spawn(move || {
fuser::mount2(hello_fs_clone, &remote_path_clone, &[]).unwrap();
})
};
// Signal handling
let mut signals = Signals::new(&[SIGINT, SIGTERM])?;
for sig in signals.forever() {
match sig {
SIGINT | SIGTERM => {
println!("Received signal, unmounting...");
Self::handle_unmount(source.to_str().unwrap());
break;
}
_ => {}
}
}
mount_thread.join().unwrap();
Ok(())
}
/// Unmounts a filesystem at the specified path.
///
/// # Arguments
/// * `path` - The path to unmount
/// * `specific_source` - Optional specific source to unmount
///
/// # Returns
/// * `Result<()>` - Success or error
pub fn unmount(&self, path: &Path, specific_source: Option<&Path>) -> Result<()> {
let abs_path = fs::canonicalize(path)?;
let mut namespace = self.fs.namespace_manager.namespace.write().unwrap();
if let Some(entries) = namespace.get_mut(&abs_path) {
if let Some(specific_source) = specific_source {
let abs_specific_source = fs::canonicalize(specific_source)?;
entries.retain(|entry| entry.source.clone() != abs_specific_source);
} else {
entries.clear();
}
if entries.is_empty() {
namespace.remove(&abs_path);
}
}
Ok(())
}
// Platform-specific unmount handler
fn handle_unmount(path: &str) {
let c_path = CString::new(path).expect("CString::new failed");
#[cfg(target_os = "macos")]
unsafe {
if unmount(c_path.as_ptr(), 0) != 0 {
eprintln!("Failed to unmount {}", path);
}
}
#[cfg(target_os = "linux")]
unsafe {
if umount(c_path.as_ptr()) != 0 {
eprintln!("Failed to unmount {}", path);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
fn setup_test_manager() -> (TempDir, FilesystemManager) {
let temp_dir = tempfile::tempdir().unwrap();
let fs = NineP::new(temp_dir.path().to_path_buf()).unwrap();
let manager = FilesystemManager::new(fs);
(temp_dir, manager)
}
fn create_temp_dir_with_files(parent: &Path) -> Result<TempDir> {
let dir = tempfile::tempdir_in(parent)?;
fs::write(dir.path().join("test.txt"), "test content")?;
Ok(dir)
}
// figure out how to test bind_directory
// #[test]
// fn test_bind_directory() -> Result<()> {
// let (root_dir, manager) = setup_test_manager();
// let source_dir = create_temp_dir_with_files(root_dir.path())?;
// let target_dir = tempfile::tempdir_in(root_dir.path())?;
// // Only test the namespace manipulation, not the actual mounting
// let abs_source = fs::canonicalize(source_dir.path())?;
// let abs_target = fs::canonicalize(target_dir.path())?;
// let entry = NamespaceEntry {
// source: abs_source.clone(),
// target: abs_target.clone(),
// bind_mode: BindMode::Replace,
// remote_node: None,
// };
// {
// let mut namespace = manager.fs.namespace_manager.namespace.write().unwrap();
// namespace
// .entry(abs_target.clone())
// .or_insert_with(Vec::new)
// .push(entry);
// }
// let namespace = manager.fs.namespace_manager.namespace.read().unwrap();
// assert_eq!(namespace.len(), 1);
// Ok(())
// }
// #[test]
// fn test_multiple_binds() -> Result<()> {
// let (root_dir, manager) = setup_test_manager();
// let temp_dirs: Vec<TempDir> = (0..3)
// .map(|_| tempfile::tempdir_in(root_dir.path()).unwrap())
// .collect();
// // Test namespace manipulation directly instead of using bind()
// let abs_source1 = fs::canonicalize(temp_dirs[0].path())?;
// let abs_target1 = fs::canonicalize(temp_dirs[1].path())?;
// let abs_target2 = fs::canonicalize(temp_dirs[2].path())?;
// {
// let mut namespace = manager.fs.namespace_manager.namespace.write().unwrap();
// // First binding
// namespace
// .entry(abs_target1.clone())
// .or_insert_with(Vec::new)
// .push(NamespaceEntry {
// source: abs_source1.clone(),
// target: abs_target1.clone(),
// bind_mode: BindMode::Replace,
// remote_node: None,
// });
// // Second binding
// namespace
// .entry(abs_target2.clone())
// .or_insert_with(Vec::new)
// .push(NamespaceEntry {
// source: abs_target1.clone(),
// target: abs_target2.clone(),
// bind_mode: BindMode::Replace,
// remote_node: None,
// });
// }
// let namespace = manager.fs.namespace_manager.namespace.read().unwrap();
// assert_eq!(namespace.len(), 2);
// Ok(())
// }
// figure out how to test unmount
// #[test]
// fn test_unmount() -> Result<()> {
// let (root_dir, manager) = setup_test_manager();
// let source_dir = create_temp_dir_with_files(root_dir.path())?;
// let target_dir = tempfile::tempdir_in(root_dir.path())?;
// let abs_source = fs::canonicalize(source_dir.path())?;
// let abs_target = fs::canonicalize(target_dir.path())?;
// // First set up the binding directly in the namespace
// {
// let mut namespace = manager.fs.namespace_manager.namespace.write().unwrap();
// namespace
// .entry(abs_target.clone())
// .or_insert_with(Vec::new)
// .push(NamespaceEntry {
// source: abs_source.clone(),
// target: abs_target.clone(),
// bind_mode: BindMode::Replace,
// remote_node: None,
// });
// }
// // Verify initial binding
// {
// let namespace = manager.fs.namespace_manager.namespace.read().unwrap();
// assert_eq!(namespace.len(), 1);
// }
// // Test unmount
// manager.unmount(target_dir.path(), None)?;
// // Verify unmount
// {
// let namespace = manager.fs.namespace_manager.namespace.read().unwrap();
// assert!(namespace.is_empty());
// }
// Ok(())
// }
}