Skip to main content

agentmux_remote/
serve.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `agentmux-remote serve --stdio`: file operations for srv over this
5//! process's stdin and stdout (`fsproto`), one request at a time, until
6//! stdin closes (spec §6.1, §6.3). Paths are the host's own; `~` and a
7//! relative path are under the user's home. Nothing here opens a socket or
8//! reaches beyond what this user can already read and write.
9
10use std::fs;
11use std::io::{self, Read, Write};
12use std::path::{Path, PathBuf};
13use std::sync::atomic::{AtomicU64, Ordering};
14use std::time::UNIX_EPOCH;
15
16use crate::fsproto::{self, Entry, ErrKind, Kind, Reply, Request, Splitter, MAX_READ, MAX_WRITE};
17use crate::rename::rename_no_replace;
18
19/// Serve requests from `input`, answering on `output`, until `input` ends.
20/// `home` is the user's home directory ([`home_dir`]).
21pub fn run(home: &Path, input: &mut impl Read, output: &mut impl Write) -> io::Result<()> {
22    run_with(Server::new(home.to_path_buf()), input, output)
23}
24
25/// [`run`] with a [`Server`] made by the caller (one that can ask the
26/// session daemon for a session's shell: [`Server::with_sessions`]).
27pub fn run_with(mut server: Server, input: &mut impl Read, output: &mut impl Write) -> io::Result<()> {
28    let mut splitter = Splitter::new();
29    let mut buf = vec![0u8; 64 * 1024];
30    loop {
31        let n = input.read(&mut buf)?;
32        if n == 0 {
33            return Ok(());
34        }
35        let bodies = splitter
36            .push(&buf[..n])
37            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
38        for body in bodies {
39            let reply = match Request::decode(&body) {
40                Ok((id, req)) => (id, server.handle(req)),
41                // A request that cannot be read: the stream is broken.
42                Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidData, e)),
43            };
44            output.write_all(&reply.1.encode(reply.0))?;
45            output.flush()?;
46        }
47    }
48}
49
50/// A durable session's shell PID, by session id (the daemon's).
51pub type SessionPid = Box<dyn Fn(&str) -> Option<u32> + Send>;
52
53/// One connection's server: [`handle`], plus what lasts between requests
54/// (Tower's CPU rates, `procs`).
55pub struct Server {
56    home: PathBuf,
57    procs: crate::procs::Sampler,
58    session_pid: Option<SessionPid>,
59}
60
61impl Server {
62    pub fn new(home: PathBuf) -> Self {
63        Self { home, procs: crate::procs::Sampler::new(), session_pid: None }
64    }
65
66    /// A server that finds a durable session's shell through `session_pid`
67    /// (`PaneProcs` with a session).
68    pub fn with_sessions(home: PathBuf, session_pid: SessionPid) -> Self {
69        Self { session_pid: Some(session_pid), ..Self::new(home) }
70    }
71
72    pub fn handle(&mut self, req: Request) -> Reply {
73        match req {
74            Request::Procs { top, filter } => Reply::Procs(self.procs.frame(top, &filter)),
75            Request::PaneProcs { block_id, session } => {
76                let pid = (!session.is_empty()).then(|| self.session_pid.as_ref().and_then(|f| f(&session))).flatten();
77                Reply::PaneProcs(self.procs.pane(&block_id, pid))
78            }
79            req => handle(&self.home, req),
80        }
81    }
82}
83
84pub fn home_dir() -> PathBuf {
85    let var = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
86    std::env::var_os(var)
87        .filter(|h| !h.is_empty())
88        .map(PathBuf::from)
89        .unwrap_or_else(|| PathBuf::from("/"))
90}
91
92/// A request's path on this host: `~` and `~/…` under the home directory,
93/// a relative path too, an absolute one as given.
94pub fn resolve(home: &Path, path: &str) -> PathBuf {
95    let p = if path == "~" {
96        home.to_path_buf()
97    } else if let Some(rest) = path.strip_prefix("~/") {
98        home.join(rest)
99    } else if Path::new(path).is_absolute() {
100        PathBuf::from(path)
101    } else {
102        home.join(path)
103    };
104    // Rebuilt from its parts: no trailing separator, which would make the OS
105    // follow a final symlink (`~/link/` is the link's target, not the link)
106    // and act on something other than what was named.
107    p.components().collect()
108}
109
110fn err(e: io::Error) -> Reply {
111    Reply::Err {
112        kind: ErrKind::from_io(&e),
113        message: e.to_string(),
114    }
115}
116
117fn invalid(message: &str) -> Reply {
118    Reply::Err {
119        kind: ErrKind::Invalid,
120        message: message.to_string(),
121    }
122}
123
124/// The reply to one request; `home` is the user's home directory. A `Procs`
125/// here has no previous round, so its frame has no CPU rates: the serve loop
126/// answers it through [`Server`] instead.
127pub fn handle(home: &Path, req: Request) -> Reply {
128    let result = match req {
129        Request::Procs { top, filter } => Ok(Reply::Procs(crate::procs::Sampler::new().frame(top, &filter))),
130        Request::PaneProcs { block_id, .. } => Ok(Reply::PaneProcs(crate::procs::Sampler::new().pane(&block_id, None))),
131        Request::Hello => Ok(Reply::Hello {
132            protocol: fsproto::PROTOCOL,
133            home: home.to_string_lossy().into_owned(),
134            os: std::env::consts::OS.to_string(),
135        }),
136        Request::Stat { path } => {
137            let p = resolve(home, &path);
138            entry_of(&p).map(Reply::Stat)
139        }
140        Request::List {
141            path,
142            offset,
143            limit,
144        } => list(&resolve(home, &path), offset, limit),
145        Request::Read { path, offset, len } => read(&resolve(home, &path), offset, len),
146        Request::Write { path, data } => {
147            if data.len() > MAX_WRITE {
148                return Reply::Err {
149                    kind: ErrKind::TooLarge,
150                    message: format!("over the {} MB a write may be", MAX_WRITE >> 20),
151                };
152            }
153            write_atomic(&resolve(home, &path), &data).map(|()| Reply::Done)
154        }
155        Request::Append { path, data } => {
156            if data.len() > MAX_WRITE {
157                return Reply::Err {
158                    kind: ErrKind::TooLarge,
159                    message: format!("over the {} MB a write may be", MAX_WRITE >> 20),
160                };
161            }
162            let p = resolve(home, &path);
163            // Only a file already there: never makes one, never follows a
164            // link somewhere else.
165            match fs::symlink_metadata(&p) {
166                Ok(m) if m.is_file() => fs::OpenOptions::new()
167                    .append(true)
168                    .open(&p)
169                    .and_then(|mut f| f.write_all(&data))
170                    .map(|()| Reply::Done),
171                Ok(_) => return invalid("only a regular file can be appended to"),
172                Err(e) => Err(e),
173            }
174        }
175        Request::Mkdir { path, parents } => {
176            let p = resolve(home, &path);
177            if parents {
178                fs::create_dir_all(&p)
179            } else {
180                fs::create_dir(&p)
181            }
182            .map(|()| Reply::Done)
183        }
184        Request::Rename { from, to } => {
185            let (from, to) = (resolve(home, &from), resolve(home, &to));
186            if let Err(e) = fs::symlink_metadata(&from) {
187                return err(e);
188            }
189            return match rename(&from, &to) {
190                Ok(()) => Reply::Done,
191                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Reply::Err {
192                    kind: ErrKind::AlreadyExists,
193                    message: format!("{} already exists", to.display()),
194                },
195                Err(e) => err(e),
196            };
197        }
198        Request::Replace { from, to } => {
199            let (from, to) = (resolve(home, &from), resolve(home, &to));
200            // Files only: `rename` over a file is atomic, and a folder is
201            // never replaced this way.
202            for p in [&from, &to] {
203                match fs::symlink_metadata(p) {
204                    Ok(m) if m.is_dir() => return invalid("only a file is replaced in one step"),
205                    Ok(_) => {}
206                    Err(e) => return err(e),
207                }
208            }
209            fs::rename(&from, &to).map(|()| Reply::Done)
210        }
211        Request::Sync { path } => {
212            let p = resolve(home, &path);
213            match fs::symlink_metadata(&p) {
214                Ok(m) if m.is_file() => fs::OpenOptions::new()
215                    // Read-only on Unix (fsync needs no write access, and a read-only file
216                    // must sync too); Windows flushes only a handle it can write.
217                    .read(cfg!(unix))
218                    .write(!cfg!(unix))
219                    .open(&p)
220                    .and_then(|f| f.sync_all())
221                    .map(|()| Reply::Done),
222                Ok(_) => return invalid("only a file is synced"),
223                Err(e) => Err(e),
224            }
225        }
226        Request::Realpath { path } => fs::canonicalize(resolve(home, &path))
227            .map(|p| Reply::Path(p.to_string_lossy().into_owned())),
228        Request::SetMeta {
229            path,
230            mode,
231            mtime_ms,
232        } => {
233            let p = resolve(home, &path);
234            match fs::symlink_metadata(&p) {
235                Ok(m) if m.is_file() => set_meta(&p, mode, mtime_ms).map(|()| Reply::Done),
236                Ok(_) => return invalid("only a file's metadata is set"),
237                Err(e) => Err(e),
238            }
239        }
240        Request::Delete { path, recursive } => {
241            let p = resolve(home, &path);
242            // `..` is never needed to name a thing to delete, and it is how a
243            // path that looks like it is under home reaches home or above.
244            if p.components().any(|c| c == std::path::Component::ParentDir) {
245                return invalid("refusing to delete a path with '..' in it");
246            }
247            // What it really is, its parents' links resolved (the thing
248            // itself is not followed: a link is removed, never its target).
249            let real = match (p.parent(), p.file_name()) {
250                (Some(parent), Some(name)) => match fs::canonicalize(parent) {
251                    Ok(dir) => dir.join(name),
252                    Err(e) => return err(e),
253                },
254                _ => return invalid("refusing to delete the root"),
255            };
256            let real_home = fs::canonicalize(home).unwrap_or_else(|_| home.to_path_buf());
257            if real.parent().is_none() || real == real_home || real_home.starts_with(&real) {
258                return invalid(
259                    "refusing to delete the root, the home directory or a folder holding it",
260                );
261            }
262            // Everything from here on uses `real`, the path the guard checked:
263            // never `p`, whose trailing slash (`~/link/`) would make the OS
264            // follow a link the guard saw as a link.
265            match fs::symlink_metadata(&real) {
266                // A link is removed, never followed (a directory link is a
267                // directory entry on Windows).
268                Ok(m) if m.file_type().is_symlink() => {
269                    fs::remove_file(&real).or_else(|_| fs::remove_dir(&real))
270                }
271                Ok(m) if m.is_dir() => {
272                    if recursive {
273                        fs::remove_dir_all(&real)
274                    } else {
275                        fs::remove_dir(&real)
276                    }
277                }
278                Ok(_) => fs::remove_file(&real),
279                Err(e) => Err(e),
280            }
281            .map(|()| Reply::Done)
282        }
283    };
284    result.unwrap_or_else(err)
285}
286
287/// `Rename`: never over something already there. The rename itself refuses a
288/// taken name (`rename_no_replace`), in the one step that would take it: with
289/// a check first and a rename after, a file made in between was replaced.
290///
291/// The same file under another spelling (a case-only rename on a
292/// case-insensitive disk) is not something else at the new name. It goes by
293/// way of a name nothing has, each step refusing a taken name, and comes back
294/// if the new name turns out to be taken after all (a second hard link to the
295/// file, on a disk that tells the two spellings apart).
296fn rename(from: &Path, to: &Path) -> io::Result<()> {
297    static N: AtomicU64 = AtomicU64::new(0);
298    if from == to {
299        return Ok(());
300    }
301    if !same_file(from, to) {
302        return rename_no_replace(from, to);
303    }
304    let between = to.with_file_name(format!(
305        ".amx-rename-{}-{}.tmp",
306        std::process::id(),
307        N.fetch_add(1, Ordering::Relaxed)
308    ));
309    rename_no_replace(from, &between)?;
310    rename_no_replace(&between, to).inspect_err(|_| {
311        let _ = rename_no_replace(&between, from);
312    })
313}
314
315/// A file's permission bits (`mode`, when not 0, on Unix) and modification
316/// time (`mtime_ms`, when not 0).
317fn set_meta(p: &Path, mode: u32, mtime_ms: i64) -> io::Result<()> {
318    if mtime_ms > 0 {
319        let t = UNIX_EPOCH + std::time::Duration::from_millis(mtime_ms as u64);
320        fs::OpenOptions::new()
321            .write(true)
322            .open(p)?
323            .set_modified(t)?;
324    }
325    #[cfg(unix)]
326    if mode != 0 {
327        use std::os::unix::fs::PermissionsExt;
328        fs::set_permissions(p, fs::Permissions::from_mode(mode & 0o7777))?;
329    }
330    #[cfg(not(unix))]
331    let _ = mode;
332    Ok(())
333}
334
335fn entry_of(p: &Path) -> io::Result<Entry> {
336    let link = fs::symlink_metadata(p)?;
337    let symlink = link.file_type().is_symlink();
338    // A symlink is what it points to; a dangling one is shown as itself.
339    let meta = if symlink {
340        fs::metadata(p).unwrap_or(link)
341    } else {
342        link
343    };
344    let kind = if meta.is_dir() {
345        Kind::Dir
346    } else if meta.is_file() {
347        Kind::File
348    } else {
349        Kind::Other
350    };
351    let mtime_ms = meta
352        .modified()
353        .ok()
354        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
355        .map(|d| d.as_millis() as i64)
356        .unwrap_or(0);
357    #[cfg(unix)]
358    let mode = {
359        use std::os::unix::fs::PermissionsExt;
360        // The permission bits only, not the file type in st_mode.
361        meta.permissions().mode() & 0o7777
362    };
363    #[cfg(not(unix))]
364    let mode = 0;
365    let link_target = if symlink {
366        fs::read_link(p)
367            .map(|t| t.to_string_lossy().into_owned())
368            .unwrap_or_default()
369    } else {
370        String::new()
371    };
372    Ok(Entry {
373        link_target,
374        name: p
375            .file_name()
376            .map(|n| n.to_string_lossy().into_owned())
377            .unwrap_or_else(|| p.to_string_lossy().into_owned()),
378        kind,
379        size: meta.len(),
380        mtime_ms,
381        mode,
382        symlink,
383    })
384}
385
386/// Whether `a` and `b` are one file (both exist): the same inode on Unix,
387/// the same final path on Windows, which gives each file one spelling.
388fn same_file(a: &Path, b: &Path) -> bool {
389    #[cfg(unix)]
390    {
391        use std::os::unix::fs::MetadataExt;
392        match (fs::symlink_metadata(a), fs::symlink_metadata(b)) {
393            (Ok(x), Ok(y)) => x.dev() == y.dev() && x.ino() == y.ino(),
394            _ => false,
395        }
396    }
397    #[cfg(not(unix))]
398    {
399        match (fs::canonicalize(a), fs::canonicalize(b)) {
400            (Ok(x), Ok(y)) => x == y,
401            _ => false,
402        }
403    }
404}
405
406fn list(dir: &Path, offset: u32, limit: u32) -> io::Result<Reply> {
407    let mut names: Vec<std::ffi::OsString> = fs::read_dir(dir)?
408        .filter_map(|e| e.ok().map(|e| e.file_name()))
409        .collect();
410    names.sort();
411    let total = names.len() as u32;
412    let entries = names
413        .into_iter()
414        .skip(offset as usize)
415        .take(limit.min(5000) as usize)
416        // An entry that vanished between the listing and its stat is left out.
417        .filter_map(|n| entry_of(&dir.join(n)).ok())
418        .collect();
419    Ok(Reply::List { entries, total })
420}
421
422fn read(p: &Path, offset: u64, len: u32) -> io::Result<Reply> {
423    use std::io::{Seek, SeekFrom};
424    // Never stuck opening a pipe: whatever this opened must be a regular
425    // file. A link is read through, as the editor opens a linked dotfile
426    // (a transfer skips links before it reads).
427    #[cfg(unix)]
428    let mut f = {
429        use std::os::unix::fs::OpenOptionsExt;
430        fs::OpenOptions::new()
431            .read(true)
432            .custom_flags(libc::O_NONBLOCK)
433            .open(p)?
434    };
435    #[cfg(not(unix))]
436    let mut f = fs::File::open(p)?;
437    let opened = f.metadata()?;
438    if !opened.is_dir() && !opened.is_file() {
439        return Ok(Reply::Err {
440            kind: ErrKind::Invalid,
441            message: format!("{} isn't a regular file", p.display()),
442        });
443    }
444    if opened.is_dir() {
445        return Ok(Reply::Err {
446            kind: ErrKind::IsADirectory,
447            message: format!("{} is a directory", p.display()),
448        });
449    }
450    f.seek(SeekFrom::Start(offset))?;
451    let want = len.min(MAX_READ) as usize;
452    let mut data = Vec::with_capacity(want);
453    Read::by_ref(&mut f)
454        .take(want as u64)
455        .read_to_end(&mut data)?;
456    // At the end if this range reached it.
457    let eof = data.len() < want || f.read(&mut [0u8; 1])? == 0;
458    Ok(Reply::Read { data, eof })
459}
460
461/// Replace `p` with `data`: write a temp file beside it, sync it, give it the
462/// old file's permissions, and rename it over. A reader never sees half a
463/// file, and a failure leaves the old one as it was. A symlink is written
464/// through to its target, so the link stays a link.
465fn write_atomic(p: &Path, data: &[u8]) -> io::Result<()> {
466    static N: AtomicU64 = AtomicU64::new(0);
467    let target = match fs::symlink_metadata(p) {
468        Ok(m) if m.file_type().is_symlink() => fs::canonicalize(p)?,
469        _ => p.to_path_buf(),
470    };
471    let dir = target
472        .parent()
473        .filter(|d| !d.as_os_str().is_empty())
474        .unwrap_or(Path::new("."));
475    let name = target
476        .file_name()
477        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "not a file path"))?;
478    let tmp = dir.join(format!(
479        ".{}.amx-{}-{}.tmp",
480        name.to_string_lossy(),
481        std::process::id(),
482        N.fetch_add(1, Ordering::Relaxed)
483    ));
484    let old = fs::metadata(&target).ok();
485    if old.as_ref().is_some_and(|m| m.is_dir()) {
486        return Err(io::Error::new(
487            io::ErrorKind::InvalidInput,
488            format!("{} is a directory", target.display()),
489        ));
490    }
491    let result = (|| {
492        let mut f = fs::OpenOptions::new()
493            .write(true)
494            .create_new(true)
495            .open(&tmp)?;
496        f.write_all(data)?;
497        f.sync_all()?;
498        if let Some(m) = &old {
499            fs::set_permissions(&tmp, m.permissions())?;
500        }
501        fs::rename(&tmp, &target)
502    })();
503    if result.is_err() {
504        let _ = fs::remove_file(&tmp);
505    }
506    result
507}
508
509#[cfg(test)]
510mod tests {
511    use super::*;
512
513    /// Run requests through `run` as srv would, and return the replies.
514    fn exchange(home: &Path, requests: &[Request]) -> Vec<Reply> {
515        let mut input = Vec::new();
516        for (i, r) in requests.iter().enumerate() {
517            input.extend(r.encode(i as u32));
518        }
519        let mut output = Vec::new();
520        run(home, &mut input.as_slice(), &mut output).unwrap();
521        let mut s = Splitter::new();
522        s.push(&output)
523            .unwrap()
524            .iter()
525            .enumerate()
526            .map(|(i, b)| {
527                let (id, reply) = Reply::decode(b).unwrap();
528                assert_eq!(id, i as u32, "replies in order, each with its id");
529                reply
530            })
531            .collect()
532    }
533
534    #[test]
535    fn files_are_listed_read_written_renamed_and_deleted() {
536        let home = tempfile::tempdir().unwrap();
537        let h = home.path();
538        let replies = exchange(
539            h,
540            &[
541                Request::Hello,
542                Request::Mkdir {
543                    path: "~/d/e".into(),
544                    parents: true,
545                },
546                Request::Write {
547                    path: "d/a.txt".into(),
548                    data: b"hello world".to_vec(),
549                },
550                Request::Read {
551                    path: "~/d/a.txt".into(),
552                    offset: 6,
553                    len: 100,
554                },
555                Request::Read {
556                    path: "~/d/a.txt".into(),
557                    offset: 0,
558                    len: 5,
559                },
560                Request::List {
561                    path: "~/d".into(),
562                    offset: 0,
563                    limit: 10,
564                },
565                Request::List {
566                    path: "~/d".into(),
567                    offset: 1,
568                    limit: 10,
569                },
570                Request::Rename {
571                    from: "~/d/a.txt".into(),
572                    to: "~/d/b.txt".into(),
573                },
574                Request::Stat {
575                    path: "~/d/a.txt".into(),
576                },
577                Request::Delete {
578                    path: "~/d".into(),
579                    recursive: false,
580                },
581                Request::Delete {
582                    path: "~/d".into(),
583                    recursive: true,
584                },
585                Request::Stat { path: "~/d".into() },
586            ],
587        );
588        match &replies[0] {
589            Reply::Hello {
590                protocol, home: hh, ..
591            } => {
592                assert_eq!(*protocol, fsproto::PROTOCOL);
593                assert_eq!(Path::new(hh), h);
594            }
595            r => panic!("{r:?}"),
596        }
597        assert_eq!(replies[1], Reply::Done);
598        assert_eq!(replies[2], Reply::Done);
599        assert_eq!(
600            replies[3],
601            Reply::Read {
602                data: b"world".to_vec(),
603                eof: true
604            }
605        );
606        assert_eq!(
607            replies[4],
608            Reply::Read {
609                data: b"hello".to_vec(),
610                eof: false
611            }
612        );
613        match &replies[5] {
614            Reply::List { entries, total } => {
615                assert_eq!(*total, 2);
616                let got: Vec<(&str, Kind, u64)> = entries
617                    .iter()
618                    .map(|e| (e.name.as_str(), e.kind, e.size))
619                    .collect();
620                assert_eq!(
621                    got,
622                    vec![("a.txt", Kind::File, 11), ("e", Kind::Dir, got[1].2)]
623                );
624                assert!(entries[0].mtime_ms > 0);
625            }
626            r => panic!("{r:?}"),
627        }
628        match &replies[6] {
629            Reply::List { entries, total } => {
630                assert_eq!(
631                    (*total, entries.len(), entries[0].name.as_str()),
632                    (2, 1, "e")
633                )
634            }
635            r => panic!("{r:?}"),
636        }
637        assert_eq!(replies[7], Reply::Done);
638        assert!(matches!(
639            replies[8],
640            Reply::Err {
641                kind: ErrKind::NotFound,
642                ..
643            }
644        ));
645        // Not empty, and not recursive: refused, kept.
646        assert!(matches!(replies[9], Reply::Err { .. }), "{:?}", replies[9]);
647        assert_eq!(replies[10], Reply::Done);
648        assert!(matches!(
649            replies[11],
650            Reply::Err {
651                kind: ErrKind::NotFound,
652                ..
653            }
654        ));
655    }
656
657    #[test]
658    fn a_write_replaces_whole_keeps_the_mode_and_follows_a_link() {
659        let home = tempfile::tempdir().unwrap();
660        let h = home.path();
661        let f = h.join("f.sh");
662        fs::write(&f, b"old").unwrap();
663        #[cfg(unix)]
664        {
665            use std::os::unix::fs::PermissionsExt;
666            fs::set_permissions(&f, fs::Permissions::from_mode(0o750)).unwrap();
667            std::os::unix::fs::symlink(&f, h.join("link")).unwrap();
668        }
669        let replies = exchange(
670            h,
671            &[
672                Request::Write {
673                    path: "~/f.sh".into(),
674                    data: b"new".to_vec(),
675                },
676                #[cfg(unix)]
677                Request::Write {
678                    path: "~/link".into(),
679                    data: b"via link".to_vec(),
680                },
681            ],
682        );
683        assert!(replies.iter().all(|r| *r == Reply::Done), "{replies:?}");
684        #[cfg(unix)]
685        {
686            use std::os::unix::fs::PermissionsExt;
687            assert_eq!(fs::read(&f).unwrap(), b"via link");
688            assert_eq!(
689                fs::metadata(&f).unwrap().permissions().mode() & 0o777,
690                0o750
691            );
692            assert!(fs::symlink_metadata(h.join("link"))
693                .unwrap()
694                .file_type()
695                .is_symlink());
696        }
697        #[cfg(not(unix))]
698        assert_eq!(fs::read(&f).unwrap(), b"new");
699        // No temp file left behind.
700        let left: Vec<_> = fs::read_dir(h)
701            .unwrap()
702            .filter_map(|e| e.ok())
703            .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
704            .collect();
705        assert!(left.is_empty());
706    }
707
708    #[test]
709    fn a_case_only_rename_is_not_refused_as_a_clash() {
710        let home = tempfile::tempdir().unwrap();
711        let h = home.path();
712        fs::write(h.join("a.txt"), b"a").unwrap();
713        let case_insensitive = h.join("A.TXT").exists();
714        let r = exchange(
715            h,
716            &[Request::Rename {
717                from: "a.txt".into(),
718                to: "A.txt".into(),
719            }],
720        );
721        assert_eq!(
722            r[0],
723            Reply::Done,
724            "case-insensitive disk: {case_insensitive}"
725        );
726        let names: Vec<String> = fs::read_dir(h)
727            .unwrap()
728            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
729            .collect();
730        assert_eq!(names, vec!["A.txt"]);
731    }
732
733    #[test]
734    fn a_path_never_ends_in_a_separator() {
735        let h = Path::new("/home/u");
736        assert_eq!(resolve(h, "~/link/"), Path::new("/home/u/link"));
737        assert_eq!(resolve(h, "/srv/data//"), Path::new("/srv/data"));
738        assert_eq!(resolve(h, "rel/"), Path::new("/home/u/rel"));
739        assert_eq!(resolve(h, "~"), h);
740    }
741
742    #[test]
743    fn append_adds_to_an_existing_file_only() {
744        let home = tempfile::tempdir().unwrap();
745        let h = home.path();
746        let r = exchange(
747            h,
748            &[
749                Request::Write {
750                    path: "~/up".into(),
751                    data: b"ab".to_vec(),
752                },
753                Request::Append {
754                    path: "~/up".into(),
755                    data: b"cd".to_vec(),
756                },
757                Request::Append {
758                    path: "~/missing".into(),
759                    data: b"x".to_vec(),
760                },
761                Request::Append {
762                    path: "~".into(),
763                    data: b"x".to_vec(),
764                },
765            ],
766        );
767        assert_eq!((&r[0], &r[1]), (&Reply::Done, &Reply::Done));
768        assert!(
769            matches!(
770                r[2],
771                Reply::Err {
772                    kind: ErrKind::NotFound,
773                    ..
774                }
775            ),
776            "{:?}",
777            r[2]
778        );
779        assert!(
780            matches!(
781                r[3],
782                Reply::Err {
783                    kind: ErrKind::Invalid,
784                    ..
785                }
786            ),
787            "{:?}",
788            r[3]
789        );
790        assert_eq!(fs::read(h.join("up")).unwrap(), b"abcd");
791        assert!(!h.join("missing").exists());
792    }
793
794    #[test]
795    fn replace_realpath_and_set_meta() {
796        let home = tempfile::tempdir().unwrap();
797        let h = home.path();
798        fs::write(h.join("new"), b"new").unwrap();
799        fs::write(h.join("old"), b"old").unwrap();
800        fs::create_dir(h.join("d")).unwrap();
801        let r = exchange(
802            h,
803            &[
804                Request::Replace {
805                    from: "~/new".into(),
806                    to: "~/old".into(),
807                },
808                Request::Replace {
809                    from: "~/old".into(),
810                    to: "~/d".into(),
811                },
812                Request::Realpath {
813                    path: "~/d/../old".into(),
814                },
815                Request::SetMeta {
816                    path: "~/old".into(),
817                    mode: 0o751,
818                    mtime_ms: 1_600_000_000_000,
819                },
820                Request::SetMeta {
821                    path: "~/d".into(),
822                    mode: 0o700,
823                    mtime_ms: 0,
824                },
825            ],
826        );
827        assert_eq!(r[0], Reply::Done);
828        assert_eq!(fs::read(h.join("old")).unwrap(), b"new");
829        assert!(!h.join("new").exists());
830        assert!(
831            matches!(
832                r[1],
833                Reply::Err {
834                    kind: ErrKind::Invalid,
835                    ..
836                }
837            ),
838            "{:?}",
839            r[1]
840        );
841        match &r[2] {
842            Reply::Path(p) => assert_eq!(Path::new(p), fs::canonicalize(h.join("old")).unwrap()),
843            other => panic!("{other:?}"),
844        }
845        assert_eq!(r[3], Reply::Done);
846        let e = entry_of(&h.join("old")).unwrap();
847        assert_eq!(e.mtime_ms, 1_600_000_000_000);
848        #[cfg(unix)]
849        assert_eq!(e.mode, 0o751);
850        assert!(matches!(
851            r[4],
852            Reply::Err {
853                kind: ErrKind::Invalid,
854                ..
855            }
856        ));
857    }
858
859    /// A pipe is refused at once (never a read that waits for a writer); a
860    /// link is read through.
861    #[cfg(unix)]
862    #[test]
863    fn a_read_takes_only_a_regular_file() {
864        let home = tempfile::tempdir().unwrap();
865        let h = home.path();
866        assert!(std::process::Command::new("mkfifo")
867            .arg(h.join("pipe"))
868            .status()
869            .unwrap()
870            .success());
871        fs::write(h.join("real"), b"r").unwrap();
872        std::os::unix::fs::symlink(h.join("real"), h.join("link")).unwrap();
873        let r = exchange(
874            h,
875            &[
876                Request::Read {
877                    path: "~/pipe".into(),
878                    offset: 0,
879                    len: 10,
880                },
881                Request::Read {
882                    path: "~/link".into(),
883                    offset: 0,
884                    len: 10,
885                },
886                Request::Sync {
887                    path: "~/real".into(),
888                },
889            ],
890        );
891        assert!(
892            matches!(
893                r[0],
894                Reply::Err {
895                    kind: ErrKind::Invalid,
896                    ..
897                }
898            ),
899            "{:?}",
900            r[0]
901        );
902        assert_eq!(
903            r[1],
904            Reply::Read {
905                data: b"r".to_vec(),
906                eof: true
907            },
908            "a link is read through"
909        );
910        assert_eq!(r[2], Reply::Done);
911        // A read-only file syncs too.
912        use std::os::unix::fs::PermissionsExt;
913        fs::set_permissions(h.join("real"), fs::Permissions::from_mode(0o444)).unwrap();
914        let r = exchange(
915            h,
916            &[Request::Sync {
917                path: "~/real".into(),
918            }],
919        );
920        assert_eq!(r[0], Reply::Done);
921    }
922
923    #[test]
924    fn modes_are_permission_bits_only() {
925        let home = tempfile::tempdir().unwrap();
926        fs::write(home.path().join("f"), b"").unwrap();
927        let e = entry_of(&home.path().join("f")).unwrap();
928        assert_eq!(e.mode & !0o7777, 0, "{:o}", e.mode);
929    }
930
931    #[test]
932    fn it_refuses_what_would_destroy_more_than_asked() {
933        let home = tempfile::tempdir().unwrap();
934        let h = home.path();
935        fs::write(h.join("a"), b"a").unwrap();
936        fs::write(h.join("b"), b"b").unwrap();
937        fs::create_dir(h.join("x")).unwrap();
938        #[cfg(unix)]
939        {
940            std::os::unix::fs::symlink(h, h.join("to-home")).unwrap();
941            std::os::unix::fs::symlink(h, h.join("to-home2")).unwrap();
942        }
943        let replies = exchange(
944            h,
945            &[
946                Request::Rename {
947                    from: "a".into(),
948                    to: "b".into(),
949                },
950                Request::Delete {
951                    path: "~".into(),
952                    recursive: true,
953                },
954                Request::Delete {
955                    path: "/".into(),
956                    recursive: true,
957                },
958                Request::Read {
959                    path: "~".into(),
960                    offset: 0,
961                    len: 10,
962                },
963                // Home, or above it, spelled another way.
964                Request::Delete {
965                    path: "~/x/..".into(),
966                    recursive: true,
967                },
968                Request::Delete {
969                    path: "~/..".into(),
970                    recursive: true,
971                },
972                Request::Delete {
973                    path: h.join("x/..").to_string_lossy().into_owned(),
974                    recursive: true,
975                },
976                Request::Rename {
977                    from: "missing".into(),
978                    to: "b".into(),
979                },
980            ],
981        );
982        assert!(matches!(
983            replies[0],
984            Reply::Err {
985                kind: ErrKind::AlreadyExists,
986                ..
987            }
988        ));
989        for r in [
990            &replies[1],
991            &replies[2],
992            &replies[4],
993            &replies[5],
994            &replies[6],
995        ] {
996            assert!(
997                matches!(
998                    r,
999                    Reply::Err {
1000                        kind: ErrKind::Invalid,
1001                        ..
1002                    }
1003                ),
1004                "{r:?}"
1005            );
1006        }
1007        assert!(matches!(replies[3], Reply::Err { .. }));
1008        assert!(matches!(
1009            replies[7],
1010            Reply::Err {
1011                kind: ErrKind::NotFound,
1012                ..
1013            }
1014        ));
1015        assert_eq!(fs::read(h.join("b")).unwrap(), b"b");
1016        assert!(h.join("x").exists());
1017
1018        // Through a link to home: the link goes, home stays.
1019        #[cfg(unix)]
1020        {
1021            let r = exchange(
1022                h,
1023                &[Request::Delete {
1024                    path: "~/to-home".into(),
1025                    recursive: true,
1026                }],
1027            );
1028            assert_eq!(r[0], Reply::Done);
1029            assert!(h.join("a").exists() && !h.join("to-home").exists());
1030            // A trailing slash would make the OS follow the link: still only
1031            // the link goes.
1032            let r = exchange(
1033                h,
1034                &[Request::Delete {
1035                    path: "~/to-home2/".into(),
1036                    recursive: true,
1037                }],
1038            );
1039            assert_eq!(r[0], Reply::Done);
1040            assert!(h.join("a").exists() && h.join("x").exists() && !h.join("to-home2").exists());
1041        }
1042    }
1043
1044    fn already_exists(r: &Reply) -> bool {
1045        matches!(r, Reply::Err { kind: ErrKind::AlreadyExists, .. })
1046    }
1047
1048    #[test]
1049    fn two_renames_to_one_name_started_together_have_one_winner_and_lose_nothing() {
1050        let home = tempfile::tempdir().unwrap();
1051        let h = home.path();
1052        for round in 0..100 {
1053            fs::write(h.join("a"), b"one").unwrap();
1054            fs::write(h.join("b"), b"two").unwrap();
1055            let to = format!("to{round}");
1056            let start = std::sync::Arc::new(std::sync::Barrier::new(2));
1057            let ask = |from: &str| {
1058                let (start, home, from, to) = (start.clone(), h.to_path_buf(), from.to_string(), to.clone());
1059                std::thread::spawn(move || {
1060                    start.wait();
1061                    handle(&home, Request::Rename { from, to })
1062                })
1063            };
1064            let (a, b) = (ask("a"), ask("b"));
1065            let (a, b) = (a.join().unwrap(), b.join().unwrap());
1066            let (won, lost, kept) = match (&a, &b) {
1067                (Reply::Done, lost) if already_exists(lost) => (&b"one"[..], "b", &b"two"[..]),
1068                (lost, Reply::Done) if already_exists(lost) => (&b"two"[..], "a", &b"one"[..]),
1069                other => panic!("round {round}: exactly one must win: {other:?}"),
1070            };
1071            assert_eq!(fs::read(h.join(&to)).unwrap(), won, "round {round}");
1072            // The one that was refused is where it was, with what it held.
1073            assert_eq!(fs::read(h.join(lost)).unwrap(), kept, "round {round}");
1074            fs::remove_file(h.join(lost)).unwrap();
1075        }
1076    }
1077
1078    #[test]
1079    fn a_file_made_at_the_new_name_while_a_rename_is_under_way_is_never_replaced() {
1080        let home = tempfile::tempdir().unwrap();
1081        let h = home.path();
1082        for round in 0..100 {
1083            fs::write(h.join("a"), b"renamed").unwrap();
1084            let to = format!("to{round}");
1085            let start = std::sync::Arc::new(std::sync::Barrier::new(2));
1086            let renamer = {
1087                let (start, home, to) = (start.clone(), h.to_path_buf(), to.clone());
1088                std::thread::spawn(move || {
1089                    start.wait();
1090                    handle(&home, Request::Rename { from: "a".into(), to })
1091                })
1092            };
1093            let maker = {
1094                let (start, at) = (start.clone(), h.join(&to));
1095                std::thread::spawn(move || {
1096                    start.wait();
1097                    fs::OpenOptions::new().write(true).create_new(true).open(at)?.write_all(b"made")
1098                })
1099            };
1100            let (renamed, made) = (renamer.join().unwrap(), maker.join().unwrap());
1101            match (&renamed, &made) {
1102                (Reply::Done, Err(e)) => {
1103                    assert_eq!(e.kind(), io::ErrorKind::AlreadyExists, "round {round}: {e}");
1104                    assert_eq!(fs::read(h.join(&to)).unwrap(), b"renamed", "round {round}");
1105                }
1106                (lost, Ok(())) if already_exists(lost) => {
1107                    assert_eq!(fs::read(h.join(&to)).unwrap(), b"made", "round {round}");
1108                    assert_eq!(fs::read(h.join("a")).unwrap(), b"renamed", "round {round}");
1109                }
1110                other => panic!("round {round}: exactly one must get the name: {other:?}"),
1111            }
1112        }
1113    }
1114
1115    #[test]
1116    fn a_rename_is_refused_by_an_empty_folder_and_by_a_dangling_link() {
1117        let home = tempfile::tempdir().unwrap();
1118        let h = home.path();
1119        fs::write(h.join("a"), b"a").unwrap();
1120        fs::create_dir(h.join("d")).unwrap();
1121        fs::create_dir(h.join("empty")).unwrap();
1122        // A plain rename replaces an empty folder with a folder.
1123        let r = exchange(h, &[Request::Rename { from: "d".into(), to: "empty".into() }]);
1124        assert!(already_exists(&r[0]), "{r:?}");
1125        assert!(h.join("d").is_dir() && h.join("empty").is_dir());
1126        #[cfg(unix)]
1127        {
1128            std::os::unix::fs::symlink(h.join("nowhere"), h.join("dangling")).unwrap();
1129            let r = exchange(h, &[Request::Rename { from: "a".into(), to: "dangling".into() }]);
1130            assert!(already_exists(&r[0]), "{r:?}");
1131            assert!(fs::symlink_metadata(h.join("dangling")).unwrap().file_type().is_symlink());
1132            assert_eq!(fs::read(h.join("a")).unwrap(), b"a");
1133        }
1134    }
1135
1136    // Where the helper runs. Windows takes a move onto another name of the same file as done, by its own
1137    // rule; nothing is lost there either, the two names being one file.
1138    #[cfg(unix)]
1139    #[test]
1140    fn a_second_name_of_the_same_file_is_a_taken_name() {
1141        let home = tempfile::tempdir().unwrap();
1142        let h = home.path();
1143        fs::write(h.join("a"), b"a").unwrap();
1144        fs::hard_link(h.join("a"), h.join("b")).unwrap();
1145        // Not the other spelling of one name: both names stay, and the answer says the new one is taken
1146        // (a plain rename answers "done" and leaves the old name where it was).
1147        let r = exchange(h, &[Request::Rename { from: "a".into(), to: "b".into() }]);
1148        assert!(already_exists(&r[0]), "{r:?}");
1149        let mut names: Vec<String> =
1150            fs::read_dir(h).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
1151        names.sort();
1152        assert_eq!(names, vec!["a", "b"]);
1153    }
1154
1155    #[test]
1156    fn a_rename_to_its_own_name_changes_nothing() {
1157        let home = tempfile::tempdir().unwrap();
1158        let h = home.path();
1159        fs::write(h.join("a"), b"a").unwrap();
1160        let r = exchange(h, &[Request::Rename { from: "a".into(), to: "~/a".into() }]);
1161        assert_eq!(r[0], Reply::Done);
1162        assert_eq!(fs::read(h.join("a")).unwrap(), b"a");
1163    }
1164}