Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support clean up the historical control_directory #126

Merged
merged 6 commits into from
Jul 31, 2023
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 48 additions & 2 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ use super::{Error, Session};

use std::borrow::Cow;
use std::ffi::OsString;
use std::fs;
use std::iter::IntoIterator;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::str;
use std::{fs, io};

use dirs::state_dir;
use once_cell::sync::OnceCell;
Expand Down Expand Up @@ -34,6 +34,31 @@ fn get_default_control_dir<'a>() -> Result<&'a Path, Error> {
})
}

fn clean_history_control_dir(dir: &TempDir, prefix: &str) -> io::Result<()> {
// Check if the parent directory of the given TempDir exists
if let Some(parent) = dir.path().parent() {
// Read the entries in the parent directory
fs::read_dir(parent)?
// Filter out and keep only the valid entries
.filter_map(Result::ok)
// Filter the entries to only include files that start with prefix
.filter(|entry| {
if let Ok(file_type) = entry.file_type() {
file_type.is_dir()
&& entry.file_name().to_string_lossy().starts_with(prefix)
&& entry.path() != dir.path()
} else {
false
}
})
// For each matching entry, remove the directory
.for_each(|entry| {
let _ = fs::remove_dir_all(entry.path());
});
}
Ok(())
}

/// Build a [`Session`] with options.
#[derive(Debug, Clone)]
pub struct SessionBuilder {
Expand All @@ -44,6 +69,7 @@ pub struct SessionBuilder {
server_alive_interval: Option<u64>,
known_hosts_check: KnownHosts,
control_dir: Option<PathBuf>,
clean_history_control_dir: bool,
config_file: Option<PathBuf>,
compression: Option<bool>,
jump_hosts: Vec<Box<str>>,
Expand All @@ -61,6 +87,7 @@ impl Default for SessionBuilder {
server_alive_interval: None,
known_hosts_check: KnownHosts::Add,
control_dir: None,
clean_history_control_dir: false,
config_file: None,
compression: None,
jump_hosts: Vec::new(),
Expand Down Expand Up @@ -133,6 +160,20 @@ impl SessionBuilder {
self
}

/// Clean up the temporary directories with the `.ssh-connection` prefix
/// in directory specified by [`SessionBuilder::control_directory`], created by
/// previous `openssh::Session` that is not cleaned up for some reasons
/// (e.g. process getting killed, abort on panic, etc)
baoyachi marked this conversation as resolved.
Show resolved Hide resolved
///
/// Use this with caution, do not enable this if you don't understand
/// what it does,
#[cfg(not(windows))]
#[cfg_attr(docsrs, doc(cfg(not(windows))))]
pub fn clean_history_control_directory(&mut self, clean: bool) -> &mut Self {
self.clean_history_control_dir = clean;
self
}

/// Set an alternative per-user configuration file.
///
/// By default, ssh uses `~/.ssh/config`. This is equivalent to `ssh -F <p>`.
Expand Down Expand Up @@ -295,11 +336,16 @@ impl SessionBuilder {
get_default_control_dir()?
};

let prefix = ".ssh-connection";
let dir = Builder::new()
.prefix(".ssh-connection")
.prefix(prefix)
.tempdir_in(socketdir)
.map_err(Error::Master)?;

if self.clean_history_control_dir {
let _ = clean_history_control_dir(&dir, prefix);
}
NobodyXu marked this conversation as resolved.
Show resolved Hide resolved

let log = dir.path().join("log");

let mut init = process::Command::new("ssh");
Expand Down
Loading