dicom-ul 0.9.1

Types and methods for interacting with the DICOM Upper Layer Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#[cfg(feature = "async")]
use dicom_ul::association::AsyncServerAssociation;
use dicom_ul::{
    association::{client::ClientAssociationOptions, server::ServerAssociationOptions, Error},
    pdu::{
        PDataValue, PDataValueType, Pdu, PresentationContextNegotiated,
        PresentationContextResultReason,
    },
    ServerAssociation,
};
use std::io::Write;

#[cfg(feature = "async")]
use tokio::io::AsyncWriteExt;

use std::net::SocketAddr;

// Check rather arbitrary maximum PDU lengths, also different for server and client
const HI_PDU_LEN: usize = 7890;
const LO_PDU_LEN: usize = 5678;
const PDV_HDR_LEN: usize = 6;

type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync + 'static>>;

static SCU_AE_TITLE: &str = "ECHO-SCU";
static SCP_AE_TITLE: &str = "ECHO-SCP";

static IMPLICIT_VR_LE: &str = "1.2.840.10008.1.2";
static EXPLICIT_VR_LE: &str = "1.2.840.10008.1.2.1";
static JPEG_BASELINE: &str = "1.2.840.10008.1.2.4.50";
static VERIFICATION_SOP_CLASS: &str = "1.2.840.10008.1.1";
static DIGITAL_MG_STORAGE_SOP_CLASS: &str = "1.2.840.10008.5.1.4.1.1.1.2";

// Return a PData PDU with one PDV which has a payload of the given length.
// It's a "bogus packet" because the payload is filled with zeros instead of
// being a valid DICOM object.
fn bogus_packet(len: usize) -> Pdu {
    Pdu::PData {
        data: vec![PDataValue {
            presentation_context_id: 1,
            value_type: PDataValueType::Command,
            is_last: true,
            data: vec![0_u8; len],
        }],
    }
}

fn spawn_scp(
    max_server_pdu_len: usize,
    max_client_pdu_len: usize,
) -> Result<(
    std::thread::JoinHandle<Result<ServerAssociation<std::net::TcpStream>>>,
    SocketAddr,
)> {
    let listener = std::net::TcpListener::bind("localhost:0")?;
    let addr = listener.local_addr()?;
    let scp = ServerAssociationOptions::new()
        .accept_called_ae_title()
        .ae_title(SCP_AE_TITLE)
        .max_pdu_length(max_server_pdu_len as u32)
        .with_abstract_syntax(VERIFICATION_SOP_CLASS);

    let h = std::thread::spawn(move || -> Result<_> {
        let (stream, _addr) = listener.accept()?;
        let mut association = scp.establish(stream)?;

        assert_eq!(
            association.presentation_contexts(),
            &[
                PresentationContextNegotiated {
                    id: 1,
                    reason: PresentationContextResultReason::Acceptance,
                    transfer_syntax: IMPLICIT_VR_LE.to_string(),
                    abstract_syntax: VERIFICATION_SOP_CLASS.to_string(),
                },
                PresentationContextNegotiated {
                    id: 3,
                    reason: PresentationContextResultReason::AbstractSyntaxNotSupported,
                    transfer_syntax: IMPLICIT_VR_LE.to_string(),
                    abstract_syntax: DIGITAL_MG_STORAGE_SOP_CLASS.to_string(),
                }
            ],
        );

        assert_eq!(
            association.requestor_max_pdu_length(),
            max_client_pdu_len as u32
        );
        assert_eq!(
            association.acceptor_max_pdu_length(),
            max_server_pdu_len as u32
        );

        // handle one bogus payload
        let pdu = association.receive()?;
        let data = match pdu {
            Pdu::PData { ref data } => data,
            other => panic!("Unexpected packet type: {:?}", other),
        };
        assert_eq!(data.len(), 1);
        assert_eq!(data[0].data.len(), max_server_pdu_len - PDV_HDR_LEN);

        // Create a bogus payload which fills the PDU to the max.
        // Take into account the PDU and PDV header lengths for that purpose.
        let filler_len = max_client_pdu_len - PDV_HDR_LEN;
        let mut packet = bogus_packet(filler_len);

        // send one bogus response
        association.send(&packet).expect("failed sending packet");

        // Add 1 byte to the payload to exceed maximum length
        if let Pdu::PData { ref mut data } = packet {
            data[0].data.push(0);
        }

        match association.send(&packet) {
            Err(Error::SendTooLongPdu { .. }) => (),
            e => panic!("Expected SendTooLongPdu but didn't happen: {:?}", e),
        }

        // Test send_pdata() fragmentation of the client; we should receive two packets
        // First packet
        match association.receive() {
            Ok(Pdu::PData { data }) => {
                assert_eq!(data.len(), 1);
                assert_eq!(data[0].data.len(), max_server_pdu_len - PDV_HDR_LEN);
            }
            Ok(other_pdus) => {
                panic!("Unknown PDU: {:?}", other_pdus);
            }
            Err(err) => {
                panic!("Receive returned error {:?}", err);
            }
        }
        // Second packet
        match association.receive() {
            Ok(Pdu::PData { data }) => {
                assert_eq!(data.len(), 1);
                assert_eq!(data[0].data.len(), 2);
            }
            Ok(other_pdus) => {
                panic!("Unknown PDU: {:?}", other_pdus);
            }
            Err(err) => {
                panic!("Receive returned error {:?}", err);
            }
        }
        // Let the client test our send_pdata() fragmentation for us
        {
            // Send two more bytes than fit in a PDU
            let filler_len = max_client_pdu_len - PDV_HDR_LEN + 2;
            let buf = vec![0_u8; filler_len];
            let mut sender = association.send_pdata(1);
            // This should split the data in two packets
            sender
                .write_all(&buf)
                .expect("Error sending fragmented data");
        }

        // handle one release request
        let pdu = association.receive()?;
        assert_eq!(pdu, Pdu::ReleaseRQ);
        association.send(&Pdu::ReleaseRP)?;

        Ok(association)
    });
    Ok((h, addr))
}

#[cfg(feature = "async")]
async fn spawn_scp_async(
    max_server_pdu_len: usize,
    max_client_pdu_len: usize,
) -> Result<(
    tokio::task::JoinHandle<Result<AsyncServerAssociation<tokio::net::TcpStream>>>,
    SocketAddr,
)> {
    let listener = tokio::net::TcpListener::bind("localhost:0").await?;
    let addr = listener.local_addr()?;
    let scp = ServerAssociationOptions::new()
        .accept_called_ae_title()
        .ae_title(SCP_AE_TITLE)
        .max_pdu_length(max_server_pdu_len as u32)
        .with_abstract_syntax(VERIFICATION_SOP_CLASS);

    let h = tokio::spawn(async move {
        let (stream, _addr) = listener.accept().await?;
        let mut association = scp.establish_async(stream).await?;

        assert_eq!(
            association.presentation_contexts(),
            &[
                PresentationContextNegotiated {
                    id: 1,
                    reason: PresentationContextResultReason::Acceptance,
                    transfer_syntax: IMPLICIT_VR_LE.to_string(),
                    abstract_syntax: VERIFICATION_SOP_CLASS.to_string(),
                },
                PresentationContextNegotiated {
                    id: 3,
                    reason: PresentationContextResultReason::AbstractSyntaxNotSupported,
                    transfer_syntax: IMPLICIT_VR_LE.to_string(),
                    abstract_syntax: DIGITAL_MG_STORAGE_SOP_CLASS.to_string(),
                }
            ],
        );

        assert_eq!(
            association.requestor_max_pdu_length(),
            max_client_pdu_len as u32
        );
        assert_eq!(
            association.acceptor_max_pdu_length(),
            max_server_pdu_len as u32
        );

        // handle one bogus payload
        let pdu = association.receive().await?;
        let data = match pdu {
            Pdu::PData { ref data } => data,
            other => panic!("Unexpected packet type: {:?}", other),
        };
        assert_eq!(data.len(), 1);
        assert_eq!(data[0].data.len(), max_server_pdu_len - PDV_HDR_LEN);

        // Create a bogus payload which fills the PDU to the max.
        // Take into account the PDU and PDV header lengths for that purpose.
        let filler_len = max_client_pdu_len - PDV_HDR_LEN;
        let mut packet = bogus_packet(filler_len);

        // send one bogus response
        association
            .send(&packet)
            .await
            .expect("failed sending packet");

        if let Pdu::PData { ref mut data } = packet {
            // Add 1 byte to the payload to exceed maximum length
            data[0].data.push(0);
        }

        match association.send(&packet).await {
            Err(Error::SendTooLongPdu { .. }) => (),
            e => panic!("Expected SendTooLongPdu but didn't happen: {:?}", e),
        }

        // Test send_pdata() fragmentation of the client; we should receive two packets
        // First packet
        match association.receive().await {
            Ok(Pdu::PData { data }) => {
                assert_eq!(data.len(), 1);
                assert_eq!(data[0].data.len(), max_server_pdu_len - PDV_HDR_LEN);
            }
            Ok(other_pdus) => {
                panic!("Unknown PDU: {:?}", other_pdus);
            }
            Err(err) => {
                panic!("Receive returned error {:?}", err);
            }
        }
        // Second packet
        match association.receive().await {
            Ok(Pdu::PData { data }) => {
                assert_eq!(data.len(), 1);
                assert_eq!(data[0].data.len(), 2);
            }
            Ok(other_pdus) => {
                panic!("Unknown PDU: {:?}", other_pdus);
            }
            Err(err) => {
                panic!("Receive returned error {:?}", err);
            }
        }
        // Let the client test our send_pdata() fragmentation
        {
            // Send two more bytes than fit in a PDU
            let filler_len = max_client_pdu_len - PDV_HDR_LEN + 2;
            let buf = vec![0_u8; filler_len];
            let mut sender = association.send_pdata(1);
            // This should split the data in two packets
            sender
                .write_all(&buf)
                .await
                .expect("Error sending fragmented data");
        }

        // handle one release request
        let pdu = association.receive().await?;
        assert_eq!(pdu, Pdu::ReleaseRQ);
        association.send(&Pdu::ReleaseRP).await?;

        Ok(association)
    });
    Ok((h, addr))
}

/// Run an SCP and an SCU concurrently, negotiate an association and release it.
#[test]
fn scu_scp_association_test() {
    for max_is_client in [false, true] {
        run_scu_scp_association_test(max_is_client);
    }
}

fn run_scu_scp_association_test(max_is_client: bool) {
    let (max_client_pdu_len, max_server_pdu_len) = if max_is_client {
        (HI_PDU_LEN, LO_PDU_LEN)
    } else {
        (LO_PDU_LEN, HI_PDU_LEN)
    };
    let (scp_handle, scp_addr) = spawn_scp(max_server_pdu_len, max_client_pdu_len).unwrap();

    let mut association = ClientAssociationOptions::new()
        .calling_ae_title(SCU_AE_TITLE)
        .called_ae_title(SCP_AE_TITLE)
        .with_presentation_context(VERIFICATION_SOP_CLASS, vec![IMPLICIT_VR_LE, EXPLICIT_VR_LE])
        .with_presentation_context(
            DIGITAL_MG_STORAGE_SOP_CLASS,
            vec![IMPLICIT_VR_LE, EXPLICIT_VR_LE, JPEG_BASELINE],
        )
        .max_pdu_length(max_client_pdu_len as u32)
        .establish(scp_addr)
        .unwrap();

    assert_eq!(
        association.requestor_max_pdu_length(),
        max_client_pdu_len as u32
    );
    assert_eq!(
        association.acceptor_max_pdu_length(),
        max_server_pdu_len as u32
    );

    // Create a bogus payload which fills the PDU to the max.
    // Take into account the PDU and PDV header lengths for that purpose.
    let filler_len = max_server_pdu_len - PDV_HDR_LEN;
    let mut packet = bogus_packet(filler_len);

    association.send(&packet).expect("failed sending packet");

    let pdu = association.receive().expect("can't receive response");
    match pdu {
        Pdu::PData { .. } => (),
        _ => panic!("unexpected response packet type"),
    }

    // Add 1 byte to the payload to exceed maximum length
    if let Pdu::PData { ref mut data } = packet {
        data[0].data.push(0);
    }
    match association.send(&packet) {
        Err(Error::SendTooLongPdu { .. }) => (),
        e => panic!("Expected SendTooLongPdu but didn't happen: {:?}", e),
    }

    // Let the server test our send_pdata() fragmentation for us
    {
        // Send two more bytes than fit in a PDU
        let filler_len = max_server_pdu_len - PDV_HDR_LEN + 2;
        let buf = vec![0_u8; filler_len];
        let mut sender = association.send_pdata(1);
        // This should split the data in two packets
        sender
            .write_all(&buf)
            .expect("Error sending fragmented data");
    }
    // Test send_pdata() fragmentation of the server; we should receive two packets
    // First packet
    match association.receive() {
        Ok(Pdu::PData { data }) => {
            assert_eq!(data.len(), 1);
            assert_eq!(data[0].data.len(), max_client_pdu_len - PDV_HDR_LEN);
        }
        Ok(other_pdus) => {
            panic!("Unknown PDU: {:?}", other_pdus);
        }
        Err(err) => {
            panic!("Receive returned error {:?}", err);
        }
    }
    // Second packet
    match association.receive() {
        Ok(Pdu::PData { data }) => {
            assert_eq!(data.len(), 1);
            assert_eq!(data[0].data.len(), 2);
        }
        Ok(other_pdus) => {
            panic!("Unknown PDU: {:?}", other_pdus);
        }
        Err(err) => {
            panic!("Receive returned error {:?}", err);
        }
    }

    association
        .release()
        .expect("did not have a peaceful release");

    scp_handle
        .join()
        .expect("SCP panicked")
        .expect("Error at the SCP");
}

#[cfg(feature = "async")]
#[tokio::test(flavor = "multi_thread")]
async fn scu_scp_association_test_async() {
    for max_is_client in [false, true] {
        run_scu_scp_association_test_async(max_is_client).await;
    }
}

#[cfg(feature = "async")]
async fn run_scu_scp_association_test_async(max_is_client: bool) {
    let (max_client_pdu_len, max_server_pdu_len) = if max_is_client {
        (HI_PDU_LEN, LO_PDU_LEN)
    } else {
        (LO_PDU_LEN, HI_PDU_LEN)
    };
    let (scp_handle, scp_addr) = spawn_scp_async(max_server_pdu_len, max_client_pdu_len)
        .await
        .unwrap();

    let mut association = ClientAssociationOptions::new()
        .calling_ae_title(SCU_AE_TITLE)
        .called_ae_title(SCP_AE_TITLE)
        .with_presentation_context(VERIFICATION_SOP_CLASS, vec![IMPLICIT_VR_LE, EXPLICIT_VR_LE])
        .with_presentation_context(
            DIGITAL_MG_STORAGE_SOP_CLASS,
            vec![IMPLICIT_VR_LE, EXPLICIT_VR_LE, JPEG_BASELINE],
        )
        .max_pdu_length(max_client_pdu_len as u32)
        .establish_async(scp_addr)
        .await
        .unwrap();

    assert_eq!(
        association.requestor_max_pdu_length(),
        max_client_pdu_len as u32
    );
    assert_eq!(
        association.acceptor_max_pdu_length(),
        max_server_pdu_len as u32
    );

    // Create a bogus payload which fills the PDU to the max.
    // Take into account the PDU and PDV header lengths for that purpose.
    let filler_len = max_server_pdu_len - PDV_HDR_LEN;
    let mut packet = bogus_packet(filler_len);

    association
        .send(&packet)
        .await
        .expect("failed sending packet (async)");

    let pdu = association
        .receive()
        .await
        .expect("can't receive response (async)");
    match pdu {
        Pdu::PData { .. } => (),
        _ => panic!("unexpected response packet type (async)"),
    }

    // Add 1 byte to the payload to exceed maximum length
    if let Pdu::PData { ref mut data } = packet {
        data[0].data.push(0);
    }
    match association.send(&packet).await {
        Err(Error::SendTooLongPdu { .. }) => (),
        e => panic!("Expected SendTooLongPdu but didn't happen (async): {:?}", e),
    }

    // Let the server test our send_pdata() fragmentation for us
    {
        // Send two more bytes than fit in a PDU
        let filler_len = max_server_pdu_len - PDV_HDR_LEN + 2;
        let buf = vec![0_u8; filler_len];
        let mut sender = association.send_pdata(1);
        // This should split the data in two packets
        sender
            .write_all(&buf)
            .await
            .expect("Error sending fragmented data");
    }
    // Test send_pdata() fragmentation of the server; we should receive two packets
    // First packet
    match association.receive().await {
        Ok(Pdu::PData { data }) => {
            assert_eq!(data.len(), 1);
            assert_eq!(data[0].data.len(), max_client_pdu_len - PDV_HDR_LEN);
        }
        Ok(other_pdus) => {
            panic!("Unknown PDU: {:?}", other_pdus);
        }
        Err(err) => {
            panic!("Receive returned error {:?}", err);
        }
    }
    // Second packet
    match association.receive().await {
        Ok(Pdu::PData { data }) => {
            assert_eq!(data.len(), 1);
            assert_eq!(data[0].data.len(), 2);
        }
        Ok(other_pdus) => {
            panic!("Unknown PDU: {:?}", other_pdus);
        }
        Err(err) => {
            panic!("Receive returned error {:?}", err);
        }
    }

    association
        .release()
        .await
        .expect("did not have a peaceful release (async)");

    scp_handle
        .await
        .expect("SCP panicked (async)")
        .expect("Error at the SCP (async)");
}