whichdisk 0.5.0

Cross-platform disk/volume resolver — given a path, tells you which disk it's on, its mount point, relative path, disk usage, and per-volume capabilities (case-sensitivity, filesystem type)
Documentation
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
use std::{
  cell::RefCell,
  collections::HashMap,
  ffi::OsStr,
  os::unix::ffi::OsStrExt,
  path::{Path, PathBuf},
};

use rustix::fs::{stat, statfs};

use super::{SmallBytes, VolumeCapabilities};

struct CacheEntry {
  mount_point: SmallBytes,
  device: SmallBytes,
  capabilities: VolumeCapabilities,
}

thread_local! {
  static CACHE: RefCell<HashMap<u64, CacheEntry>> = RefCell::new(HashMap::new());
}

#[derive(Clone, PartialEq, Eq)]
pub(super) struct Inner {
  mount: super::MountPoint,
  canonical: PathBuf,
  relative_offset: usize,
}

impl Inner {
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub(super) fn mount_info(&self) -> &super::MountPoint {
    &self.mount
  }

  #[cfg_attr(not(tarpaulin), inline(always))]
  pub(super) fn canonical_path(&self) -> &Path {
    &self.canonical
  }

  #[cfg_attr(not(tarpaulin), inline(always))]
  pub(super) fn relative_path(&self) -> &Path {
    let bytes = self.canonical.as_os_str().as_bytes();
    Path::new(OsStr::from_bytes(&bytes[self.relative_offset..]))
  }
}

#[cfg_attr(not(tarpaulin), inline(always))]
pub(super) fn resolve(path: &Path) -> std::io::Result<Inner> {
  let canonical = path.canonicalize()?;
  let st = stat(&canonical).map_err(std::io::Error::from)?;
  let dev = st.st_dev as u64;

  // Try thread-local cache first — avoids the statfs syscall on repeated lookups
  // for paths on the same device.
  let cached = CACHE.with(|c| {
    c.borrow().get(&dev).map(|e| {
      (
        e.mount_point.clone(),
        e.device.clone(),
        e.capabilities.clone(),
      )
    })
  });

  #[cfg(not(feature = "disk-usage"))]
  let (mount_point, device, capabilities) = if let Some(hit) = cached {
    hit
  } else {
    let fs = statfs(&canonical).map_err(std::io::Error::from)?;
    let mp = SmallBytes::from_bytes(c_chars_as_bytes(&fs.f_mntonname));
    let dv = SmallBytes::from_bytes(c_chars_as_bytes(&fs.f_mntfromname));
    let caps = volume_capabilities(&canonical, c_chars_as_bytes(&fs.f_fstypename));
    CACHE.with(|c| {
      c.borrow_mut().insert(
        dev,
        CacheEntry {
          mount_point: mp.clone(),
          device: dv.clone(),
          capabilities: caps.clone(),
        },
      );
    });
    (mp, dv, caps)
  };

  #[cfg(feature = "disk-usage")]
  #[allow(clippy::unnecessary_cast)]
  let (mount_point, device, capabilities, total_bytes, available_bytes) =
    if let Some((mp, dv, caps)) = cached {
      // Re-query statfs for fresh size info (sizes change, mount/device don't).
      match statfs(&canonical) {
        Ok(fs) => {
          let bsize = fs.f_bsize as u64;
          (
            mp,
            dv,
            caps,
            (fs.f_blocks as u64).saturating_mul(bsize),
            (fs.f_bavail as u64).saturating_mul(bsize),
          )
        }
        Err(_) => (mp, dv, caps, 0, 0),
      }
    } else {
      let fs = statfs(&canonical).map_err(std::io::Error::from)?;
      let mp = SmallBytes::from_bytes(c_chars_as_bytes(&fs.f_mntonname));
      let dv = SmallBytes::from_bytes(c_chars_as_bytes(&fs.f_mntfromname));
      let caps = volume_capabilities(&canonical, c_chars_as_bytes(&fs.f_fstypename));
      let bsize = fs.f_bsize as u64;
      let total = (fs.f_blocks as u64).saturating_mul(bsize);
      let avail = (fs.f_bavail as u64).saturating_mul(bsize);
      CACHE.with(|c| {
        c.borrow_mut().insert(
          dev,
          CacheEntry {
            mount_point: mp.clone(),
            device: dv.clone(),
            capabilities: caps.clone(),
          },
        );
      });
      (mp, dv, caps, total, avail)
    };

  let canonical_bytes = canonical.as_os_str().as_bytes();
  let mount_point_bytes = mount_point.as_bytes();

  let relative_offset = if canonical_bytes.starts_with(mount_point_bytes) {
    let off = mount_point_bytes.len();
    if off < canonical_bytes.len() && canonical_bytes[off] == b'/' {
      off + 1
    } else {
      off
    }
  } else {
    // Apple firmlink case: canonicalize() returns a path in the root namespace
    // (e.g. /Users/...) while statfs reports the real mount point
    // (e.g. /System/Volumes/Data). The relative part is the canonical path
    // without the leading '/'.
    #[cfg(any(
      target_os = "macos",
      target_os = "ios",
      target_os = "watchos",
      target_os = "tvos",
      target_os = "visionos",
    ))]
    {
      let firmlinked = Path::new(OsStr::from_bytes(mount_point_bytes))
        .join(canonical.strip_prefix("/").unwrap_or(&canonical));
      if firmlinked.exists() {
        // canonicalize() always returns absolute paths starting with '/',
        // so the relative part starts at byte 1.
        1
      } else {
        canonical_bytes.len()
      }
    }
    #[cfg(not(any(
      target_os = "macos",
      target_os = "ios",
      target_os = "watchos",
      target_os = "tvos",
      target_os = "visionos",
    )))]
    {
      canonical_bytes.len()
    }
  };

  let is_ejectable = is_ejectable(mount_point.as_path(), device.as_os_str());

  Ok(Inner {
    mount: super::MountPoint {
      mount_point,
      device,
      is_ejectable,
      capabilities,
      #[cfg(feature = "disk-usage")]
      total_bytes,
      #[cfg(feature = "disk-usage")]
      available_bytes,
    },
    canonical,
    relative_offset,
  })
}

/// Apple platforms: enumerate volumes via NSFileManager, skip non-browsable
/// and non-local volumes, query ejectable/removable properties.
#[cfg(feature = "list")]
#[cfg(any(
  target_os = "macos",
  target_os = "ios",
  target_os = "watchos",
  target_os = "tvos",
  target_os = "visionos",
))]
pub(super) fn list(opts: super::ListOptions) -> std::io::Result<Vec<super::MountPoint>> {
  use objc2_foundation::{
    NSArray, NSFileManager, NSURLResourceKey, NSURLVolumeIsBrowsableKey, NSURLVolumeIsEjectableKey,
    NSURLVolumeIsLocalKey, NSURLVolumeIsRemovableKey, NSVolumeEnumerationOptions,
  };

  let fm = NSFileManager::defaultManager();
  let keys: &[&NSURLResourceKey] = unsafe {
    &[
      NSURLVolumeIsBrowsableKey,
      NSURLVolumeIsLocalKey,
      NSURLVolumeIsEjectableKey,
      NSURLVolumeIsRemovableKey,
    ]
  };
  let keys_array = NSArray::from_slice(keys);

  let urls = fm.mountedVolumeURLsIncludingResourceValuesForKeys_options(
    Some(&keys_array),
    NSVolumeEnumerationOptions::empty(),
  );
  let urls = urls.ok_or_else(|| std::io::Error::other("failed to enumerate volumes"))?;

  let mut mounts = Vec::new();
  for url in urls.iter() {
    if !get_bool_resource(&url, unsafe { NSURLVolumeIsBrowsableKey }) {
      continue;
    }
    if !get_bool_resource(&url, unsafe { NSURLVolumeIsLocalKey }) {
      continue;
    }

    let ejectable = get_bool_resource(&url, unsafe { NSURLVolumeIsEjectableKey });
    let removable = get_bool_resource(&url, unsafe { NSURLVolumeIsRemovableKey });
    let is_ejectable = ejectable || removable;

    if opts.is_ejectable_only() && !is_ejectable {
      continue;
    }
    if opts.is_non_ejectable_only() && is_ejectable {
      continue;
    }

    if let Some(path) = url.path() {
      let path_bytes = path.to_string().into_bytes();
      let mount_point = SmallBytes::from_bytes(&path_bytes);

      let mp_path = Path::new(OsStr::from_bytes(&path_bytes));
      let fs = match statfs(mp_path) {
        Ok(fs) => fs,
        Err(_) => continue,
      };
      let device = SmallBytes::from_bytes(c_chars_as_bytes(&fs.f_mntfromname));
      let capabilities = volume_capabilities(mp_path, c_chars_as_bytes(&fs.f_fstypename));
      #[cfg(feature = "disk-usage")]
      let (total_bytes, available_bytes) = {
        let bsize = fs.f_bsize as u64;
        (
          (fs.f_blocks as u64).saturating_mul(bsize),
          (fs.f_bavail as u64).saturating_mul(bsize),
        )
      };

      mounts.push(super::MountPoint {
        mount_point,
        device,
        is_ejectable,
        capabilities,
        #[cfg(feature = "disk-usage")]
        total_bytes,
        #[cfg(feature = "disk-usage")]
        available_bytes,
      });
    }
  }
  Ok(mounts)
}

/// Apple platforms: query NSURLVolumeIsEjectableKey / NSURLVolumeIsRemovableKey.
#[cfg(any(
  target_os = "macos",
  target_os = "ios",
  target_os = "watchos",
  target_os = "tvos",
  target_os = "visionos",
))]
pub(super) fn is_ejectable(mount_point: &Path, _device: &OsStr) -> bool {
  use objc2_foundation::{NSURL, NSURLVolumeIsEjectableKey, NSURLVolumeIsRemovableKey};

  let url = NSURL::fileURLWithPath(&objc2_foundation::NSString::from_str(
    &mount_point.to_string_lossy(),
  ));
  let ejectable = get_bool_resource(&url, unsafe { NSURLVolumeIsEjectableKey });
  let removable = get_bool_resource(&url, unsafe { NSURLVolumeIsRemovableKey });
  ejectable || removable
}

/// Helper: extract a boolean volume resource value from an NSURL.
#[cfg(any(
  target_os = "macos",
  target_os = "ios",
  target_os = "watchos",
  target_os = "tvos",
  target_os = "visionos",
))]
fn get_bool_resource(
  url: &objc2_foundation::NSURL,
  key: &objc2_foundation::NSURLResourceKey,
) -> bool {
  use objc2_foundation::NSNumber;
  let val = url.resourceValuesForKeys_error(&objc2_foundation::NSArray::from_slice(&[key]));
  match val {
    Ok(dict) => {
      let obj = dict.objectForKey(key);
      match obj {
        Some(obj) => {
          let num: &NSNumber = unsafe { &*(&*obj as *const _ as *const NSNumber) };
          num.boolValue()
        }
        None => false,
      }
    }
    Err(_) => false,
  }
}

/// FreeBSD, OpenBSD, DragonFlyBSD: use getmntinfo, skip virtual filesystems.
#[cfg(feature = "list")]
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly"))]
pub(super) fn list(opts: super::ListOptions) -> std::io::Result<Vec<super::MountPoint>> {
  const MNT_WAIT: core::ffi::c_int = 1;
  const MNT_NOWAIT: core::ffi::c_int = 2;

  let mut mntbuf: *mut libc::statfs = core::ptr::null_mut();
  // MNT_NOWAIT returns cached statistics (fast), but on a cold process some
  // BSDs (notably OpenBSD) return 0 entries without setting errno; fall back to
  // MNT_WAIT, which forces a refresh and reliably populates the mount list.
  let mut count = unsafe { libc::getmntinfo(&mut mntbuf, MNT_NOWAIT) };
  if count <= 0 || mntbuf.is_null() {
    count = unsafe { libc::getmntinfo(&mut mntbuf, MNT_WAIT) };
  }
  if count <= 0 || mntbuf.is_null() {
    return Err(std::io::Error::last_os_error());
  }

  let entries = unsafe { core::slice::from_raw_parts(mntbuf, count as usize) };
  let mut mounts = Vec::new();
  for entry in entries {
    let fs_type = c_chars_as_bytes(&entry.f_fstypename);
    if matches!(
      fs_type,
      b"autofs" | b"devfs" | b"linprocfs" | b"procfs" | b"fdescfs" | b"tmpfs" | b"linsysfs"
    ) {
      continue;
    }
    let mp_bytes = c_chars_as_bytes(&entry.f_mntonname);
    if mp_bytes == b"/boot/efi" {
      continue;
    }
    let device_bytes = c_chars_as_bytes(&entry.f_mntfromname);
    let is_ejectable = is_removable_bsd(fs_type, device_bytes);
    if opts.is_ejectable_only() && !is_ejectable {
      continue;
    }
    if opts.is_non_ejectable_only() && is_ejectable {
      continue;
    }
    let mount_point = SmallBytes::from_bytes(mp_bytes);
    let device = SmallBytes::from_bytes(device_bytes);
    let capabilities = volume_capabilities(mount_point.as_path(), fs_type);
    #[cfg(feature = "disk-usage")]
    let (total_bytes, available_bytes) = {
      let bsize = entry.f_bsize as u64;
      (
        (entry.f_blocks as u64).saturating_mul(bsize),
        (entry.f_bavail as u64).saturating_mul(bsize),
      )
    };
    mounts.push(super::MountPoint {
      mount_point,
      device,
      is_ejectable,
      capabilities,
      #[cfg(feature = "disk-usage")]
      total_bytes,
      #[cfg(feature = "disk-usage")]
      available_bytes,
    });
  }
  Ok(mounts)
}

/// FreeBSD, OpenBSD, DragonFlyBSD: check filesystem type and device path.
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly"))]
pub(super) fn is_ejectable(mount_point: &Path, _device: &OsStr) -> bool {
  match statfs(mount_point) {
    Ok(fs) => {
      let fs_type = c_chars_as_bytes(&fs.f_fstypename);
      let device = c_chars_as_bytes(&fs.f_mntfromname);
      is_removable_bsd(fs_type, device)
    }
    Err(_) => false,
  }
}

#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly"))]
fn is_removable_bsd(_fs_type: &[u8], device: &[u8]) -> bool {
  // da* = USB mass storage (SCSI disk), cd* = optical drives
  device.starts_with(b"/dev/da") || device.starts_with(b"/dev/cd")
}

/// Apple platforms: query case-handling capabilities via `getattrlist` with
/// `ATTR_VOL_CAPABILITIES`. `fs_type` is taken from the caller's `statfs`
/// (`f_fstypename`). Case flags fall back to `None` when the volume does not
/// report the `VOL_CAP_FMT_CASE_SENSITIVE` / `VOL_CAP_FMT_CASE_PRESERVING` bits
/// as valid, or the syscall fails.
#[cfg(any(
  target_os = "macos",
  target_os = "ios",
  target_os = "watchos",
  target_os = "tvos",
  target_os = "visionos",
))]
fn volume_capabilities(path: &Path, fs_type: &[u8]) -> VolumeCapabilities {
  // getattrlist writes a leading u32 length followed by the requested
  // attributes in bitmap order; for ATTR_VOL_CAPABILITIES that is a single
  // vol_capabilities_attr_t. #[repr(C)] guarantees the layout the kernel writes.
  #[repr(C)]
  struct CapabilitiesBuf {
    length: u32,
    caps: libc::vol_capabilities_attr_t,
  }

  let Ok(c_path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
    return VolumeCapabilities::from_fs_type(fs_type);
  };

  let mut attrs: libc::attrlist = unsafe { core::mem::zeroed() };
  attrs.bitmapcount = libc::ATTR_BIT_MAP_COUNT;
  attrs.volattr = libc::ATTR_VOL_INFO | libc::ATTR_VOL_CAPABILITIES;

  let mut buf: CapabilitiesBuf = unsafe { core::mem::zeroed() };
  let rc = unsafe {
    libc::getattrlist(
      c_path.as_ptr(),
      core::ptr::from_mut(&mut attrs).cast::<core::ffi::c_void>(),
      core::ptr::from_mut(&mut buf).cast::<core::ffi::c_void>(),
      core::mem::size_of::<CapabilitiesBuf>(),
      0,
    )
  };
  if rc != 0 {
    return VolumeCapabilities::from_fs_type(fs_type);
  }

  // capabilities[VOL_CAPABILITIES_FORMAT] holds the format-capability bits;
  // a bit is only meaningful when the matching valid[...] bit is set.
  let format = buf.caps.capabilities[libc::VOL_CAPABILITIES_FORMAT];
  let format_valid = buf.caps.valid[libc::VOL_CAPABILITIES_FORMAT];

  let case_sensitive = if format_valid & libc::VOL_CAP_FMT_CASE_SENSITIVE != 0 {
    Some(format & libc::VOL_CAP_FMT_CASE_SENSITIVE != 0)
  } else {
    None
  };
  let case_preserving = if format_valid & libc::VOL_CAP_FMT_CASE_PRESERVING != 0 {
    Some(format & libc::VOL_CAP_FMT_CASE_PRESERVING != 0)
  } else {
    None
  };

  VolumeCapabilities {
    case_sensitive,
    case_preserving,
    fs_type: SmallBytes::from_bytes(fs_type),
  }
}

/// FreeBSD, OpenBSD, DragonFlyBSD: derive case semantics from the filesystem
/// type — `Some(...)` only for types that determine it (FFS/UFS are
/// case-sensitive, msdosfs/exFAT are case-insensitive) and `None` otherwise
/// (ZFS case sensitivity is a per-dataset property). There is no portable
/// per-volume query. `fs_type` comes from `statfs` (`f_fstypename`).
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly"))]
fn volume_capabilities(_path: &Path, fs_type: &[u8]) -> VolumeCapabilities {
  VolumeCapabilities::from_fs_type_defaults(fs_type)
}

#[cfg_attr(not(tarpaulin), inline(always))]
fn c_chars_as_bytes(chars: &[core::ffi::c_char]) -> &[u8] {
  // SAFETY: c_char and u8 have the same size and alignment.
  let bytes: &[u8] =
    unsafe { &*(core::ptr::from_ref::<[core::ffi::c_char]>(chars) as *const [u8]) };
  let len = super::find_byte(0, bytes).unwrap_or(bytes.len());
  &bytes[..len]
}