zond-engine 0.18.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # Creating a file inside a journal
//!
//! Three things that must not be separated: the mode it is created with, who it
//! then belongs to, and that it is the file this crate meant rather than a link
//! standing where one should be.
//!
//! A journal holds the addresses an engagement was pointed at, so every file is
//! `0600` from creation rather than chmod'd after, and when the scan ran under
//! `sudo` it is given to the user who invoked it rather than left to root.
//! [`paths`](crate::journal::paths) explains why the journal goes to the
//! invoking user's home; this is the other half of that answer, without which
//! it goes to their home and stays unreadable to them.
//!
//! They live together because separating them costs exactly that. A cursor
//! writer with its own copy of the mode and none of the ownership would leave
//! `cursor.json` owned by root after a sweep run with `sudo`, beside a manifest
//! and findings owned by the user. An unprivileged listing would read the plan
//! and not the progress, and report every scan as untouched.
//!
//! ## Why nothing here takes a path twice
//!
//! Giving the journal to the invoking user means the directory it sits in
//! belongs to them, and the names inside it are fixed. A root process opening
//! `cursor.json.tmp` by path, truncating it, and then chowning that path is a
//! root process doing both of those to whatever the user pointed the name at.
//! `O_NOFOLLOW` refuses a link where a journal file should be, and every
//! ownership change goes through the descriptor already open rather than
//! through the name, so there is no second lookup to redirect between them.
//!
//! Taking a lock is the one file this does not open. It has to appear at its name
//! already holding its record, or a racer reads a lock mid-creation and finds it
//! empty. See `lock::Lock::create_exclusively`, which stages the content through
//! [`link_new`](crate::journal::file::link_new) here and links it into place.
//!
//! Directories are opened the same way for the same reason.
//!
//! Reading is opened the same way too. A root process resuming a scan reads
//! the manifest, the cursor and the findings out of that user's directory, and
//! a link at one of those names would have it read whatever the user chose and
//! take it for the job's; see
//! [`open_to_read`](crate::journal::file::open_to_read) for why such a job is
//! refused by name rather than read as one that recorded nothing.
//!
//! ## Why nothing here is created through a link above it either
//!
//! `O_NOFOLLOW` guards the last name, and every name above it is the invoking
//! user's to place as well. Under `sudo` a journal's files and directories are
//! created relative to a directory reached from that user's home without
//! following a link out of it; see
//! [`ownership::Place`](crate::journal::ownership::Place) for why, and for why a link
//! that stays inside the home still works. What renames, links or removes a
//! name that is already there is reached the same way, since a lookup by path
//! between staging a file and renaming it is one more lookup a link above it
//! could redirect: [`replace`](crate::journal::file::replace),
//! [`link_new`](crate::journal::file::link_new),
//! [`remove`](crate::journal::file::remove) and
//! [`remove_directory`](crate::journal::file::remove_directory) are how a
//! journal changes a name, and nothing in it does so by path.

use std::fs;
use std::path::Path;

use super::ownership::{Directory, Kind, Place};

/// Creates a file in a journal: private, the invoking user's, and new.
///
/// The mode is set as the file is created rather than after, so there is no
/// moment where what a scan is recording can be read by anyone else. The
/// directory is `0700` as well, which would cover it either way.
///
/// Create-only, which is what every caller means. Create *or truncate* would
/// mean a root process truncating and then chowning whatever the directory's
/// owner had put at the name. `O_NOFOLLOW` already refuses a symlink there, so
/// the residual case is a planted regular file: narrow, since the directory is
/// `0700` and the planter would be its owner, but narrow is not the same as
/// closed. `create_new` closes it: a name that already exists is refused rather
/// than emptied.
///
/// The files a journal writes whole, through a staged sibling, want a name
/// that may be left over from an interrupted run; [`replace`] and
/// [`link_new`] stage them, which is this with one deliberate retry.
pub(super) fn create_private(path: &Path) -> std::io::Result<fs::File> {
    create_in(&Place::of(path)?, path)
}

/// [`create_private`] at a name already reached; `path` is what it is called.
fn create_in(place: &Place, path: &Path) -> std::io::Result<fs::File> {
    let file = open_in(place, path, Access::CreateNew)?;
    claim(&file, path);
    Ok(file)
}

/// Creates a staging file, discarding one an interrupted run left behind.
///
/// [`create_private`] refuses a name that exists, which is right for the files
/// a journal creates once and wrong for those it re-creates every time it
/// writes whole: `cursor.json.tmp` on every checkpoint, `hosts.jsonl-tmp` on
/// every compaction. Each is renamed away on success and removed on failure,
/// so a leftover means a previous run died between the create and the rename,
/// and refusing forever after that would wedge the journal, trading the defect
/// `create_new` closes for a failure of its own.
///
/// The removal is safe in the way truncation is not. It unlinks the name, so
/// a symlink planted there loses the link rather than the target, and the
/// retry is still `create_new` under `O_NOFOLLOW`: if something wins the race
/// and plants a file between the two calls, this fails rather than opening
/// it. A refused checkpoint is a cost; a truncated stranger is a defect.
fn stage(place: &Place, path: &Path) -> std::io::Result<fs::File> {
    match create_in(place, path) {
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
            place.remove()?;
            create_in(place, path)
        }
        other => other,
    }
}

/// Writes a journal file whole: `write` fills a file staged at `staged`, which
/// is then renamed over `destination`, so the name holds all of what was there
/// or all of what was written and never part of either.
///
/// `staged` lies beside `destination`, in the same directory, and both are
/// reached through one walk; see [`Place::beside`]. The staged file is closed
/// before the rename, since `write` takes it, because renaming over a file
/// still held open is a hazard on platforms this may yet reach. The
/// destination becomes the staged file's inode, which already carries the
/// mode and the ownership [`create_private`] gives.
///
/// A write or a rename that fails removes what it staged, so a failure leaves
/// nothing behind beside the destination for the next attempt to discard.
pub(super) fn replace<T, E: From<std::io::Error>>(
    destination: &Path,
    staged: &Path,
    write: impl FnOnce(fs::File) -> Result<T, E>,
) -> Result<T, E> {
    replace_at(&Place::of(destination)?, destination, staged, write)
}

/// [`replace`] at a destination already reached.
fn replace_at<T, E: From<std::io::Error>>(
    target: &Place,
    destination: &Path,
    staged: &Path,
    write: impl FnOnce(fs::File) -> Result<T, E>,
) -> Result<T, E> {
    let staging = target.beside(sibling(destination, staged)?)?;
    let file = stage(&staging, staged)?;
    let replaced = write(file).and_then(|written| {
        staging.rename_over(target)?;
        Ok(written)
    });
    if replaced.is_err() {
        let _ = staging.remove();
    }
    replaced
}

/// Puts a file at `destination` holding what `write` wrote, refusing a name
/// that exists there.
///
/// For a file that must appear at its name already whole, where creating it
/// and then writing it would let a reader find it empty: the lock. Staged at
/// `staged` as [`replace`] stages, and then linked into place, since a link
/// refuses a name that exists, the same exclusion `create_new` gives, over a
/// file that already has its contents. The staged name is removed either way.
pub(super) fn link_new(
    destination: &Path,
    staged: &Path,
    write: impl FnOnce(fs::File) -> std::io::Result<()>,
) -> std::io::Result<()> {
    link_new_at(&Place::of(destination)?, destination, staged, write)
}

/// [`link_new`] at a destination already reached.
fn link_new_at(
    target: &Place,
    destination: &Path,
    staged: &Path,
    write: impl FnOnce(fs::File) -> std::io::Result<()>,
) -> std::io::Result<()> {
    let staging = target.beside(sibling(destination, staged)?)?;
    let file = stage(&staging, staged)?;
    let linked = write(file).and_then(|()| staging.link_as(target));
    let _ = staging.remove();
    linked
}

/// `staged`'s name, where it lies beside `destination`.
fn sibling<'a>(destination: &Path, staged: &'a Path) -> std::io::Result<&'a std::ffi::OsStr> {
    debug_assert_eq!(
        destination.parent(),
        staged.parent(),
        "a file is staged beside its destination"
    );
    staged.file_name().ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("{} names no file", staged.display()),
        )
    })
}

/// Opens an existing journal file to add to it, keeping what is already there.
///
/// [`create_private`] for the files written a record at a time. The mode is not
/// set, because the file exists and the one that created it set it.
pub(super) fn append_existing(path: &Path) -> std::io::Result<fs::File> {
    open(path, Access::Append)
}

/// Opens an existing journal file for reading and writing, to inspect and mend
/// it before anything is added to it.
///
/// [`append_existing`] can only add to the end, which is what makes it cheap and
/// what makes it blind: an append-only descriptor cannot see whether the file
/// carries a header or whether its last line ever finished. `store`'s
/// `open_for_append` asks both questions through this handle first.
///
/// Neither creates and neither truncates, so a name that is not there is still
/// an error and what is in the file is still whatever was written. The mode is
/// not set for the same reason [`append_existing`] does not set it: the file
/// exists, and the call that created it set it.
pub(super) fn open_existing(path: &Path) -> std::io::Result<fs::File> {
    open(path, Access::ReadWrite)
}

/// Opens a journal's rendezvous file, creating it if it is not there yet.
///
/// The one shape neither [`create_private`] nor [`replace`] fits: a file
/// every racer must be able to *open*, where creating it is incidental and
/// winning the create decides nothing. `journal::lock`'s `break` file is the
/// only one: the lock taken on it lives on the open file, so what matters is
/// that every process ends up on the same one.
///
/// No truncate, because there is nothing in it to empty and a truncate would be
/// one more thing a racer could do to a file another racer holds. The mode and
/// `O_NOFOLLOW` are the same as everywhere else here.
pub(super) fn open_or_create_private(path: &Path) -> std::io::Result<fs::File> {
    let file = open(path, Access::CreateOrOpen)?;
    claim(&file, path);
    Ok(file)
}

/// Removes a journal file's name: a link at it rather than what the link
/// points to, and relative to the directory holding it, reached as every
/// opener here reaches a name.
pub(super) fn remove(path: &Path) -> std::io::Result<()> {
    Place::of(path)?.remove()
}

/// Removes a journal's directory and everything in it, each name looked up
/// relative to the directory holding it; see [`Place::remove_tree`].
///
/// A journal is removed by whoever may prune it, which under `sudo` is root
/// in a directory the invoking user arranges. By path, a link placed above
/// the journal between the decision and the removal would have root remove
/// whatever stands under the journal's name wherever the link leads.
pub(super) fn remove_directory(path: &Path) -> std::io::Result<()> {
    Place::of(path)?.remove_tree()
}

/// Creates one scan's directory, private from the moment it exists.
///
/// The mode is set as the directory is created rather than chmod'd afterwards,
/// which is the same rule this module applies to everything inside it and for
/// the same two reasons. Creating at the default mode leaves a window in which
/// the addresses an engagement was pointed at are world-readable, and a `chmod`
/// by path is a privileged operation on a name in a directory this engine has
/// just given to an unprivileged user.
///
/// Fails with [`AlreadyExists`](std::io::ErrorKind::AlreadyExists) on a
/// directory that is already there, which is what makes a minted id that
/// collides a retry rather than two scans sharing one journal.
#[cfg(unix)]
pub(super) fn create_private_directory(path: &Path) -> std::io::Result<()> {
    Place::of(path)?.create_directory(0o700)
}

/// The platforms with no mode to set at creation, where the directory is created
/// and nothing more is promised about it.
#[cfg(not(unix))]
pub(super) fn create_private_directory(path: &Path) -> std::io::Result<()> {
    fs::create_dir(path)
}

/// Opens a journal file to read it, refusing a link standing at its name.
///
/// Every file a journal holds is created by this module, and none of its
/// openers ever leaves a link at a journal's name, so one there is not a
/// journal file of any shape: it is a job that cannot be read, and the error
/// says a link is why. Read as damaged instead, the job would list as a scan
/// that found nothing, which is not what happened to it. Followed, it would
/// have a process that is usually root read whatever the directory's owner
/// pointed it at, and report what it found there as the job's own.
///
/// Reached as every other opener here reaches a name, so under `sudo` a link
/// above it that leads out of the invoking user's home is refused as well.
pub(super) fn open_to_read(path: &Path) -> std::io::Result<fs::File> {
    open(path, Access::Read)
}

/// The names in the directory at `path`, reached as every opener here
/// reaches a name; see [`Directory`].
pub(super) fn names(path: &Path) -> std::io::Result<Vec<std::ffi::OsString>> {
    Directory::of(path)?.names()
}

/// The names in the directory at `path`, each with what stands at it, a link
/// being a link, looked at relative to the directory holding it; see
/// [`Directory`]. A name gone by the time it is looked at is passed over.
pub(super) fn kinds(path: &Path) -> std::io::Result<Vec<(std::ffi::OsString, Kind)>> {
    let directory = Directory::of(path)?;
    Ok(directory
        .names()?
        .into_iter()
        .filter_map(|name| {
            let kind = directory.entry(&name).and_then(|entry| entry.kind()).ok()?;
            Some((name, kind))
        })
        .collect())
}

/// Whether anything stands at `path`, a link included, asked of the name
/// itself and reached as every opener here reaches a name.
///
/// A directory above it that is not there is nothing at the name either.
pub(super) fn exists(path: &Path) -> std::io::Result<bool> {
    match Place::of(path) {
        Ok(place) => place.exists(),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(e),
    }
}

/// The five ways a journal file is opened.
#[derive(Clone, Copy)]
enum Access {
    /// Created, and refused if the name exists.
    CreateNew,
    /// Created if missing, opened for reading and writing either way.
    CreateOrOpen,
    /// Opened to add to its end.
    Append,
    /// Opened for reading and writing.
    ReadWrite,
    /// Opened for reading.
    Read,
}

/// Opens a journal file private, refusing a link at its name, and reached the
/// way [`Place`] reaches it.
fn open(path: &Path, how: Access) -> std::io::Result<fs::File> {
    open_in(&Place::of(path)?, path, how)
}

/// [`open`] at a name already reached; `path` is what it is called.
///
/// A link refused at the name is said to be one: the system's own word for it
/// is a loop of links, which names no link the reader placed and sends them
/// looking for a cycle there is none of.
#[cfg(unix)]
fn open_in(place: &Place, path: &Path, how: Access) -> std::io::Result<fs::File> {
    let flags = match how {
        Access::CreateNew => libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL,
        Access::CreateOrOpen => libc::O_RDWR | libc::O_CREAT,
        Access::Append => libc::O_WRONLY | libc::O_APPEND,
        Access::ReadWrite => libc::O_RDWR,
        Access::Read => libc::O_RDONLY,
    };
    place.open(flags, 0o600).map_err(|error| {
        // Asked of the name itself, where it was reached, to tell a link at
        // it from a loop further up, which fails the same way.
        let linked = error.raw_os_error() == Some(libc::ELOOP)
            && place.kind().is_ok_and(|kind| kind == Kind::Link);
        if linked {
            std::io::Error::other(format!(
                "{} is a link, not a journal file (not followed)",
                path.display()
            ))
        } else {
            error
        }
    })
}

/// The platforms with no mode to set at open. Nothing is promised about who else
/// can read a journal there, which is one of the reasons the crate does not claim
/// to support them.
#[cfg(not(unix))]
fn open_in(place: &Place, _path: &Path, how: Access) -> std::io::Result<fs::File> {
    let mut options = fs::OpenOptions::new();
    match how {
        Access::CreateNew => options.write(true).create_new(true),
        Access::CreateOrOpen => options.read(true).write(true).create(true),
        Access::Append => options.append(true),
        Access::ReadWrite => options.read(true).write(true),
        Access::Read => options.read(true),
    };
    options.open(place.path())
}

/// Gives a directory a journal created under `sudo` to the user who invoked
/// it, when it lies in their home.
///
/// The file cases claim through the handle they already hold. A directory has
/// none, so one is opened for it, refusing a link in the same position for the
/// same reason. The boundary is the one every giving shares; see
/// [`ownership`](super::ownership).
pub(super) fn claim_directory_for_invoking_user(path: &Path) {
    super::ownership::give(path);
}

/// Gives a file a journal wrote under `sudo` to the user who invoked it, when
/// it lies in their home.
///
/// Best effort: a journal left owned by root is one they can neither read nor
/// prune, which is worth trying to avoid and not worth failing a scan over.
/// Taking the descriptor rather than the path is what stops the name being
/// repointed between the open and the change of owner.
fn claim(file: &fs::File, path: &Path) {
    super::ownership::give_open(file, path);
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use std::io::Write;

    fn scratch(name: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("zond-file-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).expect("a scratch directory");
        dir
    }

    /// The journal lives in a directory this engine gives to the invoking user,
    /// under fixed names, and is written by a process that is usually root. A
    /// link standing where a journal file should be is the one thing that turns
    /// that arrangement into somebody else's file being truncated.
    #[test]
    fn a_link_where_a_journal_file_should_be_is_refused() {
        let dir = scratch("nofollow");
        let elsewhere = dir.join("elsewhere");
        fs::write(&elsewhere, b"not the journal's to touch").expect("writes");

        let planted = dir.join("cursor.json.tmp");
        std::os::unix::fs::symlink(&elsewhere, &planted).expect("links");

        for opened in [
            create_private(&planted).err(),
            append_existing(&planted).err(),
        ] {
            assert!(opened.is_some(), "a link was opened as a journal file");
        }

        assert_eq!(
            fs::read(&elsewhere).expect("reads"),
            b"not the journal's to touch",
            "the file behind the link was written through"
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// And an ordinary file still opens, both ways.
    #[test]
    fn an_ordinary_journal_file_opens_and_is_private() {
        use std::os::unix::fs::PermissionsExt;

        let dir = scratch("ordinary");
        let path = dir.join("findings");

        create_private(&path)
            .expect("creates")
            .write_all(b"one")
            .expect("writes");
        append_existing(&path)
            .expect("appends")
            .write_all(b"two")
            .expect("writes");

        assert_eq!(fs::read(&path).expect("reads"), b"onetwo");
        assert_eq!(
            fs::metadata(&path).expect("stats").permissions().mode() & 0o777,
            0o600
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// `O_NOFOLLOW` covers a link planted at a journal's name; it says nothing
    /// about an ordinary file planted there. Opened with truncation, that one
    /// would be emptied and then chowned to the invoking user by a process that
    /// is usually root.
    #[test]
    fn a_file_already_at_a_journal_name_is_refused_rather_than_emptied() {
        let dir = scratch("create-only");
        let planted = dir.join("manifest.json");
        fs::write(&planted, b"somebody else's bytes").expect("writes");

        let refusal = create_private(&planted).expect_err("a name that exists was created over");
        assert_eq!(refusal.kind(), std::io::ErrorKind::AlreadyExists);
        assert_eq!(
            fs::read(&planted).expect("reads"),
            b"somebody else's bytes",
            "the planted file was truncated"
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// Under `sudo` a file written whole is staged and then renamed or linked
    /// into place in the one directory the walk from the invoking user's home
    /// reached. Every name above it is that user's to rearrange meanwhile, and
    /// a rename, link or removal looked up by path after the staging follows
    /// a link placed in between to wherever it leads, having root rename,
    /// link or remove there whatever stands under a journal's fixed names.
    #[test]
    fn a_staged_file_is_put_in_place_where_it_was_staged_whatever_moves_above_it() {
        use crate::journal::paths::InvokingUser;

        let dir = scratch("walked");
        let home = dir.join("home");
        let elsewhere = dir.join("elsewhere");
        fs::create_dir_all(home.join("state/journal")).expect("a journal");
        fs::create_dir_all(elsewhere.join("journal")).expect("a directory outside");
        for name in ["cursor.tmp", "LOCK.lock-1"] {
            fs::write(elsewhere.join("journal").join(name), b"bait").expect("writes");
        }
        // SAFETY: neither call has any precondition.
        let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
        let user = InvokingUser::new(uid, gid, home.clone());

        // Leads `state` out of the home, the journal kept aside, and back.
        let redirect = || -> std::io::Result<()> {
            fs::rename(home.join("state"), home.join("kept"))?;
            std::os::unix::fs::symlink(&elsewhere, home.join("state"))
        };
        let restore = || {
            fs::remove_file(home.join("state")).expect("removes the link");
            fs::rename(home.join("kept"), home.join("state")).expect("restores");
        };

        let cursor = home.join("state/journal/cursor.json");
        let target = Place::of_as(Some(&user), &cursor).expect("reached");
        replace_at(
            &target,
            &cursor,
            &cursor.with_extension("tmp"),
            |mut file| {
                file.write_all(b"the journal's")?;
                redirect()
            },
        )
        .expect("replaces");
        restore();
        assert_eq!(fs::read(&cursor).expect("reads"), b"the journal's");

        let lock = home.join("state/journal/LOCK");
        let target = Place::of_as(Some(&user), &lock).expect("reached");
        link_new_at(
            &target,
            &lock,
            &lock.with_extension("lock-1"),
            |mut file| {
                file.write_all(b"held")?;
                redirect()
            },
        )
        .expect("links");
        restore();
        assert_eq!(fs::read(&lock).expect("reads"), b"held");

        let outside: Vec<_> = fs::read_dir(elsewhere.join("journal"))
            .expect("lists")
            .map(|entry| entry.expect("an entry").file_name())
            .collect();
        assert_eq!(
            outside.len(),
            2,
            "renamed or linked out of the home: {outside:?}"
        );
        for name in ["cursor.tmp", "LOCK.lock-1"] {
            assert_eq!(
                fs::read(elsewhere.join("journal").join(name)).expect("reads"),
                b"bait",
                "{name} was changed out of the home"
            );
        }

        fs::remove_dir_all(&dir).ok();
    }

    /// And the staging names, which a crashed run does leave behind, are the
    /// one place that refusal has to lift, or a journal wedges for good.
    #[test]
    fn a_staged_name_left_by_a_crashed_run_is_discarded_rather_than_wedging() {
        let dir = scratch("staged");
        let temporary = dir.join("cursor.json.tmp");
        fs::write(&temporary, b"a checkpoint that never got renamed").expect("writes");

        let destination = dir.join("cursor.json");
        replace(&destination, &temporary, |mut file| {
            file.write_all(b"the next one")
        })
        .expect("a leftover staging file is discarded");

        assert_eq!(fs::read(&destination).expect("reads"), b"the next one");
        assert!(!temporary.exists(), "the staged name was renamed away");

        // And it is still a link that cannot be followed: the removal unlinks the
        // name, and the create behind it is the same refusing one.
        let elsewhere = dir.join("elsewhere");
        fs::write(&elsewhere, b"not the journal's to touch").expect("writes");
        let linked = dir.join("hosts.jsonl-tmp");
        std::os::unix::fs::symlink(&elsewhere, &linked).expect("links");

        replace(&dir.join("hosts.jsonl"), &linked, |mut file| {
            file.write_all(b"compacted")
        })
        .expect("the link is unlinked and a real file created");
        assert_eq!(
            fs::read(&elsewhere).expect("reads"),
            b"not the journal's to touch",
            "the file behind the link was written through"
        );

        fs::remove_dir_all(&dir).ok();
    }
}