use std::collections::HashMap;
use std::error::Error as StdError;
use std::fmt;
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use dcmnorm_core::dictionary::{DataDictionary, DataDictionaryEntry};
use dcmnorm_core::{dicom_value, DataElement, PrimitiveValue, VR};
use dcmnorm_dictionary::{tags, uids, StandardDataDictionary};
use dcmnorm_dimse::{
association::{client::ClientAssociationOptions, Error as AssociationError},
pdu::{PDataValue, PDataValueType, Pdu, PresentationContextNegotiated},
ClientAssociation, Incoming,
};
use dcmnorm_encoding::{TransferSyntax, TransferSyntaxIndex};
use dcmnorm_object::{FileMetaTable, InMemDicomObject, OpenFileOptions, ReadPreamble};
use dcmnorm_transcode::TransferSyntaxRegistry;
use super::io::{can_encode_transfer_syntax, read_dicom_file, transcode_dcmnorm_object_owned};
use super::json::write_dataset_as_dicom_json_with_options;
use super::streaming_transcode::prepare_streaming_dataset_for_dimse;
use super::types::{
DicomJsonError, DicomJsonFormat, DicomJsonKeyStyle, DicomJsonWriteOptions, ReadError,
TranscodeError, WriteError,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CancelMode {
Release,
Abort,
}
pub struct CancelSignal(AtomicU8);
impl CancelSignal {
pub fn new() -> Arc<Self> {
Arc::new(Self(AtomicU8::new(0)))
}
pub fn request(&self, mode: CancelMode) {
let value = match mode {
CancelMode::Release => 1,
CancelMode::Abort => 2,
};
self.0.store(value, Ordering::SeqCst);
}
pub fn requested(&self) -> Option<CancelMode> {
match self.0.load(Ordering::SeqCst) {
1 => Some(CancelMode::Release),
2 => Some(CancelMode::Abort),
_ => None,
}
}
}
#[derive(Debug)]
pub enum DimseError {
Association(AssociationError),
Read(ReadError),
Write(WriteError),
Transcode(TranscodeError),
Json(DicomJsonError),
Io(std::io::Error),
UnknownTransferSyntax(String),
NoAcceptedPresentationContext,
NoAcceptablePresentationContext {
sop_class_uid: String,
transfer_syntax_uid: String,
},
NoFilesToSend,
InvalidQueryKey(String),
InvalidMoveIdentifier(String),
Protocol(String),
AbsoluteTimeout,
StaleDataConnection {
path: PathBuf,
},
Cancelled(CancelMode),
}
impl fmt::Display for DimseError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Association(error) => write!(formatter, "DICOM association error: {error}"),
Self::Read(error) => write!(formatter, "failed to read DICOM data: {error}"),
Self::Write(error) => write!(formatter, "failed to write DICOM data: {error}"),
Self::Transcode(error) => write!(formatter, "failed to transcode DICOM data: {error}"),
Self::Json(error) => write!(formatter, "failed to build DICOM JSON: {error}"),
Self::Io(error) => write!(formatter, "I/O error: {error}"),
Self::UnknownTransferSyntax(uid) => write!(formatter, "unknown transfer syntax: {uid}"),
Self::NoAcceptedPresentationContext => {
write!(formatter, "peer did not accept any proposed presentation context")
}
Self::NoAcceptablePresentationContext { sop_class_uid, transfer_syntax_uid } => write!(
formatter,
"no accepted presentation context for SOP class {sop_class_uid} with transfer syntax {transfer_syntax_uid}"
),
Self::NoFilesToSend => write!(formatter, "no valid DICOM files to send"),
Self::InvalidQueryKey(key) => write!(formatter, "invalid query key '{key}'"),
Self::InvalidMoveIdentifier(message) => write!(formatter, "invalid C-MOVE identifier: {message}"),
Self::Protocol(message) => write!(formatter, "DIMSE protocol error: {message}"),
Self::AbsoluteTimeout => write!(formatter, "operation exceeded its absolute timeout"),
Self::StaleDataConnection { path } => write!(
formatter,
"no new data written under {} within the configured staleness window; treating the connection as stale",
path.display()
),
Self::Cancelled(CancelMode::Release) => {
write!(formatter, "operation was cancelled by the caller (graceful release)")
}
Self::Cancelled(CancelMode::Abort) => {
write!(formatter, "operation was cancelled by the caller (hard abort)")
}
}
}
}
impl StdError for DimseError {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
Self::Association(error) => Some(error),
Self::Read(error) => Some(error),
Self::Write(error) => Some(error),
Self::Transcode(error) => Some(error),
Self::Json(error) => Some(error),
Self::Io(error) => Some(error),
Self::UnknownTransferSyntax(_)
| Self::NoAcceptedPresentationContext
| Self::NoAcceptablePresentationContext { .. }
| Self::NoFilesToSend
| Self::InvalidQueryKey(_)
| Self::InvalidMoveIdentifier(_)
| Self::Protocol(_)
| Self::AbsoluteTimeout
| Self::StaleDataConnection { .. }
| Self::Cancelled(_) => None,
}
}
}
impl From<AssociationError> for DimseError {
fn from(value: AssociationError) -> Self {
Self::Association(value)
}
}
impl From<ReadError> for DimseError {
fn from(value: ReadError) -> Self {
Self::Read(value)
}
}
impl From<WriteError> for DimseError {
fn from(value: WriteError) -> Self {
Self::Write(value)
}
}
impl From<TranscodeError> for DimseError {
fn from(value: TranscodeError) -> Self {
Self::Transcode(value)
}
}
impl From<DicomJsonError> for DimseError {
fn from(value: DicomJsonError) -> Self {
Self::Json(value)
}
}
impl From<std::io::Error> for DimseError {
fn from(value: std::io::Error) -> Self {
Self::Io(value)
}
}
pub trait DimseLogger: Send + Sync {
fn log(&self, message: String);
}
pub(super) fn log_event(logger: Option<&dyn DimseLogger>, message: impl FnOnce() -> String) {
if let Some(logger) = logger {
logger.log(message());
}
}
pub(super) fn transfer_syntax(uid: &str) -> Result<&'static TransferSyntax, DimseError> {
TransferSyntaxRegistry
.get(uid)
.ok_or_else(|| DimseError::UnknownTransferSyntax(uid.to_owned()))
}
pub(super) fn implicit_vr_le() -> &'static TransferSyntax {
transfer_syntax(uids::IMPLICIT_VR_LITTLE_ENDIAN)
.expect("Implicit VR Little Endian is always registered")
}
fn default_transfer_syntaxes() -> Vec<String> {
vec![
uids::EXPLICIT_VR_LITTLE_ENDIAN.to_owned(),
uids::IMPLICIT_VR_LITTLE_ENDIAN.to_owned(),
]
}
fn establish(
destination: &str,
calling_ae_title: &str,
called_ae_title: Option<&str>,
max_pdu_length: u32,
presentation_contexts: &[(String, Vec<String>)],
timeout: Option<Duration>,
logger: Option<&dyn DimseLogger>,
) -> Result<ClientAssociation<TcpStream>, DimseError> {
log_event(logger, || {
format!(
"opening association to {destination} (calling AE {calling_ae_title:?}, called AE {:?}, max PDU {max_pdu_length}, {} presentation context(s) proposed)",
called_ae_title.unwrap_or("<none>"),
presentation_contexts.len()
)
});
let mut options = ClientAssociationOptions::new()
.calling_ae_title(calling_ae_title.to_owned())
.max_pdu_length(max_pdu_length);
for (abstract_syntax, transfer_syntaxes) in presentation_contexts {
options =
options.with_presentation_context(abstract_syntax.clone(), transfer_syntaxes.clone());
}
if let Some(called_ae_title) = called_ae_title {
options = options.called_ae_title(called_ae_title.to_owned());
}
if let Some(timeout) = timeout {
options = options
.read_timeout(timeout)
.write_timeout(timeout)
.connection_timeout(timeout);
}
match options.establish_with(destination) {
Ok(assoc) => {
log_event(logger, || {
let negotiated = assoc
.presentation_contexts()
.iter()
.map(|pc| format!("#{} {} / {}", pc.id, pc.abstract_syntax, pc.transfer_syntax))
.collect::<Vec<_>>()
.join(", ");
format!(
"association established; negotiated presentation context(s): [{negotiated}]"
)
});
Ok(assoc)
}
Err(error) => {
log_event(logger, || format!("association failed: {error}"));
Err(error.into())
}
}
}
fn send_command(
assoc: &mut ClientAssociation<TcpStream>,
pc_id: u8,
command: &InMemDicomObject,
) -> Result<(), DimseError> {
let mut data = Vec::with_capacity(128);
command.write_dataset_with_ts(&mut data, implicit_vr_le())?;
assoc.send(&Pdu::PData {
data: vec![PDataValue {
presentation_context_id: pc_id,
value_type: PDataValueType::Command,
is_last: true,
data,
}],
})?;
Ok(())
}
fn send_command_with_data(
assoc: &mut ClientAssociation<TcpStream>,
pc_id: u8,
command: &InMemDicomObject,
data: Vec<u8>,
) -> Result<(), DimseError> {
let mut command_data = Vec::with_capacity(128);
command.write_dataset_with_ts(&mut command_data, implicit_vr_le())?;
let combined_len = command_data.len() + data.len();
if combined_len < assoc.acceptor_max_pdu_length().saturating_sub(100) as usize {
assoc.send(&Pdu::PData {
data: vec![
PDataValue {
presentation_context_id: pc_id,
value_type: PDataValueType::Command,
is_last: true,
data: command_data,
},
PDataValue {
presentation_context_id: pc_id,
value_type: PDataValueType::Data,
is_last: true,
data,
},
],
})?;
} else {
assoc.send(&Pdu::PData {
data: vec![PDataValue {
presentation_context_id: pc_id,
value_type: PDataValueType::Command,
is_last: true,
data: command_data,
}],
})?;
let mut writer = assoc.send_pdata(pc_id);
std::io::Write::write_all(&mut writer, &data)?;
writer.finish()?;
}
Ok(())
}
fn receive_command(
assoc: &mut ClientAssociation<TcpStream>,
) -> Result<InMemDicomObject, DimseError> {
match assoc.receive_command()? {
Incoming::Command { data, .. } => Ok(InMemDicomObject::read_dataset_with_ts(
data.as_slice(),
implicit_vr_le(),
)?),
Incoming::Pdu(other) => Err(DimseError::Protocol(format!(
"unexpected response PDU: {other:?}"
))),
}
}
fn read_pdata_to_end(assoc: &mut ClientAssociation<TcpStream>) -> Result<Vec<u8>, DimseError> {
Ok(assoc.receive_data_set()?)
}
fn release_and_log(
assoc: ClientAssociation<TcpStream>,
logger: Option<&dyn DimseLogger>,
on_success: impl FnOnce() -> String,
) {
match assoc.release() {
Ok(()) => log_event(logger, on_success),
Err(error) => log_event(logger, || {
format!(
"association release failed (peer did not send a clean A-RELEASE-RP), but the \
operation's own result was already determined and is not affected by this: {}",
DimseError::from(error)
)
}),
}
}
const POLL_INTERVAL: Duration = Duration::from_millis(500);
fn is_read_timeout(error: &DimseError) -> bool {
let mut current: &(dyn StdError + 'static) = error;
loop {
if let Some(io_error) = current.downcast_ref::<std::io::Error>() {
return matches!(
io_error.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
);
}
match current.source() {
Some(source) => current = source,
None => return false,
}
}
}
struct StaleDataWatch {
path: PathBuf,
stale_after: Duration,
last_progress_at: Instant,
last_mtime: Option<std::time::SystemTime>,
}
impl StaleDataWatch {
fn new(path: PathBuf, stale_after: Duration) -> Self {
Self {
path,
stale_after,
last_progress_at: Instant::now(),
last_mtime: None,
}
}
fn newest_mtime(&self) -> Option<std::time::SystemTime> {
std::fs::read_dir(&self.path)
.ok()?
.filter_map(|entry| entry.ok()?.metadata().ok()?.modified().ok())
.max()
}
fn check(&mut self) -> Result<(), DimseError> {
let newest = self.newest_mtime();
if newest.is_some() && newest != self.last_mtime {
self.last_mtime = newest;
self.last_progress_at = Instant::now();
}
if self.last_progress_at.elapsed() >= self.stale_after {
return Err(DimseError::StaleDataConnection {
path: self.path.clone(),
});
}
Ok(())
}
}
fn poll_bounded<T>(
assoc: &mut ClientAssociation<TcpStream>,
deadline: Option<Instant>,
mut stale_watch: Option<&mut StaleDataWatch>,
cancel: Option<&CancelSignal>,
mut op: impl FnMut(&mut ClientAssociation<TcpStream>) -> Result<T, DimseError>,
) -> Result<T, DimseError> {
loop {
if let Some(deadline) = deadline {
if Instant::now() >= deadline {
return Err(DimseError::AbsoluteTimeout);
}
}
if let Some(watch) = stale_watch.as_mut() {
watch.check()?;
}
if let Some(cancel) = cancel {
if let Some(mode) = cancel.requested() {
return Err(DimseError::Cancelled(mode));
}
}
let tick = match deadline {
Some(deadline) => POLL_INTERVAL
.min(deadline.saturating_duration_since(Instant::now()))
.max(Duration::from_millis(1)),
None => POLL_INTERVAL,
};
assoc
.inner_stream()
.set_read_timeout(Some(tick))
.map_err(DimseError::Io)?;
match op(assoc) {
Ok(value) => return Ok(value),
Err(error) if is_read_timeout(&error) => continue,
Err(error) => return Err(error),
}
}
}
fn command_status(command: &InMemDicomObject) -> Result<u16, DimseError> {
command
.element(tags::STATUS)
.map_err(|error| DimseError::Protocol(format!("response is missing Status: {error}")))?
.to_int::<u16>()
.map_err(|error| DimseError::Protocol(format!("Status is not a valid integer: {error}")))
}
fn command_u16(command: &InMemDicomObject, tag: dcmnorm_core::Tag) -> u16 {
command
.element(tag)
.ok()
.and_then(|element| element.to_int::<u16>().ok())
.unwrap_or(0)
}
fn command_has_dataset(command: &InMemDicomObject) -> bool {
command
.element(tags::COMMAND_DATA_SET_TYPE)
.ok()
.and_then(|element| element.to_int::<u16>().ok())
.is_some_and(|value| value != 0x0101)
}
fn is_pending_status(status: u16) -> bool {
status == 0xFF00 || status == 0xFF01
}
pub struct EchoScuOptions {
pub calling_ae_title: String,
pub called_ae_title: Option<String>,
pub timeout: Option<Duration>,
pub on_log: Option<Box<dyn DimseLogger>>,
pub cancel: Option<Arc<CancelSignal>>,
}
pub fn echo_scu(destination: &str, options: EchoScuOptions) -> Result<u16, DimseError> {
let logger = options.on_log.as_deref();
let deadline = options.timeout.map(|timeout| Instant::now() + timeout);
let cancel = options.cancel.as_deref();
let mut assoc = establish(
destination,
&options.calling_ae_title,
options.called_ae_title.as_deref(),
dcmnorm_dimse::pdu::DEFAULT_MAX_PDU,
&[(uids::VERIFICATION.to_owned(), default_transfer_syntaxes())],
options.timeout,
logger,
)?;
let pc = assoc
.presentation_contexts()
.first()
.cloned()
.ok_or(DimseError::NoAcceptedPresentationContext)?;
let command = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, uids::VERIFICATION),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0030])),
DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [1])),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
]);
log_event(logger, || "sending C-ECHO-RQ (message id 1)".to_owned());
let result = send_command(&mut assoc, pc.id, &command)
.and_then(|_| poll_bounded(&mut assoc, deadline, None, cancel, receive_command));
let response = match result {
Ok(response) => response,
Err(error) => {
log_event(logger, || {
format!("aborting association after error: {error}")
});
let _ = assoc.abort();
return Err(error);
}
};
let status = command_status(&response)?;
log_event(logger, || {
format!("received C-ECHO-RSP: status=0x{status:04X}")
});
release_and_log(assoc, logger, || "association released".to_owned());
Ok(status)
}
pub struct StoreScuOptions {
pub calling_ae_title: String,
pub called_ae_title: Option<String>,
pub max_pdu_length: u32,
pub never_transcode: bool,
pub timeout: Option<Duration>,
pub on_log: Option<Box<dyn DimseLogger>>,
pub cancel: Option<Arc<CancelSignal>>,
}
#[derive(Clone, Debug)]
pub struct StoreScuResult {
pub sop_instance_uid: String,
pub status: u16,
}
struct StoreFile {
path: PathBuf,
sop_class_uid: String,
sop_instance_uid: String,
transfer_syntax_uid: String,
raw_part10_passthrough_ok: bool,
}
fn store_file_from_object(
path: &Path,
object: &dcmnorm_object::DefaultDicomObject,
raw_part10_passthrough_ok: bool,
) -> StoreFile {
let meta = object.meta();
let dataset_uid = |tag| {
object
.element(tag)
.ok()
.and_then(|e| e.to_str().ok())
.map(|s| s.trim_end_matches(['\0', ' ']).to_owned())
.filter(|s| !s.is_empty())
};
let sop_class_uid = dataset_uid(tags::SOP_CLASS_UID).unwrap_or_else(|| {
meta.media_storage_sop_class_uid
.trim_end_matches(['\0', ' '])
.to_owned()
});
let sop_instance_uid = dataset_uid(tags::SOP_INSTANCE_UID).unwrap_or_else(|| {
meta.media_storage_sop_instance_uid
.trim_end_matches(['\0', ' '])
.to_owned()
});
let transfer_syntax_uid = meta
.transfer_syntax
.trim_end_matches(['\0', ' '])
.to_owned();
StoreFile {
path: path.to_owned(),
sop_class_uid,
sop_instance_uid,
transfer_syntax_uid,
raw_part10_passthrough_ok,
}
}
fn probe_store_file(path: &Path) -> Result<StoreFile, DimseError> {
if let Ok(object) = OpenFileOptions::new()
.read_preamble(ReadPreamble::Always)
.read_until(dcmnorm_core::Tag(0x0008, 0x0019))
.open_file(path)
{
return Ok(store_file_from_object(path, &object, true));
}
let object = read_dicom_file(path)?;
Ok(store_file_from_object(path, &object, false))
}
pub fn store_scu(
destination: &str,
files: &[PathBuf],
options: StoreScuOptions,
) -> Result<Vec<StoreScuResult>, DimseError> {
let logger = options.on_log.as_deref();
let deadline = options.timeout.map(|timeout| Instant::now() + timeout);
let cancel = options.cancel.as_deref();
let probed: Vec<StoreFile> = files
.iter()
.filter_map(|path| probe_store_file(path).ok())
.collect();
if probed.is_empty() {
return Err(DimseError::NoFilesToSend);
}
let mut presentation_contexts: Vec<(String, Vec<String>)> = Vec::new();
let mut seen_pairs = std::collections::HashSet::new();
let mut native_by_sop_class: HashMap<&str, std::collections::HashSet<&str>> = HashMap::new();
for file in &probed {
if seen_pairs.insert((
file.sop_class_uid.as_str(),
file.transfer_syntax_uid.as_str(),
)) {
presentation_contexts.push((
file.sop_class_uid.clone(),
vec![file.transfer_syntax_uid.clone()],
));
}
native_by_sop_class
.entry(file.sop_class_uid.as_str())
.or_default()
.insert(file.transfer_syntax_uid.as_str());
}
if !options.never_transcode {
for (sop_class_uid, native_transfer_syntaxes) in &native_by_sop_class {
let fallback: Vec<String> = default_transfer_syntaxes()
.into_iter()
.filter(|ts| !native_transfer_syntaxes.contains(ts.as_str()))
.collect();
if !fallback.is_empty() {
presentation_contexts.push(((*sop_class_uid).to_owned(), fallback));
}
}
}
let mut assoc = establish(
destination,
&options.calling_ae_title,
options.called_ae_title.as_deref(),
options.max_pdu_length,
&presentation_contexts,
options.timeout,
logger,
)?;
let negotiated = assoc.presentation_contexts().to_vec();
let mut results = Vec::with_capacity(probed.len());
for (index, file) in probed.iter().enumerate() {
let message_id = (index + 1) as u16;
match send_and_receive_store(
&mut assoc,
file,
&negotiated,
message_id,
deadline,
cancel,
logger,
) {
Ok(status) => results.push(StoreScuResult {
sop_instance_uid: file.sop_instance_uid.clone(),
status,
}),
Err(error) => {
log_event(logger, || {
format!(
"aborting association after error on {}: {error}",
file.sop_instance_uid
)
});
let _ = assoc.abort();
return Err(error);
}
}
}
release_and_log(assoc, logger, || {
format!("association released ({} instance(s) sent)", results.len())
});
Ok(results)
}
fn select_store_presentation_context<'a>(
file: &StoreFile,
negotiated: &'a [PresentationContextNegotiated],
) -> Result<(&'a PresentationContextNegotiated, &'static TransferSyntax), DimseError> {
let exact = negotiated.iter().find(|pc| {
pc.abstract_syntax == file.sop_class_uid && pc.transfer_syntax == file.transfer_syntax_uid
});
if let Some(pc) = exact {
return Ok((pc, transfer_syntax(&pc.transfer_syntax)?));
}
let fallback = negotiated
.iter()
.filter(|pc| pc.abstract_syntax == file.sop_class_uid)
.find(|pc| can_encode_transfer_syntax(&pc.transfer_syntax));
match fallback {
Some(pc) => Ok((pc, transfer_syntax(&pc.transfer_syntax)?)),
None => Err(DimseError::NoAcceptablePresentationContext {
sop_class_uid: file.sop_class_uid.clone(),
transfer_syntax_uid: file.transfer_syntax_uid.clone(),
}),
}
}
fn check_send_limits(
deadline: Option<Instant>,
cancel: Option<&CancelSignal>,
) -> Result<(), DimseError> {
if let Some(deadline) = deadline {
if Instant::now() >= deadline {
return Err(DimseError::AbsoluteTimeout);
}
}
if let Some(cancel) = cancel {
if let Some(mode) = cancel.requested() {
return Err(DimseError::Cancelled(mode));
}
}
Ok(())
}
struct BoundedSendWriter<'a, W> {
inner: &'a mut W,
deadline: Option<Instant>,
cancel: Option<&'a CancelSignal>,
interrupted: Option<DimseError>,
}
impl<'a, W: std::io::Write> BoundedSendWriter<'a, W> {
fn new(inner: &'a mut W, deadline: Option<Instant>, cancel: Option<&'a CancelSignal>) -> Self {
Self {
inner,
deadline,
cancel,
interrupted: None,
}
}
fn take_interrupted(&mut self) -> Option<DimseError> {
self.interrupted.take()
}
}
impl<W: std::io::Write> std::io::Write for BoundedSendWriter<'_, W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if let Err(err) = check_send_limits(self.deadline, self.cancel) {
let msg = err.to_string();
self.interrupted = Some(err);
return Err(std::io::Error::other(msg));
}
self.inner.write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
if let Err(err) = check_send_limits(self.deadline, self.cancel) {
let msg = err.to_string();
self.interrupted = Some(err);
return Err(std::io::Error::other(msg));
}
self.inner.flush()
}
}
fn verify_store_object_matches_probed(
object: &dcmnorm_object::DefaultDicomObject,
expected: &StoreFile,
) -> Result<(), DimseError> {
let actual = store_file_from_object(&expected.path, object, expected.raw_part10_passthrough_ok);
if actual.sop_class_uid != expected.sop_class_uid
|| actual.sop_instance_uid != expected.sop_instance_uid
|| actual.transfer_syntax_uid != expected.transfer_syntax_uid
{
return Err(DimseError::Io(std::io::Error::other(format!(
"file {} changed after probing before C-STORE send (expected SOP class/instance/TS {}/{}/{}, found {}/{}/{})",
expected.path.display(),
expected.sop_class_uid,
expected.sop_instance_uid,
expected.transfer_syntax_uid,
actual.sop_class_uid,
actual.sop_instance_uid,
actual.transfer_syntax_uid,
))));
}
Ok(())
}
fn send_and_receive_store(
assoc: &mut ClientAssociation<TcpStream>,
file: &StoreFile,
negotiated: &[PresentationContextNegotiated],
message_id: u16,
deadline: Option<Instant>,
cancel: Option<&CancelSignal>,
logger: Option<&dyn DimseLogger>,
) -> Result<u16, DimseError> {
use std::io::{Read, Seek, SeekFrom};
let (pc, target_ts) = select_store_presentation_context(file, negotiated)?;
let command = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, &file.sop_class_uid),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0001])),
DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [message_id])),
DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0x0000])),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0000]),
),
DataElement::new(
tags::AFFECTED_SOP_INSTANCE_UID,
VR::UI,
dicom_value!(Str, &file.sop_instance_uid),
),
]);
log_event(logger, || {
format!(
"sending C-STORE-RQ #{message_id}: SOP instance {} (class {}, transfer syntax {})",
file.sop_instance_uid,
file.sop_class_uid,
target_ts.uid()
)
});
check_send_limits(deadline, cancel)?;
if target_ts.uid() == file.transfer_syntax_uid && file.raw_part10_passthrough_ok {
let mut raw_file = std::fs::File::open(&file.path)?;
let file_len = raw_file.metadata()?.len();
let validated = OpenFileOptions::new()
.read_preamble(ReadPreamble::Always)
.from_reader_deferring(
std::io::BufReader::new(&mut raw_file),
Some(file_len),
&|h| {
h.tag != tags::SOP_CLASS_UID
&& h.tag != tags::SOP_INSTANCE_UID
&& h.tag != tags::SPECIFIC_CHARACTER_SET
},
true,
false,
)
.map_err(|e| {
DimseError::Io(std::io::Error::other(format!(
"validating {} before C-STORE send: {e}",
file.path.display()
)))
})?;
let Some((validated_obj, _)) = validated else {
raw_file.seek(SeekFrom::Start(0))?;
let object = OpenFileOptions::new()
.read_preamble(ReadPreamble::Always)
.from_reader(std::io::BufReader::new(&mut raw_file))
.map_err(|e| {
DimseError::Io(std::io::Error::other(format!(
"validating {} before C-STORE send: {e}",
file.path.display()
)))
})?;
verify_store_object_matches_probed(&object, file)?;
check_send_limits(deadline, cancel)?;
send_command(assoc, pc.id, &command)?;
let mut writer = assoc.send_pdata(pc.id);
let mut bounded = BoundedSendWriter::new(&mut writer, deadline, cancel);
if let Err(err) = object.write_dataset_with_ts(&mut bounded, target_ts) {
if let Some(interrupted) = bounded.take_interrupted() {
return Err(interrupted);
}
return Err(err.into());
}
writer.finish()?;
let response = poll_bounded(assoc, deadline, None, cancel, receive_command)?;
let status = command_status(&response)?;
log_event(logger, || {
format!("received C-STORE-RSP #{message_id}: status=0x{status:04X}")
});
return Ok(status);
};
verify_store_object_matches_probed(&validated_obj, file)?;
raw_file.seek(SeekFrom::Start(0))?;
let mut buf_reader = std::io::BufReader::new(raw_file);
let Some(_meta) = FileMetaTable::read_from(&mut buf_reader)? else {
return Err(DimseError::Io(std::io::Error::other(format!(
"file {} lost Part 10 File Meta Information before C-STORE send",
file.path.display()
))));
};
let dataset_offset = buf_reader.stream_position()?;
let dataset_len = file_len.saturating_sub(dataset_offset);
let mut raw_file = buf_reader.into_inner();
raw_file.seek(SeekFrom::Start(dataset_offset))?;
check_send_limits(deadline, cancel)?;
let single_pdu_limit = assoc
.acceptor_max_pdu_length()
.min(65_536)
.saturating_sub(256) as u64;
if dataset_len < single_pdu_limit {
let mut data = Vec::with_capacity(dataset_len as usize);
raw_file.by_ref().take(dataset_len).read_to_end(&mut data)?;
if data.len() as u64 != dataset_len {
return Err(DimseError::Io(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
format!(
"file {} shrank before C-STORE send (expected {dataset_len} dataset bytes, read {})",
file.path.display(),
data.len()
),
)));
}
send_command_with_data(assoc, pc.id, &command, data)?;
} else {
send_command(assoc, pc.id, &command)?;
let mut writer = assoc.send_pdata(pc.id);
let mut bounded = BoundedSendWriter::new(&mut writer, deadline, cancel);
let copied = match std::io::copy(&mut raw_file.by_ref().take(dataset_len), &mut bounded)
{
Ok(n) => n,
Err(err) => {
if let Some(interrupted) = bounded.take_interrupted() {
return Err(interrupted);
}
return Err(err.into());
}
};
if copied != dataset_len {
return Err(DimseError::Io(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
format!(
"file {} shrank during C-STORE send (expected {dataset_len} dataset bytes, sent {copied})",
file.path.display()
),
)));
}
writer.finish()?;
}
} else if target_ts.uid() == file.transfer_syntax_uid {
let object = read_dicom_file(&file.path)?;
verify_store_object_matches_probed(&object, file)?;
check_send_limits(deadline, cancel)?;
send_command(assoc, pc.id, &command)?;
let mut writer = assoc.send_pdata(pc.id);
let mut bounded = BoundedSendWriter::new(&mut writer, deadline, cancel);
if let Err(err) = object.write_dataset_with_ts(&mut bounded, target_ts) {
if let Some(interrupted) = bounded.take_interrupted() {
return Err(interrupted);
}
return Err(err.into());
}
writer.finish()?;
} else if let Some(prepared) = prepare_streaming_dataset_for_dimse(&file.path, target_ts.uid())?
{
verify_store_object_matches_probed(prepared.object(), file)?;
check_send_limits(deadline, cancel)?;
send_command(assoc, pc.id, &command)?;
let mut writer = assoc.send_pdata(pc.id);
let mut bounded = BoundedSendWriter::new(&mut writer, deadline, cancel);
if let Err(err) = prepared.write_to(&mut bounded) {
if let Some(interrupted) = bounded.take_interrupted() {
return Err(interrupted);
}
return Err(err.into());
}
writer.finish()?;
} else {
let object = read_dicom_file(&file.path)?;
verify_store_object_matches_probed(&object, file)?;
let object = transcode_dcmnorm_object_owned(object, target_ts.uid())?;
check_send_limits(deadline, cancel)?;
send_command(assoc, pc.id, &command)?;
let mut writer = assoc.send_pdata(pc.id);
let mut bounded = BoundedSendWriter::new(&mut writer, deadline, cancel);
if let Err(err) = object.write_dataset_with_ts(&mut bounded, target_ts) {
if let Some(interrupted) = bounded.take_interrupted() {
return Err(interrupted);
}
return Err(err.into());
}
writer.finish()?;
}
let response = poll_bounded(assoc, deadline, None, cancel, receive_command)?;
let status = command_status(&response)?;
log_event(logger, || {
format!("received C-STORE-RSP #{message_id}: status=0x{status:04X}")
});
Ok(status)
}
pub struct FindScuOptions {
pub calling_ae_title: String,
pub called_ae_title: Option<String>,
pub max_pdu_length: u32,
pub timeout: Option<Duration>,
pub on_log: Option<Box<dyn DimseLogger>>,
pub cancel: Option<Arc<CancelSignal>>,
}
fn put_query_attribute(
identifier: &mut InMemDicomObject,
key: &str,
value: &str,
) -> Result<(), DimseError> {
let tag = StandardDataDictionary
.parse_tag(key)
.ok_or_else(|| DimseError::InvalidQueryKey(key.to_owned()))?;
let vr = StandardDataDictionary
.by_tag(tag)
.map(|entry| entry.vr().relaxed())
.ok_or_else(|| DimseError::InvalidQueryKey(key.to_owned()))?;
identifier.put_str(tag, vr, value.to_owned());
Ok(())
}
fn build_identifier(query: &HashMap<String, String>) -> Result<InMemDicomObject, DimseError> {
let mut identifier = InMemDicomObject::new_empty();
for (key, value) in query {
put_query_attribute(&mut identifier, key, value)?;
}
if identifier.element(tags::QUERY_RETRIEVE_LEVEL).is_err() {
put_query_attribute(&mut identifier, "QueryRetrieveLevel", "STUDY")?;
}
Ok(identifier)
}
pub fn find_scu(
destination: &str,
query: &HashMap<String, String>,
options: FindScuOptions,
) -> Result<Vec<String>, DimseError> {
let logger = options.on_log.as_deref();
let deadline = options.timeout.map(|timeout| Instant::now() + timeout);
let cancel = options.cancel.as_deref();
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND;
let mut assoc = establish(
destination,
&options.calling_ae_title,
options.called_ae_title.as_deref(),
options.max_pdu_length,
&[(abstract_syntax.to_owned(), default_transfer_syntaxes())],
options.timeout,
logger,
)?;
let pc = assoc
.presentation_contexts()
.first()
.cloned()
.ok_or(DimseError::NoAcceptedPresentationContext)?;
let ts = transfer_syntax(&pc.transfer_syntax)?;
let identifier = build_identifier(query)?;
let mut identifier_data = Vec::with_capacity(128);
identifier.write_dataset_with_ts(&mut identifier_data, ts)?;
let command = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0020])),
DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [1])),
DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0x0000])),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0001]),
),
]);
log_event(logger, || {
let mut keys: Vec<&str> = query.keys().map(String::as_str).collect();
keys.sort_unstable();
format!(
"sending C-FIND-RQ (message id 1); query key(s): [{}]",
keys.join(", ")
)
});
if let Err(error) = send_command_with_data(&mut assoc, pc.id, &command, identifier_data) {
log_event(logger, || {
format!("aborting association after error: {error}")
});
let _ = assoc.abort();
return Err(error);
}
let mut matches = Vec::new();
loop {
let response = match poll_bounded(&mut assoc, deadline, None, cancel, receive_command) {
Ok(response) => response,
Err(error) => {
log_event(logger, || {
format!("aborting association after error: {error}")
});
let _ = assoc.abort();
return Err(error);
}
};
let status = match command_status(&response) {
Ok(status) => status,
Err(error) => {
log_event(logger, || {
format!("aborting association after error: {error}")
});
let _ = assoc.abort();
return Err(error);
}
};
log_event(logger, || {
format!("received C-FIND-RSP: status=0x{status:04X}")
});
if status == 0x0000 {
break;
}
if !is_pending_status(status) {
log_event(logger, || {
format!("aborting association: C-FIND-RSP failed with status 0x{status:04X}")
});
let _ = assoc.abort();
return Err(DimseError::Protocol(format!(
"C-FIND-RSP failed with status {status:#06X}"
)));
}
let bytes = match poll_bounded(&mut assoc, deadline, None, cancel, read_pdata_to_end) {
Ok(bytes) => bytes,
Err(error) => {
log_event(logger, || {
format!("aborting association after error: {error}")
});
let _ = assoc.abort();
return Err(error);
}
};
let matched = InMemDicomObject::read_dataset_with_ts(bytes.as_slice(), ts)?;
let json = write_dataset_as_dicom_json_with_options(
matched,
ts.uid(),
DicomJsonWriteOptions {
key_style: DicomJsonKeyStyle::Hex,
format: DicomJsonFormat::Flat,
..Default::default()
},
)?;
matches.push(json);
}
release_and_log(assoc, logger, || {
format!("association released ({} match(es))", matches.len())
});
Ok(matches)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum QueryRetrieveLevel {
#[default]
Study,
Series,
Image,
}
impl QueryRetrieveLevel {
pub fn as_str(self) -> &'static str {
match self {
Self::Study => "STUDY",
Self::Series => "SERIES",
Self::Image => "IMAGE",
}
}
}
impl fmt::Display for QueryRetrieveLevel {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl std::str::FromStr for QueryRetrieveLevel {
type Err = DimseError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.trim().to_ascii_uppercase().as_str() {
"STUDY" => Ok(Self::Study),
"SERIES" => Ok(Self::Series),
"IMAGE" => Ok(Self::Image),
_ => Err(DimseError::InvalidMoveIdentifier(format!(
"unknown QueryRetrieveLevel '{value}' (expected STUDY, SERIES or IMAGE)"
))),
}
}
}
pub struct MoveScuOptions {
pub calling_ae_title: String,
pub called_ae_title: Option<String>,
pub max_pdu_length: u32,
pub timeout: Option<Duration>,
pub stale_data_path: Option<PathBuf>,
pub stale_data_timeout: Option<Duration>,
pub on_log: Option<Box<dyn DimseLogger>>,
pub cancel: Option<Arc<CancelSignal>>,
pub query_retrieve_level: Option<QueryRetrieveLevel>,
pub series_instance_uid: Option<String>,
pub sop_instance_uids: Vec<String>,
}
fn check_retrieve_uid(key: &str, uid: &str) -> Result<(), DimseError> {
let well_formed = !uid.is_empty()
&& uid.len() <= 64
&& uid
.bytes()
.all(|byte| byte.is_ascii_digit() || byte == b'.');
if well_formed {
Ok(())
} else {
Err(DimseError::InvalidMoveIdentifier(format!(
"{key} '{uid}' is not a valid UID"
)))
}
}
pub(super) fn build_move_identifier(
study_instance_uid: &str,
level: QueryRetrieveLevel,
series_instance_uid: Option<&str>,
sop_instance_uids: &[String],
) -> Result<InMemDicomObject, DimseError> {
let mut identifier = InMemDicomObject::new_empty();
put_query_attribute(&mut identifier, "QueryRetrieveLevel", level.as_str())?;
put_query_attribute(&mut identifier, "StudyInstanceUID", study_instance_uid)?;
if level == QueryRetrieveLevel::Study {
return Ok(identifier);
}
check_retrieve_uid("StudyInstanceUID", study_instance_uid)?;
let series_instance_uid = series_instance_uid
.filter(|uid| !uid.is_empty())
.ok_or_else(|| {
DimseError::InvalidMoveIdentifier(format!(
"a {level}-level retrieve needs a SeriesInstanceUID"
))
})?;
check_retrieve_uid("SeriesInstanceUID", series_instance_uid)?;
put_query_attribute(&mut identifier, "SeriesInstanceUID", series_instance_uid)?;
if level == QueryRetrieveLevel::Series {
return Ok(identifier);
}
if sop_instance_uids.is_empty() {
return Err(DimseError::InvalidMoveIdentifier(
"an IMAGE-level retrieve needs at least one SOPInstanceUID".to_owned(),
));
}
for uid in sop_instance_uids {
check_retrieve_uid("SOPInstanceUID", uid)?;
}
identifier.put(DataElement::new(
tags::SOP_INSTANCE_UID,
VR::UI,
PrimitiveValue::Strs(sop_instance_uids.iter().cloned().collect()),
));
Ok(identifier)
}
#[derive(Clone, Debug, Default)]
pub struct MoveScuResult {
pub status: u16,
pub completed: u16,
pub failed: u16,
pub warning: u16,
pub remaining: u16,
pub cancelled: bool,
pub cancelled_via: Option<CancelMode>,
}
fn handle_move_cancelled(
assoc: ClientAssociation<TcpStream>,
logger: Option<&dyn DimseLogger>,
mode: CancelMode,
last_result: MoveScuResult,
) -> MoveScuResult {
match mode {
CancelMode::Release => {
log_event(logger, || {
"cancelled by caller - releasing association".to_owned()
});
release_and_log(assoc, logger, || {
"association released after cancellation".to_owned()
});
}
CancelMode::Abort => {
log_event(logger, || {
"cancelled by caller - aborting association".to_owned()
});
let _ = assoc.abort();
}
}
MoveScuResult {
cancelled: true,
cancelled_via: Some(mode),
status: 0,
..last_result
}
}
pub fn move_scu(
destination: &str,
move_destination_ae: &str,
study_instance_uid: &str,
options: MoveScuOptions,
) -> Result<MoveScuResult, DimseError> {
let level = options.query_retrieve_level.unwrap_or_default();
let identifier = build_move_identifier(
study_instance_uid,
level,
options.series_instance_uid.as_deref(),
&options.sop_instance_uids,
)?;
let logger = options.on_log.as_deref();
let deadline = options.timeout.map(|timeout| Instant::now() + timeout);
let mut stale_watch = match (options.stale_data_path, options.stale_data_timeout) {
(Some(path), Some(stale_after)) => Some(StaleDataWatch::new(path, stale_after)),
_ => None,
};
let cancel = options.cancel.as_deref();
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_MOVE;
let mut assoc = establish(
destination,
&options.calling_ae_title,
options.called_ae_title.as_deref(),
options.max_pdu_length,
&[(abstract_syntax.to_owned(), default_transfer_syntaxes())],
options.timeout,
logger,
)?;
let pc = assoc
.presentation_contexts()
.first()
.cloned()
.ok_or(DimseError::NoAcceptedPresentationContext)?;
let ts = transfer_syntax(&pc.transfer_syntax)?;
let mut identifier_data = Vec::with_capacity(128);
identifier.write_dataset_with_ts(&mut identifier_data, ts)?;
let command = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0021])),
DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [1])),
DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0x0000])),
DataElement::new(
tags::MOVE_DESTINATION,
VR::AE,
dicom_value!(Str, move_destination_ae),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0001]),
),
]);
log_event(logger, || {
match level {
QueryRetrieveLevel::Study => {
format!("sending C-MOVE-RQ: study {study_instance_uid} -> move destination AE {move_destination_ae}")
}
QueryRetrieveLevel::Series => format!(
"sending C-MOVE-RQ: study {study_instance_uid} series {} -> move destination AE {move_destination_ae}",
options.series_instance_uid.as_deref().unwrap_or_default()
),
QueryRetrieveLevel::Image => format!(
"sending C-MOVE-RQ: study {study_instance_uid} series {} ({} instance(s)) -> move destination AE {move_destination_ae}",
options.series_instance_uid.as_deref().unwrap_or_default(),
options.sop_instance_uids.len()
),
}
});
if let Err(error) = send_command_with_data(&mut assoc, pc.id, &command, identifier_data) {
log_event(logger, || {
format!("aborting association after error: {error}")
});
let _ = assoc.abort();
return Err(error);
}
let mut last_result = MoveScuResult::default();
loop {
let response = match poll_bounded(
&mut assoc,
deadline,
stale_watch.as_mut(),
cancel,
receive_command,
) {
Ok(response) => response,
Err(DimseError::Cancelled(mode)) => {
return Ok(handle_move_cancelled(assoc, logger, mode, last_result));
}
Err(error) => {
log_event(logger, || {
format!("aborting association after error: {error}")
});
let _ = assoc.abort();
return Err(error);
}
};
let status = match command_status(&response) {
Ok(status) => status,
Err(error) => {
log_event(logger, || {
format!("aborting association after error: {error}")
});
let _ = assoc.abort();
return Err(error);
}
};
if command_has_dataset(&response) {
match poll_bounded(
&mut assoc,
deadline,
stale_watch.as_mut(),
cancel,
read_pdata_to_end,
) {
Ok(_) => {}
Err(DimseError::Cancelled(mode)) => {
return Ok(handle_move_cancelled(assoc, logger, mode, last_result));
}
Err(error) => {
log_event(logger, || {
format!("aborting association after error: {error}")
});
let _ = assoc.abort();
return Err(error);
}
}
}
let result = MoveScuResult {
status,
completed: command_u16(&response, tags::NUMBER_OF_COMPLETED_SUBOPERATIONS),
failed: command_u16(&response, tags::NUMBER_OF_FAILED_SUBOPERATIONS),
warning: command_u16(&response, tags::NUMBER_OF_WARNING_SUBOPERATIONS),
remaining: command_u16(&response, tags::NUMBER_OF_REMAINING_SUBOPERATIONS),
cancelled: false,
cancelled_via: None,
};
log_event(logger, || {
format!(
"received C-MOVE-RSP: status=0x{status:04X} completed={} failed={} warning={} remaining={}",
result.completed, result.failed, result.warning, result.remaining
)
});
last_result = result.clone();
if is_pending_status(status) {
continue;
}
release_and_log(assoc, logger, || "association released".to_owned());
return Ok(result);
}
}