aboutsummaryrefslogtreecommitdiffstats
path: root/pkgs
diff options
context:
space:
mode:
Diffstat (limited to 'pkgs')
-rw-r--r--pkgs/populate/src/run.rs128
1 files changed, 109 insertions, 19 deletions
diff --git a/pkgs/populate/src/run.rs b/pkgs/populate/src/run.rs
index c4be18c..bdff78f 100644
--- a/pkgs/populate/src/run.rs
+++ b/pkgs/populate/src/run.rs
@@ -101,6 +101,9 @@ pub struct Context {
/// Populate's private temporary directory, which is $TMPDIR for the
/// commands it runs.
pub tmpdir: PathBuf,
+ /// The directory of the master connection's socket, see socket_dir:
+ /// tmpdir, or one of its own.
+ socket_dir: PathBuf,
/// The ssh command, with the options for the target and for sharing a
/// master connection, as a script in tmpdir, for rsync's -e as well.
pub ssh: PathBuf,
@@ -131,15 +134,15 @@ pub struct Context {
impl Context {
/// Creates the temporary directory, and the ssh script in it.
pub fn new(target: Target, local: bool) -> Result<Context> {
- let output = Command::new("mktemp")
- .args(["-dt", "populate.XXXXXXXX"])
- .stderr(Stdio::inherit())
- .output()
- .map_err(|e| Failure::Message(format!("error: can't run mktemp: {e}")))?;
- if !output.status.success() {
- return Err(failed(output.status));
- }
- let tmpdir = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim_end());
+ let tmpdir = mktemp(&["-dt".as_ref(), "populate.XXXXXXXX".as_ref()], true)?;
+ let socket_dir = if local {
+ tmpdir.clone()
+ } else {
+ socket_dir(&tmpdir, std::env::var_os("XDG_RUNTIME_DIR")).map_err(|e| {
+ let _ = Command::new("rm").arg("-R").arg(&tmpdir).status();
+ e
+ })?
+ };
// Shared with the commands populate runs.
std::env::set_var("TMPDIR", &tmpdir);
let ssh = tmpdir.join("ssh");
@@ -148,6 +151,7 @@ impl Context {
target,
local,
tmpdir,
+ socket_dir,
ssh,
ssh_nix,
metadata: Default::default(),
@@ -189,7 +193,7 @@ impl Context {
options.extend(["-p".to_string(), port.clone()]);
}
if shared {
- let control_path = control_path(&self.tmpdir);
+ let control_path = control_path(&self.socket_dir);
// The keepalives end the connection, and with it the command
// holding the lock on the target, about a minute after the
// target stops answering, e.g. when the network fails, instead
@@ -448,7 +452,8 @@ impl Context {
}
/// Releases the lock, stops the ssh master, if any command started one,
- /// and removes the temporary directory.
+ /// and removes the temporary directory, and the socket's, if that's one of
+ /// its own.
pub fn clean_up(&self) {
self.unlock();
if !self.local {
@@ -466,6 +471,9 @@ impl Context {
}
}
let _ = Command::new("rm").arg("-R").arg(&self.tmpdir).status();
+ if self.socket_dir != self.tmpdir {
+ let _ = Command::new("rm").arg("-R").arg(&self.socket_dir).status();
+ }
}
}
@@ -482,15 +490,68 @@ pub fn local_shell(script: &str, args: &[&str], dir: &Path) -> Command {
command
}
-/// The ssh option naming the master connection's socket in tmpdir. The
-/// name is short, since the socket's path, with the suffix ssh adds while
-/// it sets up the connection, must fit in about 100 bytes, and TMPDIR can
-/// be long, e.g. nix-shell's below /run/user; a run has only one target.
-/// ssh expands % in ControlPath, so the directory's ones get doubled.
-fn control_path(tmpdir: &Path) -> String {
+/// Runs mktemp with args, returning the path it prints, and what it prints
+/// to standard error if verbose.
+fn mktemp(args: &[&std::ffi::OsStr], verbose: bool) -> Result<PathBuf> {
+ let output = Command::new("mktemp")
+ .args(args)
+ .stderr(if verbose {
+ Stdio::inherit()
+ } else {
+ Stdio::null()
+ })
+ .output()
+ .map_err(|e| Failure::Message(format!("error: can't run mktemp: {e}")))?;
+ if !output.status.success() {
+ return Err(failed(output.status));
+ }
+ Ok(PathBuf::from(
+ String::from_utf8_lossy(&output.stdout).trim_end(),
+ ))
+}
+
+/// The name of the master connection's socket, short, since its path must
+/// fit into a socket address; a run has only one target.
+const SOCKET: &str = "ssh.sock";
+
+/// Whether the path of the master connection's socket in dir fits into a
+/// socket address, 104 bytes on macOS, 108 on Linux, with the trailing NUL,
+/// and with the suffix of 17 bytes ssh adds while it sets up the
+/// connection.
+fn socket_fits(dir: &Path) -> bool {
+ dir.as_os_str().len() + 1 + SOCKET.len() + 17 < 104
+}
+
+/// The directory for the master connection's socket: tmpdir, if the
+/// socket's path fits there, which TMPDIR may be too long for, e.g. that of
+/// nested nix-shells. Else a directory of its own, from mktemp, in
+/// runtime, XDG_RUNTIME_DIR, which is meant for such sockets, if that's
+/// set, and mktemp can make one there, which the socket's path fits, and
+/// else in /tmp. Everything else stays in tmpdir.
+fn socket_dir(tmpdir: &Path, runtime: Option<std::ffi::OsString>) -> Result<PathBuf> {
+ if socket_fits(tmpdir) {
+ return Ok(tmpdir.to_path_buf());
+ }
+ if let Some(runtime) = runtime {
+ let template = Path::new(&runtime).join("populate.XXXXXXXX");
+ if template.is_absolute() {
+ if let Ok(dir) = mktemp(&["-d".as_ref(), template.as_os_str()], false) {
+ if socket_fits(&dir) {
+ return Ok(dir);
+ }
+ let _ = fs::remove_dir(&dir);
+ }
+ }
+ }
+ mktemp(&["-d".as_ref(), "/tmp/populate.XXXXXXXX".as_ref()], true)
+}
+
+/// The ssh option naming the master connection's socket in dir. ssh
+/// expands % in ControlPath, so the directory's ones get doubled.
+fn control_path(dir: &Path) -> String {
format!(
- "ControlPath={}/ssh.sock",
- tmpdir.to_string_lossy().replace('%', "%%")
+ "ControlPath={}/{SOCKET}",
+ dir.to_string_lossy().replace('%', "%%")
)
}
@@ -658,6 +719,35 @@ mod tests {
}
#[test]
+ fn socket_dirs() {
+ let one = "/run/user/1337/nix-shell-1302688-4246724126/populate.bOsBkVtJ";
+ let nested = "/run/user/1337/nix-shell-1302688-4246724126/nix-shell-1479481-1715487425/populate.T5aG12cx";
+ // One nix-shell's TMPDIR fits, so the socket stays in tmpdir.
+ assert!(socket_fits(Path::new(one)));
+ assert_eq!(
+ socket_dir(Path::new(one), None).ok(),
+ Some(PathBuf::from(one))
+ );
+ assert!(!socket_fits(Path::new(nested)));
+ // Else it goes to XDG_RUNTIME_DIR, here a directory of the test's
+ // own, else to /tmp, also if mktemp can't make one in the former.
+ let runtime = mktemp(
+ &["-d".as_ref(), "/tmp/populate-test.XXXXXXXX".as_ref()],
+ true,
+ )
+ .expect("mktemp");
+ let dir = socket_dir(Path::new(nested), Some(runtime.clone().into())).expect("socket_dir");
+ assert_eq!(dir.parent(), Some(runtime.as_path()));
+ fs::remove_dir(&dir).expect("remove_dir");
+ fs::remove_dir(&runtime).expect("remove_dir");
+ for runtime in [None, Some(runtime.into())] {
+ let dir = socket_dir(Path::new(nested), runtime).expect("socket_dir");
+ assert_eq!(dir.parent(), Some(Path::new("/tmp")));
+ fs::remove_dir(&dir).expect("remove_dir");
+ }
+ }
+
+ #[test]
fn control_paths() {
assert_eq!(
control_path(Path::new("/tmp/populate.abc")),