trusty_code/paths/write_dir.rs
1//! Pinned, symlink-refusing write handles beneath `<project>/.trusty-code/`
2//! (#7779).
3//!
4//! Why: [`super::check_native_write_target`] answers "is this a legal write
5//! target?"
6//! against the filesystem as it looked when it was called. Every caller then
7//! wrote through the same path STRING, so a directory swapped for a symlink at
8//! any component between the two was followed and the write landed outside the
9//! project — measured at 6 of 40 real `tcode` deploys against a 4 ms
10//! `skill-refs -> victim` swap loop (#7779, PR #7773 review). A check a rename
11//! can overtake is not a boundary.
12//!
13//! What: [`NativeWriteDir`] opens the target directory ONCE, descending from the
14//! canonical project root one component at a time with `O_NOFOLLOW`, and keeps
15//! the resulting directory descriptor. Every later read, write, rename and lock
16//! is `openat`-relative to that descriptor, so the kernel resolves it against
17//! the pinned inode instead of re-walking the path — a symlink swapped in
18//! afterwards cannot redirect it. Each write then re-checks the handle's
19//! identity against the path ([`NativeWriteDir::verify_pinned`]) so a swap
20//! surfaces as a typed [`WriteTargetError::Unpinned`] instead of a deploy that
21//! silently wrote into a directory nothing will ever read.
22//!
23//! The write-boundary contract itself is unchanged: ADR-0044 restricts writes to
24//! the product's own configuration directory, and [`super::anchor_native_root`]
25//! still decides membership. It decides it ONCE, and the path it returns is the
26//! path pinned — a writer never re-resolves `.trusty-code`, so there is no
27//! second answer for a rename to substitute (#7779 round 2).
28//!
29//! ## Symlinks beneath the config root are refused, never followed
30//!
31//! Every entry this handle touches is opened `O_NOFOLLOW`, READS included. A
32//! symlinked `agents/pm.md`, `skill-refs/<skill>/SKILL.md` or ledger is a typed
33//! [`WriteTargetError::Unpinned`] that fails the whole deploy, where the
34//! pre-#7779 code followed it and treated the target's bytes as the deployed
35//! file's. This is deliberate, and it narrows `deploy`'s "a hand-edited deployed
36//! file is authoritative" policy to REAL files: a link's bytes cannot be bounded
37//! by the handle that is supposed to bound them, and publishing over it with
38//! `renameat` would silently replace the link rather than write where it points
39//! — so the two would disagree about what the deploy just did. Point the link
40//! the other way (keep the real file under `.trusty-code/` and link to it from
41//! elsewhere) or drop it. PR #7773's review asked for this on the skill-refs
42//! tree; it holds uniformly rather than per-directory.
43//!
44//! Unix only, like the rest of this crate's daemon transport — `openat`,
45//! `renameat` and `O_NOFOLLOW` are what close the window and have no portable
46//! equivalent.
47//!
48//! Test: `paths::write_dir_tests::*`.
49
50use std::ffi::{CString, OsStr};
51use std::fs::File;
52use std::io::Write;
53use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd};
54use std::os::unix::ffi::OsStrExt;
55use std::os::unix::fs::MetadataExt;
56use std::path::{Component, Path, PathBuf};
57
58use super::{
59 AnchoredRoot, TRUSTY_CODE_DIRNAME, WriteTargetError, anchor_native_root, native_config_dir,
60};
61
62/// A directory beneath `<project>/.trusty-code/`, pinned to an open descriptor.
63///
64/// Why: see the module docs — the handle IS the guarantee. Holding it is what
65/// makes "the path validated is the path written" true rather than aspirational.
66/// What: an owned directory file descriptor plus the logical path it was opened
67/// as (for diagnostics only; nothing resolves through it again). Constructing
68/// one creates every missing component with `mkdirat`, so callers no longer need
69/// `create_dir_all` — the call this race was won against.
70/// Test: `paths::write_dir_tests::pinned_write_lands_at_the_validated_path`,
71/// `paths::write_dir_tests::component_swapped_after_open_never_reaches_victim`.
72#[derive(Debug)]
73pub struct NativeWriteDir {
74 fd: OwnedFd,
75 path: PathBuf,
76}
77
78impl NativeWriteDir {
79 /// Pin `<project>/.trusty-code/<relative>`, creating it if absent.
80 ///
81 /// Why: every trusty-code write target is reached through this one
82 /// constructor so the boundary check and the descent cannot drift apart.
83 /// What, in order:
84 /// 1. [`anchor_native_root`] — the unchanged ADR-0044 membership rule (a
85 /// cross-product or escaping target keeps its existing error), which
86 /// hands back the ONE canonical `.trusty-code` it approved.
87 /// 2. That exact path — not a fresh resolution of it — is pinned by
88 /// descending from `/` with `O_NOFOLLOW` at every component. Resolving
89 /// once is what keeps a `.trusty-code` symlink that stays inside the
90 /// project working while leaving nothing for a swap to redirect: a
91 /// `.trusty-code` replaced after step 1 cannot move the descent, because
92 /// the descent never reads that name again (#7779 round 2).
93 /// 3. Each component of `relative` is created with `mkdirat` and opened with
94 /// `O_NOFOLLOW`, so a symlink at any of them fails CLOSED with
95 /// [`WriteTargetError::Unpinned`] rather than being followed.
96 ///
97 /// An absent `.trusty-code` is created under the canonical project root; a
98 /// project root that cannot be canonicalised is refused, never assumed safe.
99 /// Test: `paths::write_dir_tests::pinned_write_lands_at_the_validated_path`,
100 /// `paths::write_dir_tests::symlinked_component_is_refused_at_open`,
101 /// `paths::write_dir_tests::symlinked_native_root_escape_is_refused_at_open`,
102 /// `paths::write_dir_tests::native_root_swapped_between_check_and_pin_never_reaches_victim`.
103 pub fn open(project_root: &Path, relative: &Path) -> Result<Self, WriteTargetError> {
104 let path = native_config_dir(project_root).join(relative);
105 let mut fd = pin_native_root(project_root, &path)?;
106 for component in relative.components() {
107 let Component::Normal(name) = component else {
108 return Err(WriteTargetError::Unpinnable {
109 path: path.clone(),
110 detail: format!(
111 "`{}` is not a plain relative path under the config root",
112 relative.display()
113 ),
114 });
115 };
116 fd = create_dir_at(fd.as_fd(), name, &path)?;
117 }
118 Ok(Self { fd, path })
119 }
120
121 /// The path this handle was validated as, for diagnostics and logging.
122 pub fn path(&self) -> &Path {
123 &self.path
124 }
125
126 /// Pin a subdirectory, creating it if absent.
127 ///
128 /// Why: the skill-refs tree is two levels deep (`<skill>/SKILL.md`), and
129 /// re-deriving the whole descent per file would reopen the window this type
130 /// closes.
131 /// What: [`NativeWriteDir::open`]'s component loop, rooted at this handle
132 /// rather than at the project. A parent detached by a swap reports
133 /// [`WriteTargetError::Unpinned`], not the bare `ENOENT` `mkdirat` raises for
134 /// it.
135 /// Test: `paths::write_dir_tests::child_dir_is_pinned_like_its_parent`,
136 /// `agents::deploy::deploy_tests::swapped_skill_refs_dir_never_reaches_the_victim`.
137 pub fn child(&self, relative: &Path) -> Result<Self, WriteTargetError> {
138 let path = self.path.join(relative);
139 let mut fd = self.fd.try_clone().map_err(|e| unpinnable(&path, &e))?;
140 for component in relative.components() {
141 let Component::Normal(name) = component else {
142 return Err(WriteTargetError::Unpinnable {
143 path,
144 detail: format!("`{}` is not a plain relative path", relative.display()),
145 });
146 };
147 fd = match create_dir_at(fd.as_fd(), name, &path) {
148 Ok(fd) => fd,
149 Err(e) => {
150 // #7779: say "swapped", not "missing", when this handle is
151 // the thing that went away.
152 self.verify_pinned()?;
153 return Err(e);
154 }
155 };
156 }
157 Ok(Self { fd, path })
158 }
159
160 /// Read one file in this directory; `Ok(None)` when it does not exist.
161 ///
162 /// Why: the deploy decides "already current" and "hand-edited" from these
163 /// bytes, so reading them through the pinned handle is what keeps the
164 /// decision and the write talking about the same directory.
165 /// What: `openat` with `O_NOFOLLOW`. A SYMLINKED entry is
166 /// [`WriteTargetError::Unpinned`], never silently read through — #7727's
167 /// refusal of a committed symlink in the skill-refs tree depends on it.
168 /// Test: `paths::write_dir_tests::pinned_write_lands_at_the_validated_path`,
169 /// `agents::deploy::deploy_tests::symlinked_skill_ref_file_is_refused_before_any_write`.
170 pub fn read(&self, name: &str) -> Result<Option<Vec<u8>>, WriteTargetError> {
171 let c = cstring(name, &self.path)?;
172 let flags = libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
173 // SAFETY: `self.fd` is a live directory descriptor for the whole call
174 // and `c` is a NUL-terminated string that outlives the `openat`.
175 let raw = unsafe { libc::openat(self.fd.as_raw_fd(), c.as_ptr(), flags) };
176 if raw < 0 {
177 let err = std::io::Error::last_os_error();
178 if err.kind() == std::io::ErrorKind::NotFound {
179 return Ok(None);
180 }
181 return Err(open_error(&self.path, name, &err));
182 }
183 // SAFETY: `raw` is a fresh descriptor owned by this call alone.
184 let mut file = File::from(unsafe { OwnedFd::from_raw_fd(raw) });
185 let mut buf = Vec::new();
186 std::io::Read::read_to_end(&mut file, &mut buf).map_err(|e| unpinnable(&self.path, &e))?;
187 Ok(Some(buf))
188 }
189
190 /// Atomically replace one file in this directory.
191 ///
192 /// Why: the write half of the boundary. Temp-then-rename keeps a concurrent
193 /// reader from seeing a partial file, exactly as the shared deployer's
194 /// `atomic_write` does; doing both `openat`-relative to the pinned handle is
195 /// what keeps them inside the validated directory.
196 /// What: `openat(O_CREAT|O_EXCL|O_NOFOLLOW)` on a per-process, per-attempt
197 /// scratch name, then `renameat` onto `name`. A failed write or rename
198 /// removes the scratch file. [`NativeWriteDir::verify_pinned`] runs on both
199 /// exits: the bytes can only ever have landed in the validated directory,
200 /// but a swap means nothing will read them there, so it is reported rather
201 /// than swallowed — and a handle detached by `rmdir` reports the swap rather
202 /// than the bare `ENOENT` the kernel raises for it.
203 /// Test: `paths::write_dir_tests::pinned_write_lands_at_the_validated_path`,
204 /// `paths::write_dir_tests::component_swapped_after_open_never_reaches_victim`.
205 pub fn atomic_write(&self, name: &str, content: &[u8]) -> Result<(), WriteTargetError> {
206 let nanos = std::time::SystemTime::now()
207 .duration_since(std::time::UNIX_EPOCH)
208 .map(|d| d.as_nanos())
209 .unwrap_or_default();
210 let scratch = format!("{name}.{}.{nanos}.tmp", std::process::id());
211
212 let written = self
213 .create_new_file(&scratch)
214 .and_then(|mut f| f.write_all(content).map_err(|e| unpinnable(&self.path, &e)))
215 .and_then(|()| self.rename(&scratch, name));
216 if let Err(e) = written {
217 self.unlink(&scratch);
218 // #7779: a directory removed or renamed out from under the handle
219 // surfaces as ENOENT; name the real failure instead.
220 self.verify_pinned()?;
221 return Err(e);
222 }
223 self.verify_pinned()
224 }
225
226 /// Create one file in this directory, refusing to replace an existing one.
227 ///
228 /// Why: the legacy import's "never overwrite a user-authored file" rule was
229 /// an `exists()` test taken while planning, which the apply step could be
230 /// arbitrarily long behind. `O_EXCL` makes the kernel decide it at the
231 /// moment of the write.
232 /// What: `openat(O_CREAT|O_EXCL|O_NOFOLLOW)`; an existing target yields
233 /// [`WriteTargetError::Unpinnable`] carrying the `EEXIST` text, which the
234 /// import reports as a refusal.
235 /// Test: `paths::write_dir_tests::create_new_refuses_an_existing_file`.
236 pub fn create_new(&self, name: &str, content: &[u8]) -> Result<(), WriteTargetError> {
237 let written = self
238 .create_new_file(name)
239 .and_then(|mut f| f.write_all(content).map_err(|e| unpinnable(&self.path, &e)));
240 if let Err(e) = written {
241 // #7779: `EEXIST` is a legitimate refusal, not a swap — only a
242 // detached handle escalates to `Unpinned`.
243 self.verify_pinned()?;
244 return Err(e);
245 }
246 self.verify_pinned()
247 }
248
249 /// Take the exclusive `flock(2)` on a sidecar in this directory.
250 ///
251 /// Why: the shared deployer serialises concurrent writers on
252 /// `<dir>/.trusty-mpm-manifest.json.lock`. Deploying through a scratch
253 /// directory would otherwise move that lock off the project directory and
254 /// silently drop the cross-process guarantee.
255 /// What: `openat(O_CREAT|O_RDWR|O_NOFOLLOW)` then a blocking `LOCK_EX`. The
256 /// returned handle releases the lock when dropped.
257 /// Test: `paths::write_dir_tests::ledger_lock_is_exclusive_across_handles`.
258 pub fn lock_exclusive(&self, name: &str) -> Result<File, WriteTargetError> {
259 let c = cstring(name, &self.path)?;
260 let flags = libc::O_RDWR | libc::O_CREAT | libc::O_NOFOLLOW | libc::O_CLOEXEC;
261 // SAFETY: `self.fd` is live for the call; `c` is NUL-terminated and
262 // outlives it. The variadic mode argument is required by `O_CREAT`.
263 let raw = unsafe {
264 libc::openat(
265 self.fd.as_raw_fd(),
266 c.as_ptr(),
267 flags,
268 0o600 as libc::c_uint,
269 )
270 };
271 if raw < 0 {
272 return Err(open_error(
273 &self.path,
274 name,
275 &std::io::Error::last_os_error(),
276 ));
277 }
278 // SAFETY: `raw` is a fresh descriptor owned by this call alone.
279 let file = File::from(unsafe { OwnedFd::from_raw_fd(raw) });
280 // SAFETY: `file` owns `raw` for the duration of the `flock` call.
281 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {
282 return Err(open_error(
283 &self.path,
284 name,
285 &std::io::Error::last_os_error(),
286 ));
287 }
288 Ok(file)
289 }
290
291 /// Confirm the pinned directory is still the one `path()` names.
292 ///
293 /// Why: `openat` writes cannot be redirected, so a swap makes them land in a
294 /// directory that is no longer reachable by name — correct, but useless. The
295 /// caller has to hear about it; a deploy that "succeeded" into a detached
296 /// inode is a failed deploy.
297 /// What: compares the handle's `(dev, ino)` with the path's. Any mismatch,
298 /// including a path that no longer resolves, is
299 /// [`WriteTargetError::Unpinned`].
300 ///
301 /// This is a REPORT, never the boundary — it re-resolves `path` and so can
302 /// only be trusted because [`NativeWriteDir::open`] guarantees the pinned
303 /// side is a directory the membership rule approved. While that held only
304 /// for the first of two resolutions, a swap could make both sides name the
305 /// same victim and this function called it healthy (152 times in the
306 /// code-critic race model, #7779 round 2). It cannot now: the pinned inode
307 /// is inside the project, so a live swap makes the two differ and a reverted
308 /// one makes them agree about a write that did land correctly.
309 /// Test: `paths::write_dir_tests::component_swapped_after_open_never_reaches_victim`,
310 /// `paths::write_dir_tests::native_root_swapped_between_check_and_pin_never_reaches_victim`.
311 pub fn verify_pinned(&self) -> Result<(), WriteTargetError> {
312 let unpinned = || WriteTargetError::Unpinned {
313 path: self.path.clone(),
314 component: self
315 .path
316 .file_name()
317 .unwrap_or_else(|| OsStr::new(TRUSTY_CODE_DIRNAME))
318 .to_string_lossy()
319 .into_owned(),
320 };
321 let dup = self.fd.try_clone().map_err(|_| unpinned())?;
322 let pinned = File::from(dup).metadata().map_err(|_| unpinned())?;
323 let named = std::fs::metadata(&self.path).map_err(|_| unpinned())?;
324 if pinned.dev() == named.dev() && pinned.ino() == named.ino() {
325 Ok(())
326 } else {
327 Err(unpinned())
328 }
329 }
330
331 /// `openat(O_CREAT|O_EXCL|O_NOFOLLOW)` — shared by both write entry points.
332 fn create_new_file(&self, name: &str) -> Result<File, WriteTargetError> {
333 let c = cstring(name, &self.path)?;
334 let flags =
335 libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC;
336 // SAFETY: `self.fd` is live for the call; `c` is NUL-terminated and
337 // outlives it. The variadic mode argument is required by `O_CREAT`.
338 let raw = unsafe {
339 libc::openat(
340 self.fd.as_raw_fd(),
341 c.as_ptr(),
342 flags,
343 0o644 as libc::c_uint,
344 )
345 };
346 if raw < 0 {
347 return Err(open_error(
348 &self.path,
349 name,
350 &std::io::Error::last_os_error(),
351 ));
352 }
353 // SAFETY: `raw` is a fresh descriptor owned by this call alone.
354 Ok(File::from(unsafe { OwnedFd::from_raw_fd(raw) }))
355 }
356
357 /// `renameat` within this one pinned directory.
358 fn rename(&self, from: &str, to: &str) -> Result<(), WriteTargetError> {
359 let old = cstring(from, &self.path)?;
360 let new = cstring(to, &self.path)?;
361 // SAFETY: `self.fd` is live for the call and both strings outlive it.
362 let rc = unsafe {
363 libc::renameat(
364 self.fd.as_raw_fd(),
365 old.as_ptr(),
366 self.fd.as_raw_fd(),
367 new.as_ptr(),
368 )
369 };
370 if rc != 0 {
371 return Err(open_error(&self.path, to, &std::io::Error::last_os_error()));
372 }
373 Ok(())
374 }
375
376 /// Best-effort scratch-file removal on a failed write; never masks the
377 /// original error.
378 fn unlink(&self, name: &str) {
379 let Ok(c) = CString::new(name) else { return };
380 // SAFETY: `self.fd` is live for the call and `c` outlives it.
381 unsafe { libc::unlinkat(self.fd.as_raw_fd(), c.as_ptr(), 0) };
382 }
383}
384
385/// Pin `<project>/.trusty-code`, creating it when absent.
386///
387/// Why: #7779 round 2. The membership rule and the descent used to resolve
388/// `.trusty-code` independently, and the descriptor came from the SECOND
389/// resolution — a swap landed between them in 1419 of 20138 completed writes in
390/// a code-critic race model, 152 of which `verify_pinned` then called healthy.
391/// The pinned directory is now the one [`anchor_native_root`] approved, by
392/// construction: this function never resolves that name itself.
393/// What: [`AnchoredRoot::Existing`]'s canonical path is descended from `/` with
394/// `O_NOFOLLOW`; [`AnchoredRoot::Absent`] means the root is created under the
395/// canonical project root, itself descended the same way. A project root that
396/// cannot be canonicalised is refused.
397///
398/// What remains possible, precisely: a directory swapped in AT that approved
399/// canonical path — a rename, not a symlink, since every component is opened
400/// `O_NOFOLLOW`. Such a directory is still at a path the membership rule
401/// authorises, which is the property ADR-0044 asks for. No path outside it can
402/// be pinned.
403/// Test: `paths::write_dir_tests::symlinked_native_root_escape_is_refused_at_open`,
404/// `paths::write_dir_tests::native_root_swapped_between_check_and_pin_never_reaches_victim`.
405fn pin_native_root(project_root: &Path, target: &Path) -> Result<OwnedFd, WriteTargetError> {
406 match anchor_native_root(project_root, target)? {
407 AnchoredRoot::Existing(canon) => pin_absolute(&canon, target),
408 AnchoredRoot::Absent => {
409 let project = project_root
410 .canonicalize()
411 .map_err(|e| unpinnable(target, &e))?;
412 let root = pin_absolute(&project, target)?;
413 create_dir_at(root.as_fd(), OsStr::new(TRUSTY_CODE_DIRNAME), target)
414 }
415 }
416}
417
418/// Descend an already-canonical absolute path, refusing every symlink.
419///
420/// Why: `canonicalize` proves the path held no symlink when it ran; walking it
421/// again with `O_NOFOLLOW` proves none was introduced since.
422/// What: opens `/`, then `openat(O_DIRECTORY|O_NOFOLLOW)` per component.
423/// Test: `paths::write_dir_tests::pinned_write_lands_at_the_validated_path`.
424fn pin_absolute(canonical: &Path, target: &Path) -> Result<OwnedFd, WriteTargetError> {
425 let root = File::open(Path::new("/")).map_err(|e| unpinnable(target, &e))?;
426 let mut fd = OwnedFd::from(root);
427 for component in canonical.components() {
428 if let Component::Normal(name) = component {
429 fd = open_dir_at(fd.as_fd(), name, target)?;
430 }
431 }
432 Ok(fd)
433}
434
435/// `mkdirat` then `openat(O_DIRECTORY|O_NOFOLLOW)`; an existing directory is
436/// opened, an existing symlink is refused.
437fn create_dir_at(
438 parent: BorrowedFd<'_>,
439 name: &OsStr,
440 target: &Path,
441) -> Result<OwnedFd, WriteTargetError> {
442 let c = cstring_os(name, target)?;
443 // SAFETY: `parent` is live for the call and `c` outlives it.
444 let rc = unsafe { libc::mkdirat(parent.as_raw_fd(), c.as_ptr(), 0o755) };
445 if rc != 0 {
446 let err = std::io::Error::last_os_error();
447 if err.kind() != std::io::ErrorKind::AlreadyExists {
448 return Err(open_error(target, &name.to_string_lossy(), &err));
449 }
450 }
451 open_dir_at(parent, name, target)
452}
453
454/// `openat(O_DIRECTORY|O_NOFOLLOW)` — the single place a symlinked component is
455/// turned into [`WriteTargetError::Unpinned`].
456fn open_dir_at(
457 parent: BorrowedFd<'_>,
458 name: &OsStr,
459 target: &Path,
460) -> Result<OwnedFd, WriteTargetError> {
461 let c = cstring_os(name, target)?;
462 let flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
463 // SAFETY: `parent` is live for the call and `c` outlives it.
464 let raw = unsafe { libc::openat(parent.as_raw_fd(), c.as_ptr(), flags) };
465 if raw < 0 {
466 return Err(open_error(
467 target,
468 &name.to_string_lossy(),
469 &std::io::Error::last_os_error(),
470 ));
471 }
472 // SAFETY: `raw` is a fresh descriptor owned by this call alone.
473 Ok(unsafe { OwnedFd::from_raw_fd(raw) })
474}
475
476/// `ELOOP`/`ENOTDIR` means a link was swapped in; anything else is plain I/O.
477///
478/// Why: the two have different fixes — one is an attack or a misconfigured tree,
479/// the other is a full disk or a permission problem — and collapsing them would
480/// hide which.
481/// Test: `paths::write_dir_tests::symlinked_component_is_refused_at_open`.
482fn open_error(target: &Path, component: &str, err: &std::io::Error) -> WriteTargetError {
483 let raw = err.raw_os_error();
484 if raw == Some(libc::ELOOP) || raw == Some(libc::ENOTDIR) {
485 return WriteTargetError::Unpinned {
486 path: target.to_path_buf(),
487 component: component.to_string(),
488 };
489 }
490 WriteTargetError::Unpinnable {
491 path: target.to_path_buf(),
492 detail: format!("{component}: {err}"),
493 }
494}
495
496fn unpinnable(target: &Path, err: &std::io::Error) -> WriteTargetError {
497 WriteTargetError::Unpinnable {
498 path: target.to_path_buf(),
499 detail: err.to_string(),
500 }
501}
502
503/// A NUL-free name that is exactly ONE path component.
504///
505/// Why: `O_NOFOLLOW` guards only the LAST component of an `openat` name, so a
506/// `name` carrying a separator would have its leading components resolved with
507/// symlinks followed — the very thing this module exists to stop. No caller
508/// passes one today; [`NativeWriteDir`] is `pub`, so the type has to refuse it
509/// rather than rely on that (#7779 round 2).
510/// What: rejects an empty name, `.`, `..`, anything absolute, anything with a
511/// separator, and anything with an interior NUL.
512/// Test: `paths::write_dir_tests::a_name_with_a_path_separator_is_refused`.
513fn cstring(name: &str, target: &Path) -> Result<CString, WriteTargetError> {
514 let unusable = || WriteTargetError::Unpinnable {
515 path: target.to_path_buf(),
516 detail: format!("`{name}` is not a usable file name"),
517 };
518 let mut components = Path::new(name).components();
519 match (components.next(), components.next()) {
520 (Some(Component::Normal(one)), None) if one == OsStr::new(name) => {}
521 _ => return Err(unusable()),
522 }
523 CString::new(name).map_err(|_| unusable())
524}
525
526fn cstring_os(name: &OsStr, target: &Path) -> Result<CString, WriteTargetError> {
527 CString::new(name.as_bytes()).map_err(|_| WriteTargetError::Unpinnable {
528 path: target.to_path_buf(),
529 detail: format!("`{}` is not a usable file name", name.to_string_lossy()),
530 })
531}
532
533#[cfg(test)]
534#[path = "write_dir_tests.rs"]
535mod write_dir_tests;