Skip to content

Commit

Permalink
support clean up the historical control_directory (#126)
Browse files Browse the repository at this point in the history
* support clean up the historical control_directory before creating a SessionBuilder

* Update src/builder.rs

Co-authored-by: Jiahao XU <[email protected]>

* Update src/builder.rs

Co-authored-by: Jiahao XU <[email protected]>

* Update src/builder.rs

Co-authored-by: Jiahao XU <[email protected]>

* optimizing code

---------

Co-authored-by: Jiahao XU <[email protected]>
  • Loading branch information
baoyachi and NobodyXu authored Jul 31, 2023
1 parent fefd900 commit 2e2bfb2
Showing 1 changed file with 44 additions and 2 deletions.
46 changes: 44 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,26 @@ fn get_default_control_dir<'a>() -> Result<&'a Path, Error> {
})
}

fn clean_history_control_dir(socketdir: &Path, prefix: &str) -> io::Result<()> {
// Read the entries in the parent directory
fs::read_dir(socketdir)?
// 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)
} 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 +64,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 +82,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 +155,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)
///
/// 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,8 +331,14 @@ impl SessionBuilder {
get_default_control_dir()?
};

let prefix = ".ssh-connection";

if self.clean_history_control_dir {
let _ = clean_history_control_dir(&socketdir, prefix);

Check warning on line 337 in src/builder.rs

View workflow job for this annotation

GitHub Actions / clippy

this expression creates a reference which is immediately dereferenced by the compiler

warning: this expression creates a reference which is immediately dereferenced by the compiler --> src/builder.rs:337:47 | 337 | let _ = clean_history_control_dir(&socketdir, prefix); | ^^^^^^^^^^ help: change this to: `socketdir` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow = note: `#[warn(clippy::needless_borrow)]` on by default
}

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

Expand Down

0 comments on commit 2e2bfb2

Please sign in to comment.