use std::collections::HashMap;
use std::io::{self};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use clap::{ArgAction, Args, CommandFactory, FromArgMatches, Parser, Subcommand};
use dcmnorm::dicom_io::{
echo_scu, find_scu, move_scu, start_scp, store_scu, DimseLogger, EchoScuOptions,
FindScuOptions, MoveScuOptions, MoveScuResult, QueryRetrieveLevel, ScpHandlers, ScpOptions,
StoreScuOptions, StoreScuResult,
};
use sha2::{Digest, Sha256};
const DEFAULT_SCU_MAX_PDU: u32 = 16_384;
const DEFAULT_SCP_MAX_PDU: u32 = 262_144;
const DEFAULT_SCP_IDLE_TIMEOUT_SECS: u64 = 300;
const DEFAULT_AE_TITLE: &str = "DCMTALK";
#[derive(Parser)]
#[command(name = "dcmtalk")]
#[command(
about = "DICOM network (DIMSE) client/server: verify, send, query, retrieve, and receive"
)]
#[command(
long_about = "A DIMSE command-line tool covering the same ground as dcmtk's echoscu/storescu/findscu/movescu/storescp, built on dcmnorm's native (non-dcmtk) DICOM Upper Layer implementation. Every subcommand accepts --verbose to log association negotiation, presentation contexts, and each DIMSE command/response exchanged."
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Echoscu(EchoscuArgs),
Storescu(StorescuArgs),
Findscu(FindscuArgs),
Movescu(MovescuArgs),
Storescp(StorescpArgs),
}
#[derive(Args)]
struct ScuCommonArgs {
destination: String,
#[arg(long = "calling-aet", short = 'a', default_value = DEFAULT_AE_TITLE)]
calling_ae: String,
#[arg(long = "called-aet", short = 'c')]
called_ae: Option<String>,
#[arg(long)]
timeout: Option<u64>,
#[arg(long, short = 'v', action = ArgAction::SetTrue)]
verbose: bool,
}
#[derive(Args)]
struct EchoscuArgs {
#[command(flatten)]
common: ScuCommonArgs,
}
#[derive(Args)]
struct StorescuArgs {
#[command(flatten)]
common: ScuCommonArgs,
#[arg(required = true, num_args = 1..)]
files: Vec<PathBuf>,
#[arg(long = "max-pdu", default_value_t = DEFAULT_SCU_MAX_PDU)]
max_pdu: u32,
#[arg(long, action = ArgAction::SetTrue)]
never_transcode: bool,
}
#[derive(Args)]
struct FindscuArgs {
#[command(flatten)]
common: ScuCommonArgs,
#[arg(short = 'k', long = "key", action = ArgAction::Append, value_name = "KEY[=VALUE]")]
keys: Vec<String>,
#[arg(long = "max-pdu", default_value_t = DEFAULT_SCU_MAX_PDU)]
max_pdu: u32,
}
#[derive(Args)]
struct MovescuArgs {
#[command(flatten)]
common: ScuCommonArgs,
move_destination_ae: String,
study_instance_uid: String,
#[arg(
long = "level",
default_value = "STUDY",
value_name = "STUDY|SERIES|IMAGE"
)]
level: String,
#[arg(long = "series-uid", value_name = "UID")]
series_uid: Option<String>,
#[arg(long = "sop-uid", action = ArgAction::Append, value_name = "UID")]
sop_uids: Vec<String>,
#[arg(long = "max-pdu", default_value_t = DEFAULT_SCU_MAX_PDU)]
max_pdu: u32,
}
#[derive(Args)]
struct StorescpArgs {
port: u16,
#[arg(long = "ae-title", short = 'a', default_value = DEFAULT_AE_TITLE)]
ae_title: String,
#[arg(long = "cache-path", default_value = ".")]
cache_path: PathBuf,
#[arg(long = "max-pdu", default_value_t = DEFAULT_SCP_MAX_PDU)]
max_pdu: u32,
#[arg(long = "idle-timeout", default_value_t = DEFAULT_SCP_IDLE_TIMEOUT_SECS)]
idle_timeout: u64,
#[arg(long = "transfer-syntax", value_name = "UID")]
transfer_syntax: Option<String>,
#[arg(long, short = 'v', action = ArgAction::SetTrue)]
verbose: bool,
}
struct StderrLogger;
impl DimseLogger for StderrLogger {
fn log(&self, message: String) {
eprintln!("[dcmtalk] {message}");
}
}
fn logger_box(verbose: bool) -> Option<Box<dyn DimseLogger>> {
if verbose {
Some(Box::new(StderrLogger))
} else {
None
}
}
fn logger_arc(verbose: bool) -> Option<Arc<dyn DimseLogger>> {
if verbose {
Some(Arc::new(StderrLogger))
} else {
None
}
}
fn main() {
let version_with_hash = cli_version_with_binary_hash();
let version_static: &'static str = Box::leak(version_with_hash.into_boxed_str());
let matches = Cli::command().version(version_static).get_matches();
let cli = Cli::from_arg_matches(&matches).expect("clap generated invalid matches");
if let Err(error) = run(cli.command) {
eprintln!("dcmtalk: {error}");
std::process::exit(1);
}
}
fn cli_version_with_binary_hash() -> String {
let base_version = env!("CARGO_PKG_VERSION");
match running_binary_sha256_prefix(12) {
Some(hash_prefix) => format!("{base_version}-{hash_prefix}"),
None => base_version.to_string(),
}
}
fn running_binary_sha256_prefix(prefix_len: usize) -> Option<String> {
let exe_path = std::env::current_exe().ok()?;
let exe_bytes = std::fs::read(exe_path).ok()?;
let mut hasher = Sha256::new();
hasher.update(&exe_bytes);
let digest = hasher.finalize();
let mut hex = String::with_capacity(digest.len() * 2);
for byte in digest {
use std::fmt::Write as _;
write!(&mut hex, "{byte:02x}").ok()?;
}
Some(hex.chars().take(prefix_len).collect())
}
fn run(command: Command) -> Result<(), Box<dyn std::error::Error>> {
match command {
Command::Echoscu(args) => run_echoscu(args),
Command::Storescu(args) => run_storescu(args),
Command::Findscu(args) => run_findscu(args),
Command::Movescu(args) => run_movescu(args),
Command::Storescp(args) => run_storescp(args),
}
}
fn status_description(status: u16) -> &'static str {
match status {
0x0000 => "Success",
0xFF00 | 0xFF01 => "Pending",
0xFE00 => "Cancel",
0xA701 | 0xA702 => "Refused: Out of Resources",
0xA801 => "Move Destination Unknown",
0xA900 => "Identifier Does Not Match SOP Class",
0xC000..=0xCFFF => "Unable to Process",
0xB000..=0xBFFF => "Warning",
_ => "Failure",
}
}
fn other_error(message: impl Into<String>) -> Box<dyn std::error::Error> {
io::Error::other(message.into()).into()
}
fn run_echoscu(args: EchoscuArgs) -> Result<(), Box<dyn std::error::Error>> {
let common = args.common;
let options = EchoScuOptions {
calling_ae_title: common.calling_ae,
called_ae_title: common.called_ae,
timeout: common.timeout.map(Duration::from_secs),
on_log: logger_box(common.verbose),
cancel: None,
};
let status = echo_scu(&common.destination, options)?;
println!(
"C-ECHO status=0x{status:04X} ({})",
status_description(status)
);
if status != 0x0000 {
return Err(other_error(format!(
"C-ECHO failed with status 0x{status:04X}"
)));
}
Ok(())
}
fn collect_dicom_files(paths: &[PathBuf]) -> Vec<PathBuf> {
let mut files = Vec::new();
for path in paths {
collect_dicom_files_from(path, &mut files);
}
files
}
fn collect_dicom_files_from(path: &Path, files: &mut Vec<PathBuf>) {
if path.is_dir() {
let Ok(entries) = std::fs::read_dir(path) else {
return;
};
let mut entries: Vec<_> = entries.filter_map(Result::ok).collect();
entries.sort_by_key(|entry| entry.file_name());
for entry in entries {
collect_dicom_files_from(&entry.path(), files);
}
} else if path.is_file() {
files.push(path.to_owned());
}
}
fn run_storescu(args: StorescuArgs) -> Result<(), Box<dyn std::error::Error>> {
let common = args.common;
let files = collect_dicom_files(&args.files);
if files.is_empty() {
return Err(other_error("no files found under the given path(s)"));
}
let options = StoreScuOptions {
calling_ae_title: common.calling_ae,
called_ae_title: common.called_ae,
max_pdu_length: args.max_pdu,
never_transcode: args.never_transcode,
timeout: common.timeout.map(Duration::from_secs),
on_log: logger_box(common.verbose),
cancel: None,
};
let results: Vec<StoreScuResult> = store_scu(&common.destination, &files, options)?;
let mut failures = 0usize;
for result in &results {
if result.status != 0x0000 {
failures += 1;
}
println!(
"{} status=0x{:04X} ({})",
result.sop_instance_uid,
result.status,
status_description(result.status)
);
}
println!("{} instance(s) sent, {} failed", results.len(), failures);
if failures > 0 {
return Err(other_error(format!(
"{failures} of {} instance(s) failed",
results.len()
)));
}
Ok(())
}
fn parse_query_keys(keys: &[String]) -> HashMap<String, String> {
let mut query = HashMap::new();
for raw in keys {
match raw.split_once('=') {
Some((key, value)) => {
query.insert(key.trim().to_owned(), value.to_owned());
}
None => {
query.insert(raw.trim().to_owned(), String::new());
}
}
}
query
}
fn run_findscu(args: FindscuArgs) -> Result<(), Box<dyn std::error::Error>> {
let common = args.common;
let query = parse_query_keys(&args.keys);
let options = FindScuOptions {
calling_ae_title: common.calling_ae,
called_ae_title: common.called_ae,
max_pdu_length: args.max_pdu,
timeout: common.timeout.map(Duration::from_secs),
on_log: logger_box(common.verbose),
cancel: None,
};
let matches = find_scu(&common.destination, &query, options)?;
for json in &matches {
println!("{json}");
}
eprintln!("{} match(es)", matches.len());
Ok(())
}
fn run_movescu(args: MovescuArgs) -> Result<(), Box<dyn std::error::Error>> {
let common = args.common;
let level: QueryRetrieveLevel = args.level.parse()?;
let options = MoveScuOptions {
calling_ae_title: common.calling_ae,
called_ae_title: common.called_ae,
max_pdu_length: args.max_pdu,
timeout: common.timeout.map(Duration::from_secs),
stale_data_path: None,
stale_data_timeout: None,
on_log: logger_box(common.verbose),
cancel: None,
query_retrieve_level: Some(level),
series_instance_uid: args.series_uid,
sop_instance_uids: args.sop_uids,
};
let result: MoveScuResult = move_scu(
&common.destination,
&args.move_destination_ae,
&args.study_instance_uid,
options,
)?;
println!(
"C-MOVE status=0x{:04X} ({}) completed={} failed={} warning={} remaining={}{}",
result.status,
status_description(result.status),
result.completed,
result.failed,
result.warning,
result.remaining,
if result.cancelled { " (cancelled)" } else { "" }
);
if !result.cancelled && result.status != 0x0000 {
return Err(other_error(format!(
"C-MOVE failed with status 0x{:04X}",
result.status
)));
}
Ok(())
}
struct StandaloneScpHandlers;
impl ScpHandlers for StandaloneScpHandlers {
fn on_find(
&self,
_filter: &HashMap<String, String>,
) -> Result<Vec<HashMap<String, String>>, String> {
Err("C-FIND is not supported by dcmtalk storescp".to_owned())
}
fn on_move(
&self,
_study_instance_uid: &str,
_move_destination_ae: &str,
) -> Result<bool, String> {
Err("C-MOVE is not supported by dcmtalk storescp".to_owned())
}
fn on_association_complete(&self, stored_instances_by_study: &HashMap<String, Vec<String>>) {
for (study_instance_uid, paths) in stored_instances_by_study {
println!(
"stored study {study_instance_uid}: {} instance(s)",
paths.len()
);
for path in paths {
println!(" {path}");
}
}
}
}
fn run_storescp(args: StorescpArgs) -> Result<(), Box<dyn std::error::Error>> {
std::fs::create_dir_all(&args.cache_path)?;
let options = ScpOptions {
ae_title: args.ae_title.clone(),
max_pdu_length: args.max_pdu,
idle_timeout: Duration::from_secs(args.idle_timeout),
on_log: logger_arc(args.verbose),
storage_transfer_syntax: args.transfer_syntax.clone(),
..Default::default()
};
let scp = start_scp(
args.port,
args.cache_path.clone(),
Arc::new(StandaloneScpHandlers),
options,
)?;
println!(
"dcmtalk storescp listening on port {} (AE title {:?}, cache {}). Press Ctrl+C to stop.",
scp.local_port(),
args.ae_title,
args.cache_path.display()
);
loop {
std::thread::park();
}
}