fix: Make sure directory exists before uploading file in opnsense http
Some checks failed
Run Check Script / check (pull_request) Failing after 31s

This commit is contained in:
Jean-Gabriel Gill-Couture 2025-08-21 17:31:43 -04:00
parent da6610c625
commit 2618441de3

View File

@ -1,5 +1,6 @@
use std::{ use std::{
net::IpAddr, net::IpAddr,
path::Path,
sync::Arc, sync::Arc,
time::{SystemTime, UNIX_EPOCH}, time::{SystemTime, UNIX_EPOCH},
}; };
@ -48,7 +49,6 @@ impl OPNsenseShell for SshOPNSenseShell {
} }
async fn write_content_to_file(&self, content: &str, filename: &str) -> Result<String, Error> { async fn write_content_to_file(&self, content: &str, filename: &str) -> Result<String, Error> {
// TODO fix this to create the directory before uploading the file
let channel = self.get_ssh_channel().await?; let channel = self.get_ssh_channel().await?;
channel channel
.request_subsystem(true, "sftp") .request_subsystem(true, "sftp")
@ -58,6 +58,14 @@ impl OPNsenseShell for SshOPNSenseShell {
.await .await
.expect("Should acquire sftp subsystem"); .expect("Should acquire sftp subsystem");
if let Some(parent) = Path::new(filename).parent() {
if let Some(parent_str) = parent.to_str() {
if !parent_str.is_empty() {
self.ensure_remote_dir_exists(&sftp, parent_str).await?;
}
}
}
let mut file = sftp.create(filename).await.unwrap(); let mut file = sftp.create(filename).await.unwrap();
file.write_all(content.as_bytes()).await?; file.write_all(content.as_bytes()).await?;
@ -74,10 +82,7 @@ impl OPNsenseShell for SshOPNSenseShell {
.await .await
.expect("Should acquire sftp subsystem"); .expect("Should acquire sftp subsystem");
if !sftp.try_exists(destination).await? { self.ensure_remote_dir_exists(&sftp, destination).await?;
info!("Creating remote directory {destination}");
sftp.create_dir(destination).await?;
}
info!("Reading local directory {source}"); info!("Reading local directory {source}");
let mut entries = read_dir(source).await?; let mut entries = read_dir(source).await?;
@ -154,6 +159,18 @@ impl SshOPNSenseShell {
wait_for_completion(&mut channel).await wait_for_completion(&mut channel).await
} }
async fn ensure_remote_dir_exists(
&self,
sftp: &SftpSession,
path: &str,
) -> Result<(), Error> {
if !sftp.try_exists(path).await? {
info!("Creating remote directory {path}");
sftp.create_dir(path).await?;
}
Ok(())
}
pub fn new(host: (IpAddr, u16), credentials: SshCredentials, ssh_config: Arc<Config>) -> Self { pub fn new(host: (IpAddr, u16), credentials: SshCredentials, ssh_config: Arc<Config>) -> Self {
info!("Initializing SshOPNSenseShell on host {host:?}"); info!("Initializing SshOPNSenseShell on host {host:?}");
Self { Self {