sparsync 0.1.12

rsync-style high-performance file synchronization over QUIC and Spargio
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
639
640
use crate::endpoint::RemoteEndpoint;
use crate::profile;
use anyhow::{Context, Result, bail};
use std::io::Write;
use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::Duration;

const DEFAULT_REMOTE_AUTH_SUBPATH: &str = ".config/sparsync/auth";
const DEFAULT_REMOTE_INSTALL_SUBPATH: &str = ".local/bin/sparsync";
const DEFAULT_REMOTE_SERVICE_SUBPATH: &str = ".config/sparsync/service";

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum InstallMode {
    Auto,
    Off,
    UploadLocalBinary,
    Ephemeral,
}

impl InstallMode {
    pub fn parse(value: &str) -> Result<Self> {
        match value {
            "auto" => Ok(Self::Auto),
            "off" => Ok(Self::Off),
            "upload-local-binary" => Ok(Self::UploadLocalBinary),
            "ephemeral" => Ok(Self::Ephemeral),
            other => bail!(
                "invalid install mode '{}' (expected auto|off|upload-local-binary|ephemeral)",
                other
            ),
        }
    }
}

#[derive(Debug)]
pub struct BootstrapOptions {
    pub remote: RemoteEndpoint,
    pub destination: String,
    pub server_port: u16,
    pub server_name: String,
    pub client_id: String,
    pub profile_name: String,
    pub install_mode: InstallMode,
    pub preserve_metadata: bool,
    pub preserve_xattrs: bool,
}

pub struct BootstrapSession {
    pub server: SocketAddr,
    pub server_name: String,
    pub ca: PathBuf,
    pub client_cert: PathBuf,
    pub client_key: PathBuf,
    _binary_lease: RemoteBinaryLease,
    child: Option<Child>,
}

pub struct Enrollment {
    pub server: SocketAddr,
    pub server_name: String,
    pub ca: PathBuf,
    pub client_cert: PathBuf,
    pub client_key: PathBuf,
}

pub struct RemoteServerStatus {
    pub running: bool,
    pub pid: Option<u32>,
}

pub struct RemoteBinaryLease {
    remote: RemoteEndpoint,
    shell_prefix: String,
    cleanup_path: Option<String>,
}

impl RemoteBinaryLease {
    pub fn shell_prefix(&self) -> &str {
        &self.shell_prefix
    }
}

impl Drop for RemoteBinaryLease {
    fn drop(&mut self) {
        let Some(path) = self.cleanup_path.take() else {
            return;
        };
        let _ = run_ssh_status(&self.remote, &format!("rm -f {}", sh_quote(&path)));
    }
}

impl BootstrapSession {
    pub fn wait(mut self) -> Result<()> {
        let Some(mut child) = self.child.take() else {
            return Ok(());
        };
        let status = child
            .try_wait()
            .context("poll remote serve-session ssh process")?;
        let Some(status) = status else {
            let _ = child.kill();
            let _ = child.wait();
            return Ok(());
        };
        if !status.success() {
            bail!("remote serve-session exited with status {}", status);
        }
        Ok(())
    }
}

impl Drop for BootstrapSession {
    fn drop(&mut self) {
        let Some(mut child) = self.child.take() else {
            return;
        };
        match child.try_wait() {
            Ok(Some(_)) => {}
            Ok(None) | Err(_) => {
                let _ = child.kill();
                let _ = child.wait();
            }
        }
    }
}

fn sh_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\"'\"'"))
}

fn ssh_base_command(remote: &RemoteEndpoint) -> Command {
    let mut cmd = Command::new("ssh");
    cmd.arg("-o").arg("BatchMode=yes");
    cmd.arg("-o").arg(format!(
        "StrictHostKeyChecking={}",
        ssh_strict_host_key_checking()
    ));
    if let Ok(identity) = std::env::var("SPARSYNC_SSH_IDENTITY") {
        if !identity.trim().is_empty() {
            cmd.arg("-i").arg(identity);
        }
    }
    if let Some(port) = remote.port {
        cmd.arg("-p").arg(port.to_string());
    }
    cmd.arg(remote.ssh_target());
    cmd
}

fn ssh_strict_host_key_checking() -> String {
    if let Ok(value) = std::env::var("SPARSYNC_SSH_STRICT_HOST_KEY_CHECKING") {
        let trimmed = value.trim();
        if !trimmed.is_empty() {
            return trimmed.to_string();
        }
    }
    if std::env::var("SPARSYNC_SSH_TOFU")
        .map(|value| value == "1")
        .unwrap_or(false)
    {
        "accept-new".to_string()
    } else {
        "yes".to_string()
    }
}

fn run_ssh(remote: &RemoteEndpoint, script: &str) -> Result<Vec<u8>> {
    let output = ssh_base_command(remote)
        .arg(script)
        .output()
        .with_context(|| format!("run ssh command on {}", remote.ssh_target()))?;
    if !output.status.success() {
        bail!(
            "ssh command failed on {}: {}",
            remote.ssh_target(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(output.stdout)
}

fn run_ssh_status(remote: &RemoteEndpoint, script: &str) -> Result<bool> {
    let status = ssh_base_command(remote)
        .arg(script)
        .status()
        .with_context(|| format!("run ssh status command on {}", remote.ssh_target()))?;
    Ok(status.success())
}

fn remote_home(remote: &RemoteEndpoint) -> Result<String> {
    let bytes = run_ssh(remote, "printf %s \"$HOME\"").context("resolve remote HOME")?;
    let home = String::from_utf8(bytes).context("decode remote HOME output")?;
    let home = home.trim();
    if home.is_empty() {
        bail!("remote HOME is empty");
    }
    Ok(home.to_string())
}

fn remote_install_path(remote: &RemoteEndpoint) -> Result<String> {
    let home = remote_home(remote)?;
    Ok(format!("{home}/{DEFAULT_REMOTE_INSTALL_SUBPATH}"))
}

fn remote_auth_dir(remote: &RemoteEndpoint) -> Result<String> {
    let home = remote_home(remote)?;
    Ok(format!("{home}/{DEFAULT_REMOTE_AUTH_SUBPATH}"))
}

fn remote_service_dir(remote: &RemoteEndpoint) -> Result<String> {
    let home = remote_home(remote)?;
    Ok(format!("{home}/{DEFAULT_REMOTE_SERVICE_SUBPATH}"))
}

fn resolve_remote_service_shell_prefix(remote: &RemoteEndpoint) -> Result<String> {
    let output = run_ssh(remote, "command -v sparsync 2>/dev/null || true")
        .context("resolve remote sparsync binary for service management")?;
    let discovered = String::from_utf8(output).context("decode remote sparsync path")?;
    let discovered = discovered.trim();
    if !discovered.is_empty() {
        return Ok(sh_quote(discovered));
    }

    let install_path = remote_install_path(remote)?;
    if run_ssh_status(remote, &format!("[ -x {} ]", sh_quote(&install_path)))? {
        return Ok(sh_quote(&install_path));
    }

    bail!(
        "remote sparsync binary is unavailable (expected in PATH or at {})",
        install_path
    );
}

fn mktemp_remote_binary_path(remote: &RemoteEndpoint) -> Result<String> {
    let bytes =
        run_ssh(remote, "mktemp /tmp/sparsync.XXXXXX").context("create remote temp path")?;
    let path = String::from_utf8(bytes).context("decode remote temp path")?;
    let path = path.trim();
    if path.is_empty() {
        bail!("remote mktemp returned empty path");
    }
    Ok(path.to_string())
}

fn upload_file_via_ssh(remote: &RemoteEndpoint, local: &Path, remote_path: &str) -> Result<()> {
    let data =
        std::fs::read(local).with_context(|| format!("read local file {}", local.display()))?;
    let parent = std::path::Path::new(remote_path)
        .parent()
        .map(|value| value.to_string_lossy().into_owned())
        .filter(|value| !value.is_empty())
        .unwrap_or_else(|| ".".to_string());
    run_ssh(remote, &format!("mkdir -p {}", sh_quote(&parent)))
        .with_context(|| format!("ensure remote upload parent {}", parent))?;
    let remote_path_q = sh_quote(remote_path);
    let mut child = ssh_base_command(remote)
        .arg(format!("cat > {remote_path}", remote_path = remote_path_q))
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .with_context(|| format!("spawn ssh upload to {}", remote.ssh_target()))?;

    if let Some(stdin) = child.stdin.as_mut() {
        stdin
            .write_all(&data)
            .with_context(|| format!("stream {} to remote", local.display()))?;
    }
    let output = child
        .wait_with_output()
        .context("wait for ssh upload command")?;
    if !output.status.success() {
        bail!(
            "upload to remote failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    run_ssh_status(remote, &format!("chmod 0755 {}", remote_path_q))
        .with_context(|| format!("mark {} executable on remote", remote_path))?;
    Ok(())
}

fn fetch_file_via_ssh(remote: &RemoteEndpoint, remote_path: &str, local_path: &Path) -> Result<()> {
    let script = format!("cat {}", sh_quote(remote_path));
    let data =
        run_ssh(remote, &script).with_context(|| format!("fetch remote file {}", remote_path))?;
    profile::write_secret_file(local_path, &data)
        .with_context(|| format!("write {}", local_path.display()))?;
    Ok(())
}

fn prepare_remote_binary(
    remote: &RemoteEndpoint,
    install_mode: InstallMode,
) -> Result<RemoteBinaryLease> {
    let has_remote_sparsync = run_ssh_status(remote, "command -v sparsync >/dev/null 2>&1")?;
    match install_mode {
        InstallMode::Off => {
            if !has_remote_sparsync {
                bail!("remote sparsync is missing and install mode is off");
            }
            Ok(RemoteBinaryLease {
                remote: remote.clone(),
                shell_prefix: "sparsync".to_string(),
                cleanup_path: None,
            })
        }
        InstallMode::Auto => {
            if has_remote_sparsync {
                return Ok(RemoteBinaryLease {
                    remote: remote.clone(),
                    shell_prefix: "sparsync".to_string(),
                    cleanup_path: None,
                });
            }
            let local =
                std::env::current_exe().context("resolve local sparsync executable path")?;
            let install_path = remote_install_path(remote)?;
            upload_file_via_ssh(remote, &local, &install_path)
                .context("upload sparsync binary to remote")?;
            if !run_ssh_status(remote, &format!("[ -x {} ]", sh_quote(&install_path)))? {
                bail!("remote sparsync install failed");
            }
            Ok(RemoteBinaryLease {
                remote: remote.clone(),
                shell_prefix: sh_quote(&install_path),
                cleanup_path: None,
            })
        }
        InstallMode::UploadLocalBinary => {
            let local =
                std::env::current_exe().context("resolve local sparsync executable path")?;
            let install_path = remote_install_path(remote)?;
            upload_file_via_ssh(remote, &local, &install_path)
                .context("upload sparsync binary to remote")?;
            if !run_ssh_status(remote, &format!("[ -x {} ]", sh_quote(&install_path)))? {
                bail!("remote sparsync install failed");
            }
            Ok(RemoteBinaryLease {
                remote: remote.clone(),
                shell_prefix: sh_quote(&install_path),
                cleanup_path: None,
            })
        }
        InstallMode::Ephemeral => {
            let local =
                std::env::current_exe().context("resolve local sparsync executable path")?;
            let temp_path = mktemp_remote_binary_path(remote)?;
            upload_file_via_ssh(remote, &local, &temp_path)
                .context("upload ephemeral sparsync binary to remote")?;
            if !run_ssh_status(remote, &format!("[ -x {} ]", sh_quote(&temp_path)))? {
                bail!("ephemeral remote sparsync upload failed");
            }
            Ok(RemoteBinaryLease {
                remote: remote.clone(),
                shell_prefix: sh_quote(&temp_path),
                cleanup_path: Some(temp_path),
            })
        }
    }
}

pub fn ensure_remote_binary_available(
    remote: &RemoteEndpoint,
    install_mode: InstallMode,
) -> Result<RemoteBinaryLease> {
    prepare_remote_binary(remote, install_mode)
}

fn resolve_server_addr(remote: &RemoteEndpoint, port: u16) -> Result<SocketAddr> {
    let addr = format!("{}:{port}", remote.host);
    addr.to_socket_addrs()
        .with_context(|| format!("resolve remote host '{}'", remote.host))?
        .next()
        .ok_or_else(|| anyhow::anyhow!("no socket address resolved for {}", addr))
}

pub fn default_client_id() -> String {
    let user = std::env::var("USER").unwrap_or_else(|_| "client".to_string());
    let host = std::env::var("HOSTNAME").unwrap_or_else(|_| "host".to_string());
    let sanitize = |value: String| -> String {
        value
            .chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                    c
                } else {
                    '-'
                }
            })
            .collect()
    };
    format!("{}-{}", sanitize(user), sanitize(host))
}

fn wait_for_server_ready(server: SocketAddr, timeout: Duration) -> Result<()> {
    TcpStream::connect_timeout(&server, timeout)
        .with_context(|| format!("connect to bootstrap server {}", server))?;
    Ok(())
}

fn enroll_remote_with_lease(
    options: &BootstrapOptions,
    binary_lease: &RemoteBinaryLease,
) -> Result<Enrollment> {
    let remote_auth_dir = remote_auth_dir(&options.remote)?;

    run_ssh(
        &options.remote,
        &format!(
            "{} auth init-server --dir {} --server-name {}",
            binary_lease.shell_prefix(),
            sh_quote(&remote_auth_dir),
            sh_quote(&options.server_name)
        ),
    )
    .context("initialize remote auth material")?;

    run_ssh(
        &options.remote,
        &format!(
            "{} auth issue-client --dir {} --client-id {} --allow-prefix {}",
            binary_lease.shell_prefix(),
            sh_quote(&remote_auth_dir),
            sh_quote(&options.client_id),
            sh_quote(&options.destination)
        ),
    )
    .context("issue remote client certificate")?;

    let local_root = profile::ensure_profile_secret_dir(&options.profile_name)?;

    let ca = local_root.join("server.cert.der");
    let client_cert = local_root.join("client.cert.der");
    let client_key = local_root.join("client.key.der");

    fetch_file_via_ssh(
        &options.remote,
        &format!("{remote_auth_dir}/server.cert.der"),
        &ca,
    )?;
    fetch_file_via_ssh(
        &options.remote,
        &format!("{remote_auth_dir}/clients/{}.cert.der", options.client_id),
        &client_cert,
    )?;
    fetch_file_via_ssh(
        &options.remote,
        &format!("{remote_auth_dir}/clients/{}.key.der", options.client_id),
        &client_key,
    )?;

    let server = resolve_server_addr(&options.remote, options.server_port)?;

    Ok(Enrollment {
        server,
        server_name: options.server_name.clone(),
        ca,
        client_cert,
        client_key,
    })
}

pub fn enroll_remote(options: &BootstrapOptions) -> Result<Enrollment> {
    let binary_lease = prepare_remote_binary(&options.remote, options.install_mode)?;
    enroll_remote_with_lease(options, &binary_lease)
}

pub fn bootstrap_remote_push(options: &BootstrapOptions) -> Result<BootstrapSession> {
    let binary_lease = prepare_remote_binary(&options.remote, options.install_mode)?;
    let enrollment = enroll_remote_with_lease(options, &binary_lease)?;
    let remote_auth_dir = remote_auth_dir(&options.remote)?;

    let mut remote_cmd = format!(
        "{} serve --bind 0.0.0.0:{} --destination {} --cert {} --key {} --client-ca {} --authz {} --once",
        binary_lease.shell_prefix(),
        options.server_port,
        sh_quote(&options.destination),
        sh_quote(&format!("{remote_auth_dir}/server.cert.der")),
        sh_quote(&format!("{remote_auth_dir}/server.key.der")),
        sh_quote(&format!("{remote_auth_dir}/client-ca.cert.der")),
        sh_quote(&format!("{remote_auth_dir}/authz.json"))
    );
    if options.preserve_metadata {
        remote_cmd.push_str(" --preserve-metadata");
    }
    if options.preserve_xattrs {
        remote_cmd.push_str(" --preserve-xattrs");
    }

    let child = ssh_base_command(&options.remote)
        .arg(remote_cmd)
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .spawn()
        .with_context(|| {
            format!(
                "spawn remote serve-session on {}",
                options.remote.ssh_target()
            )
        })?;

    wait_for_server_ready(enrollment.server, Duration::from_secs(10))
        .context("wait for remote one-shot server readiness")?;

    Ok(BootstrapSession {
        server: enrollment.server,
        server_name: enrollment.server_name,
        ca: enrollment.ca,
        client_cert: enrollment.client_cert,
        client_key: enrollment.client_key,
        _binary_lease: binary_lease,
        child: Some(child),
    })
}

pub fn start_remote_server(options: &BootstrapOptions) -> Result<Enrollment> {
    if matches!(options.install_mode, InstallMode::Ephemeral) {
        bail!("install mode 'ephemeral' is not supported for persistent remote server start");
    }
    let binary_lease = prepare_remote_binary(&options.remote, options.install_mode)?;
    let enrollment = enroll_remote_with_lease(options, &binary_lease)?;
    let remote_auth_dir = remote_auth_dir(&options.remote)?;
    let service_dir = remote_service_dir(&options.remote)?;
    let pid_file = format!("{service_dir}/server.pid");
    let log_file = format!("{service_dir}/server.log");

    let mut remote_cmd = format!(
        "{} service-daemon start --bind 0.0.0.0:{} --destination {} --cert {} --key {} --client-ca {} --authz {} --pid-file {} --log-file {}",
        binary_lease.shell_prefix(),
        options.server_port,
        sh_quote(&options.destination),
        sh_quote(&format!("{remote_auth_dir}/server.cert.der")),
        sh_quote(&format!("{remote_auth_dir}/server.key.der")),
        sh_quote(&format!("{remote_auth_dir}/client-ca.cert.der")),
        sh_quote(&format!("{remote_auth_dir}/authz.json")),
        sh_quote(&pid_file),
        sh_quote(&log_file),
    );
    if options.preserve_metadata {
        remote_cmd.push_str(" --preserve-metadata");
    }
    if options.preserve_xattrs {
        remote_cmd.push_str(" --preserve-xattrs");
    }
    run_ssh(&options.remote, &remote_cmd).context("start remote sparsync server")?;
    wait_for_server_ready(enrollment.server, Duration::from_secs(10))
        .context("wait for remote persistent server readiness")?;
    Ok(enrollment)
}

pub fn stop_remote_server(remote: &RemoteEndpoint) -> Result<bool> {
    let service_dir = remote_service_dir(remote)?;
    let pid_file = format!("{service_dir}/server.pid");
    let shell_prefix = resolve_remote_service_shell_prefix(remote)?;
    let command = format!(
        "{shell_prefix} service-daemon stop --pid-file {}",
        sh_quote(&pid_file)
    );
    let output = run_ssh(remote, &command).context("stop remote sparsync server")?;
    let text = String::from_utf8(output).context("decode remote stop output")?;
    Ok(text.trim() == "stopped_running")
}

pub fn remote_server_status(remote: &RemoteEndpoint) -> Result<RemoteServerStatus> {
    let service_dir = remote_service_dir(remote)?;
    let pid_file = format!("{service_dir}/server.pid");
    let shell_prefix = resolve_remote_service_shell_prefix(remote)?;
    let command = format!(
        "{shell_prefix} service-daemon status --pid-file {}",
        sh_quote(&pid_file)
    );
    let output = run_ssh(remote, &command).context("query remote sparsync server status")?;
    let text = String::from_utf8(output).context("decode remote status output")?;
    let trimmed = text.trim();
    if let Some(pid) = trimmed.strip_prefix("running ") {
        let pid = pid
            .trim()
            .parse::<u32>()
            .with_context(|| format!("parse remote running pid '{}'", pid.trim()))?;
        return Ok(RemoteServerStatus {
            running: true,
            pid: Some(pid),
        });
    }
    Ok(RemoteServerStatus {
        running: false,
        pid: None,
    })
}

#[cfg(test)]
mod tests {
    use super::{BootstrapSession, RemoteBinaryLease};
    use crate::endpoint::{RemoteEndpoint, RemoteKind};
    use std::path::PathBuf;
    use std::process::Command;

    #[test]
    fn bootstrap_session_drop_terminates_child_process() {
        let child = Command::new("sleep")
            .arg("30")
            .spawn()
            .expect("spawn sleep child");
        let pid = child.id();

        let session = BootstrapSession {
            server: "127.0.0.1:1".parse().expect("parse socket addr"),
            server_name: "test".to_string(),
            ca: PathBuf::new(),
            client_cert: PathBuf::new(),
            client_key: PathBuf::new(),
            _binary_lease: RemoteBinaryLease {
                remote: RemoteEndpoint {
                    user: None,
                    host: "localhost".to_string(),
                    port: None,
                    path: "/tmp".to_string(),
                    kind: RemoteKind::Ssh,
                },
                shell_prefix: "sparsync".to_string(),
                cleanup_path: None,
            },
            child: Some(child),
        };

        drop(session);

        let status = Command::new("sh")
            .arg("-c")
            .arg(format!("kill -0 {pid} >/dev/null 2>&1"))
            .status()
            .expect("check process liveness");
        assert!(!status.success(), "child process {pid} is still running");
    }
}