use anyhow::{Context, Result};
use smb2::types::status::NtStatus;
use smb2::{FileInfo, SmbClient, Tree};
use crate::auth::Credentials;
use crate::target::Target;
#[derive(Debug, Clone)]
pub enum Job {
Stat(String),
Rename {
from: String,
to: String,
},
DeleteFile(String),
DeleteDirectory(String),
CreateDirectory(String),
CreateDirectoryIfMissing(String),
}
#[derive(Debug)]
pub enum Outcome {
Done,
Stat(FileInfo),
Failed(String),
}
impl Outcome {
pub fn error(&self) -> Option<&str> {
match self {
Outcome::Failed(message) => Some(message),
_ => None,
}
}
}
pub async fn connect_all(
target: &Target,
credentials: &Credentials,
count: usize,
) -> Result<Vec<(SmbClient, Tree)>> {
let mut connections = Vec::with_capacity(count);
for index in 0..count {
connections.push(
connect_one(target, credentials)
.await
.with_context(|| format!("opening connection {} of {count}", index + 1))?,
);
}
Ok(connections)
}
async fn connect_one(target: &Target, credentials: &Credentials) -> Result<(SmbClient, Tree)> {
let mut client = smb2::connect(&target.addr(), &credentials.username, &credentials.password)
.await
.with_context(|| format!("connecting to {}", target.addr()))?;
let tree = client
.connect_share(&target.share)
.await
.with_context(|| format!("connecting to share {:?}", target.share))?;
Ok((client, tree))
}
pub async fn run(
target: &Target,
credentials: &Credentials,
concurrency: usize,
jobs: Vec<Job>,
mut on_progress: impl FnMut(usize, usize),
) -> Result<Vec<Outcome>> {
if jobs.is_empty() {
return Ok(vec![]);
}
let total = jobs.len();
let workers = concurrency.clamp(1, total);
let mut lanes: Vec<Vec<(usize, Job)>> = vec![Vec::new(); workers];
for (index, job) in jobs.into_iter().enumerate() {
lanes[index % workers].push((index, job));
}
let (progress_tx, mut progress_rx) = tokio::sync::mpsc::unbounded_channel::<()>();
let mut handles = Vec::with_capacity(workers);
for lane in lanes {
let target = target.clone();
let credentials = credentials.clone();
let progress_tx = progress_tx.clone();
handles.push(tokio::spawn(async move {
let (mut client, mut tree) = connect_one(&target, &credentials).await?;
let mut results = Vec::with_capacity(lane.len());
for (index, job) in lane {
let outcome = execute(&mut client, &mut tree, &job).await;
let _ = progress_tx.send(());
results.push((index, outcome));
}
let _ = client.disconnect_share(&tree).await;
Ok::<_, anyhow::Error>(results)
}));
}
drop(progress_tx);
let mut finished = 0;
while progress_rx.recv().await.is_some() {
finished += 1;
on_progress(finished, total);
}
let mut outcomes: Vec<Option<Outcome>> = (0..total).map(|_| None).collect();
for handle in handles {
for (index, outcome) in handle.await.context("worker task panicked")?? {
outcomes[index] = Some(outcome);
}
}
Ok(outcomes
.into_iter()
.map(|outcome| outcome.unwrap_or_else(|| Outcome::Failed("no result".to_string())))
.collect())
}
async fn execute(client: &mut SmbClient, tree: &mut Tree, job: &Job) -> Outcome {
match job {
Job::Stat(path) => match client.stat(tree, path).await {
Ok(info) => Outcome::Stat(info),
Err(error) => Outcome::Failed(error.to_string()),
},
Job::Rename { from, to } => report(client.rename(tree, from, to).await),
Job::DeleteFile(path) => report(client.delete_file(tree, path).await),
Job::DeleteDirectory(path) => report(client.delete_directory(tree, path).await),
Job::CreateDirectory(path) => report(client.create_directory(tree, path).await),
Job::CreateDirectoryIfMissing(path) => match client.create_directory(tree, path).await {
Err(error) if error.status() == Some(NtStatus::OBJECT_NAME_COLLISION) => Outcome::Done,
other => report(other),
},
}
}
fn report(result: smb2::Result<()>) -> Outcome {
match result {
Ok(()) => Outcome::Done,
Err(error) => Outcome::Failed(error.to_string()),
}
}