/
_handlers.py
4279 lines (3561 loc) · 158 KB
/
_handlers.py
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Standard logging event handlers."""
import logging
from struct import unpack, calcsize
from typing import (
TYPE_CHECKING,
List,
Optional,
cast,
Union,
Dict,
Any,
Sequence,
Iterator,
Tuple,
)
from pydicom.dataset import Dataset
from pydicom.uid import UID
from pynetdicom.dimse_messages import (
C_STORE_RQ,
C_STORE_RSP,
C_FIND_RQ,
C_FIND_RSP,
C_GET_RQ,
C_GET_RSP,
C_MOVE_RQ,
C_MOVE_RSP,
C_ECHO_RQ,
C_ECHO_RSP,
C_CANCEL_RQ,
N_EVENT_REPORT_RQ,
N_EVENT_REPORT_RSP,
N_GET_RQ,
N_GET_RSP,
N_SET_RQ,
N_SET_RSP,
N_ACTION_RQ,
N_ACTION_RSP,
N_CREATE_RQ,
N_CREATE_RSP,
N_DELETE_RQ,
N_DELETE_RSP,
)
from pynetdicom.pdu import (
A_ASSOCIATE_RQ,
A_ASSOCIATE_AC,
A_ASSOCIATE_RJ,
A_RELEASE_RQ,
A_RELEASE_RP,
A_ABORT_RQ,
P_DATA_TF,
)
from pynetdicom.sop_class import uid_to_service_class
from pynetdicom.utils import pretty_bytes, decode_bytes
if TYPE_CHECKING: # pragma: no cover
from pynetdicom.events import Event
from pynetdicom.pdu_items import UserInformationItem, UserIdentitySubItemRQ
from pynetdicom.pdu_items import SOPClassCommonExtendedNegotiation
LOGGER = logging.getLogger(__name__)
# Debugging handlers
def debug_fsm(event: "Event") -> None:
"""Debugging handler for the FSM."""
LOGGER.debug(
"{}: {} + {} -> {} -> {}".format(
event.assoc.mode[0].upper(),
event.current_state,
event.fsm_event,
event.action,
event.next_state,
)
)
def debug_data(
event: "Event",
pdu_type: Optional[int] = None,
print_raw: bool = True,
print_summary: bool = False,
) -> None:
"""Debugging handler for parsing raw encoded PDUs
Usable with ``evt.EVT_DATA_RECV`` and ``evt.EVT_DATA_SENT``.
Parameters
----------
event : pynetdicom.events.Event
The event object.
pdu_type : int, optional
If used, this should be the PDU type for the PDU you are interested in,
should be in the range 1 to 7.
print_raw : bool, optional
If ``True`` (default) then print only the raw encoded PDU as hex.
print_summary : bool, optional
If ``True`` then print out a summary of the PDU contents (default
``False``).
"""
data = event.data
if pdu_type and data[0] != pdu_type:
return
if print_raw:
LOGGER.debug(f"{' DEBUG - ENCODED PDU ':=^76}")
slist = pretty_bytes(
data, prefix=" ", delimiter=" ", max_size=None, items_per_line=25
)
for s in slist:
LOGGER.debug(s)
LOGGER.debug(f"{' END ENCODED PDU ':=^76}")
PDU_ITEM_TYPES = {
0x01: ("A-ASSOCIATE-RQ", ">I", 74),
0x02: ("A-ASSOCIATE-AC", ">I", 74),
0x03: ("A-ASSOCIATE-RJ", ">I", None),
0x04: ("P-DATA-TF", ">I", None),
0x05: ("A-RELEASE-RQ", ">I", None),
0x06: ("A-RELEASE-RP", ">I", None),
0x07: ("A-ABORT", ">I", None),
0x10: ("Application Context", ">H", None),
0x20: ("Presentation Context RQ", ">H", 8),
0x21: ("Presentation Context AC", ">H", 8),
0x30: ("Abstract Syntax", ">H", None),
0x40: ("Transfer Syntax", ">H", None),
0x50: ("User Information", ">H", 4),
0x51: ("Maximum Length", ">H", None),
0x52: ("Implementation Class UID", ">H", None),
0x53: ("Asynchronous Operations", ">H", None),
0x54: ("SCP/SCU Role Selection", ">H", None),
0x55: ("Implementation Version Name", ">H", None),
0x56: ("SOP Class Extended Negotiation", ">H", None),
0x57: ("SOP Class Common Extended Negotiation", ">H", None),
0x58: ("User Identity RQ", ">H", None),
0x59: ("User Identity AC", ">H", None),
}
if print_summary:
LOGGER.debug(f"{' DEBUG - PDU SUMMARY ':=^76}")
idx = 0
digits = len(str(len(data)))
while idx < len(data):
data_type = data[idx]
name, fmt, len_fixed = PDU_ITEM_TYPES[data_type]
len_bytes = calcsize(fmt)
length = unpack(fmt, data[idx + 2 : idx + 2 + len_bytes])[0]
s = f" {idx:>{digits}}: 0x{data_type:02X} - {name} " f"({length} bytes)"
# Presentation Content Item
if data_type == 0x20:
cx_id = data[idx + 2 + len_bytes]
s += f" - {cx_id}"
# Abstract and Transfer Syntax Sub-items
if data_type in [0x30, 0x40] and length:
start = idx + 2 + len_bytes
uid = UID(decode_bytes(data[start : start + length]))
s += f" - {uid.name}"
# SCP/SCU Role Selection Sub-item
if data_type == 0x054:
start = idx + 2 + len_bytes
len_uid = unpack(">H", data[start : start + 2])[0]
uid = UID(decode_bytes(data[start + 2 : start + 2 + len_uid]))
scu_role = data[start + 2 + len_uid]
scp_role = data[start + 2 + len_uid + 1]
s += f" - {uid.name}, SCU {scu_role}, SCP {scp_role}"
# A-ASSOCIATE-RJ
if data_type == 0x03:
s += (
f" - Result {data[idx + 7]}, Source {data[idx + 8]}, "
f"Reason {data[idx + 9]}"
)
# A-ABORT
if data_type == 0x07:
s += f" - Source {data[idx + 8]}, Reason {data[idx + 9]}"
LOGGER.debug(s)
# P-DATA-TF
if data_type == 0x04:
offset = idx + 2 + len_bytes
while offset < idx + 2 + len_bytes + length:
item_length = unpack(">I", data[offset : offset + 4])[0]
cx_id = data[offset + 4]
LOGGER.debug(
f" {offset:>{digits}}: PDV - context ID "
f"{cx_id}, length {item_length}"
)
offset += item_length + 4
if len_fixed:
idx += len_fixed
else:
if data_type < 8:
idx += length + 6
else:
idx += length + 4
LOGGER.debug(f"{' END PDU SUMMARY ':=^76}")
# Standard logging handlers
def standard_pdu_recv_handler(event: "Event") -> List[str]:
"""Standard handler when a PDU is received and decoded.
**Event**
``evt.EVT_PDU_RECV``
Parameters
----------
event : events.Event
The ``evt.EVT_PDU_RECV`` event corresponding to receiving and decoding
a PDU from the peer. :class:`~pynetdicom.events.Event` attributes are:
* :attr:`~pynetdicom.events.Event.assoc`: the
:class:`~pynetdicom.association.Association`
that received the PDU.
* ``pdu``: the PDU that was received, one of the ``pdu.PDU``
subclasses.
* :attr:`~pynetdicom.events.Event.timestamp`: the date and time that
the PDU was received as :class:`datetime.datetime`.
"""
pdu = event.pdu
handlers = {
A_ASSOCIATE_AC: _receive_associate_ac,
A_ASSOCIATE_RJ: _receive_associate_rj,
A_ASSOCIATE_RQ: _receive_associate_rq,
A_RELEASE_RQ: _receive_release_rq,
A_RELEASE_RP: _receive_release_rp,
A_ABORT_RQ: _receive_abort_pdu,
P_DATA_TF: _receive_data_tf,
}
with event.assoc.lock:
return handlers[type(pdu)](event)
def standard_pdu_sent_handler(event: "Event") -> List[str]:
"""Standard handler when a PDU is encoded and sent.
**Event**
``evt.EVT_PDU_SENT``
Parameters
----------
event : events.Event
The ``evt.EVT_PDU_SENT`` event corresponding to encoding and sending
a PDU to the peer. :class:`~pynetdicom.events.Event` attributes are:
* :attr:`~pynetdicom.events.Event.assoc`: the
:class:`~pynetdicom.association.Association`
that sent the PDU.
* ``pdu``: the PDU that was sent, one of the ``pdu.PDU`` subclasses.
* :attr:`~pynetdicom.events.Event.timestamp`: the date and time that
the PDU was sent as :class:`datetime.datetime`.
"""
pdu = event.pdu
handlers = {
A_ASSOCIATE_AC: _send_associate_ac,
A_ASSOCIATE_RJ: _send_associate_rj,
A_ASSOCIATE_RQ: _send_associate_rq,
A_RELEASE_RQ: _send_release_rq,
A_RELEASE_RP: _send_release_rp,
A_ABORT_RQ: _send_abort,
P_DATA_TF: _send_data_tf,
}
with event.assoc.lock:
return handlers[type(pdu)](event)
def standard_dimse_recv_handler(event: "Event") -> List[str]:
"""Standard handler for the ACSE receiving a primitive from the DUL.
Parameters
----------
event : events.Event
The ``evt.EVT_DIMSE_RECV`` event corresponding to the DIMSE decoding
a message received from the peer. :class:`~pynetdicom.events.Event`
attributes are:
* :attr:`~pynetdicom.events.Event.assoc`: the
:class:`~pynetdicom.association.Association`
that the DIMSE is providing services for.
* ``message``: the DIMSE message that was received.
* :attr:`~pynetdicom.events.Event.timestamp`: the date and time that
the message was decoded as :class:`datetime.datetime`.
"""
handlers = {
C_ECHO_RQ: _recv_c_echo_rq,
C_ECHO_RSP: _recv_c_echo_rsp,
C_FIND_RQ: _recv_c_find_rq,
C_FIND_RSP: _recv_c_find_rsp,
C_CANCEL_RQ: _recv_c_cancel_rq,
C_GET_RQ: _recv_c_get_rq,
C_GET_RSP: _recv_c_get_rsp,
C_MOVE_RQ: _recv_c_move_rq,
C_MOVE_RSP: _recv_c_move_rsp,
C_STORE_RQ: _recv_c_store_rq,
C_STORE_RSP: _recv_c_store_rsp,
N_EVENT_REPORT_RQ: _recv_n_event_report_rq,
N_EVENT_REPORT_RSP: _recv_n_event_report_rsp,
N_SET_RQ: _recv_n_set_rq,
N_SET_RSP: _recv_n_set_rsp,
N_GET_RQ: _recv_n_get_rq,
N_GET_RSP: _recv_n_get_rsp,
N_ACTION_RQ: _recv_n_action_rq,
N_ACTION_RSP: _recv_n_action_rsp,
N_CREATE_RQ: _recv_n_create_rq,
N_CREATE_RSP: _recv_n_create_rsp,
N_DELETE_RQ: _recv_n_delete_rq,
N_DELETE_RSP: _recv_n_delete_rsp,
}
with event.assoc.lock:
return handlers[type(event.message)](event)
def standard_dimse_sent_handler(event: "Event") -> List[str]:
"""Standard handler for the ACSE receiving a primitive from the DUL.
Parameters
----------
event : events.Event
The ``evt.EVT_DIMSE_SENT`` event corresponding to the DIMSE encoding
a message to be sent to the peer. :class:`~pynetdicom.events.Event`
attributes are:
* :attr:`~pynetdicom.events.Event.assoc`: the
:class:`~pynetdicom.association.Association`
that the DIMSE is providing services for.
* ``message``: the DIMSE message to be sent.
* :attr:`~pynetdicom.events.Event.timestamp`: the date and time that
the message was decode as :class:`datetime.datetime`.
"""
handlers = {
C_ECHO_RQ: _send_c_echo_rq,
C_ECHO_RSP: _send_c_echo_rsp,
C_FIND_RQ: _send_c_find_rq,
C_FIND_RSP: _send_c_find_rsp,
C_GET_RQ: _send_c_get_rq,
C_GET_RSP: _send_c_get_rsp,
C_MOVE_RQ: _send_c_move_rq,
C_MOVE_RSP: _send_c_move_rsp,
C_STORE_RQ: _send_c_store_rq,
C_STORE_RSP: _send_c_store_rsp,
C_CANCEL_RQ: _send_c_cancel_rq,
N_EVENT_REPORT_RQ: _send_n_event_report_rq,
N_EVENT_REPORT_RSP: _send_n_event_report_rsp,
N_SET_RQ: _send_n_set_rq,
N_SET_RSP: _send_n_set_rsp,
N_GET_RQ: _send_n_get_rq,
N_GET_RSP: _send_n_get_rsp,
N_ACTION_RQ: _send_n_action_rq,
N_ACTION_RSP: _send_n_action_rsp,
N_CREATE_RQ: _send_n_create_rq,
N_CREATE_RSP: _send_n_create_rsp,
N_DELETE_RQ: _send_n_delete_rq,
N_DELETE_RSP: _send_n_delete_rsp,
}
with event.assoc.lock:
return handlers[type(event.message)](event)
# PDU sub-handlers
def _receive_abort_pdu(event: "Event") -> List[str]:
"""Standard logging handler for receiving an A-ABORT PDU."""
pdu = cast("A_ABORT_RQ", event.pdu)
s = [
"Abort Parameters:",
f"{' INCOMING A-ABORT PDU ':=^76}",
f"Abort Source: {pdu.source_str}",
f"Abort Reason: {pdu.reason_str}",
f"{' END A-ABORT PDU ':=^76}",
]
for line in s:
LOGGER.debug(line)
return s
def _receive_associate_ac(event: "Event") -> List[str]:
"""Standard logging handler for receiving an A-ASSOCIATE-AC PDU."""
assoc_ac = cast("A_ASSOCIATE_AC", event.pdu)
app_context = cast(UID, assoc_ac.application_context_name)
pres_contexts = sorted(
assoc_ac.presentation_context, key=lambda x: cast(int, x.context_id)
)
user_info = cast("UserInformationItem", assoc_ac.user_information)
async_ops = user_info.async_ops_window
roles = user_info.role_selection
req_contexts = {
ii.context_id: ii for ii in event.assoc.requestor.requested_contexts
}
their_class_uid = "unknown"
their_version = "unknown"
if user_info.implementation_class_uid:
their_class_uid = user_info.implementation_class_uid
if user_info.implementation_version_name:
their_version = user_info.implementation_version_name
s = [
"Accept Parameters:",
f"{' INCOMING A-ASSOCIATE-AC PDU ':=^76}",
f"Their Implementation Class UID: {their_class_uid}",
f"Their Implementation Version Name: {their_version}",
f"Application Context Name: {app_context}",
f"Calling Application Name: {assoc_ac.calling_ae_title}",
f"Called Application Name: {assoc_ac.called_ae_title}",
f"Their Max PDU Receive Size: {user_info.maximum_length}",
"Presentation Contexts:",
]
for cx in pres_contexts:
s.append(f" Context ID: {cx.context_id} ({cx.result_str})")
# Grab the abstract syntax from the requestor
a_syntax = cast(UID, req_contexts[cx.context_id].abstract_syntax)
s.append(f" Abstract Syntax: ={a_syntax.name}")
# Add SCP/SCU Role Selection Negotiation
# Roles are: SCU, SCP/SCU, SCP, Default
if cx.result == 0:
try:
role = roles[a_syntax]
cx_roles = []
if role.scp_role:
cx_roles.append("SCP")
if role.scu_role:
cx_roles.append("SCU")
scp_scu_role = "/".join(cx_roles)
except KeyError:
scp_scu_role = "Default"
s.append(f" Accepted SCP/SCU Role: {scp_scu_role}")
s.append(
" Accepted Transfer Syntax: "
f"={cast(UID, cx.transfer_syntax).name}"
)
# Extended Negotiation
if user_info.ext_neg:
s.append("Accepted Extended Negotiation:")
for item in user_info.ext_neg:
s.append(f" SOP Class: ={item.uid}")
s.extend([f" {s}" for s in pretty_bytes(cast(bytes, item.app_info))])
else:
s.append("Accepted Extended Negotiation: None")
# Asynchronous Operations
if async_ops:
max_invoked = async_ops.maximum_number_operations_invoked
max_performed = async_ops.maximum_number_operations_performed
s.append("Accepted Asynchronous Operations Window Negotiation:")
s.append(f" Maximum Invoked Operations: {max_invoked}")
s.append(f" Maximum Performed Operations: {max_performed}")
else:
s.append("Accepted Asynchronous Operations Window Negotiation: None")
# User Identity
usr_id = "Yes" if user_info.user_identity else "None"
s.append(f"User Identity Negotiation Response: {usr_id}")
s.append(f"{' END A-ASSOCIATE-AC PDU ':=^76}")
for line in s:
LOGGER.debug(line)
return s
def _receive_associate_rj(event: "Event") -> List[str]:
"""Standard logging handler for receiving an A-ASSOCIATE-RJ PDU."""
assoc_rj = cast("A_ASSOCIATE_RJ", event.pdu)
s = [
"Reject Parameters:",
f"{' INCOMING A-ASSOCIATE-RJ PDU ':=^76}",
f"Result: {assoc_rj.result_str}",
f"Source: {assoc_rj.source_str}",
f"Reason: {assoc_rj.reason_str}",
f"{' END A-ASSOCIATE-RJ PDU ':=^76}",
]
for line in s:
LOGGER.debug(line)
return s
def _receive_associate_rq(event: "Event") -> List[str]:
"""Standard logging handler for receiving an A-ASSOCIATE-RQ PDU."""
pdu = cast("A_ASSOCIATE_RQ", event.pdu)
app_context = cast(UID, pdu.application_context_name)
pres_contexts = sorted(
pdu.presentation_context, key=lambda x: cast(int, x.context_id)
)
user_info = cast("UserInformationItem", pdu.user_information)
their_class_uid: Union[str, UID] = "unknown"
their_version = "unknown"
if user_info.implementation_class_uid:
their_class_uid = user_info.implementation_class_uid
if user_info.implementation_version_name:
their_version = user_info.implementation_version_name
s = [
"Request Parameters:",
f"{' INCOMING A-ASSOCIATE-RQ PDU ':=^76}",
f"Their Implementation Class UID: {their_class_uid}",
f"Their Implementation Version Name: {their_version}",
f"Application Context Name: {app_context}",
f"Calling Application Name: {pdu.calling_ae_title}",
f"Called Application Name: {pdu.called_ae_title}",
f"Their Max PDU Receive Size: {user_info.maximum_length}",
]
# Presentation Contexts
if len(pres_contexts) == 1:
s.append("Presentation Context:")
else:
s.append("Presentation Contexts:")
for context in pres_contexts:
asyntax = cast(UID, context.abstract_syntax)
s.append(f" Context ID: {context.context_id} (Proposed)")
s.append(f" Abstract Syntax: ={asyntax.name}")
# Add SCP/SCU Role Selection Negotiation
# Roles are: SCU, SCP/SCU, SCP, Default
if user_info.role_selection:
try:
role = user_info.role_selection[asyntax]
roles = []
if role.scp_role:
roles.append("SCP")
if role.scu_role:
roles.append("SCU")
scp_scu_role = "/".join(roles)
except KeyError:
scp_scu_role = "Default"
else:
scp_scu_role = "Default"
s.append(f" Proposed SCP/SCU Role: {scp_scu_role}")
# Transfer Syntaxes
if len(context.transfer_syntax) == 1:
s.append(" Proposed Transfer Syntax:")
else:
s.append(" Proposed Transfer Syntaxes:")
s.extend([f" ={ts.name}" for ts in context.transfer_syntax])
# Extended Negotiation
if user_info.ext_neg:
s.append("Requested Extended Negotiation:")
for item_a in user_info.ext_neg:
s.append(f" SOP Class: ={item_a.uid}")
s.extend([f" {s}" for s in pretty_bytes(cast(bytes, item_a.app_info))])
else:
s.append("Requested Extended Negotiation: None")
# Common Extended Negotiation
if user_info.common_ext_neg:
s.append("Requested Common Extended Negotiation:")
for ib in user_info.common_ext_neg:
s.append(f" SOP Class: ={cast(UID, ib.sop_class_uid).name}")
s.append(f" Service Class: ={cast(UID, ib.service_class_uid).name}")
related_uids = ib.related_general_sop_class_identification
if related_uids:
s.append(" Related General SOP Class(es):")
s.extend([f" ={uid.name}" for uid in related_uids])
else:
s.append(" Related General SOP Classes: None")
else:
s.append("Requested Common Extended Negotiation: None")
# Asynchronous Operations Window Negotiation
async_ops = user_info.async_ops_window
if async_ops is not None:
max_invoked = async_ops.maximum_number_operations_invoked
max_performed = async_ops.maximum_number_operations_performed
s.append("Requested Asynchronous Operations Window Negotiation:")
s.append(f" Maximum Invoked Operations: {max_invoked}")
s.append(f" Maximum Performed Operations: {max_performed}")
else:
s.append("Requested Asynchronous Operations Window Negotiation: None")
# User Identity
if user_info.user_identity is not None:
usid = cast("UserIdentitySubItemRQ", user_info.user_identity)
primary = cast(bytes, usid.primary)
p_len = len(primary)
s.append("Requested User Identity Negotiation:")
s.append(f" Authentication Mode: {usid.id_type} - {usid.id_type_str}")
if usid.id_type == 1:
s.append(f" Username: [{primary.decode('utf-8')}]")
elif usid.id_type == 2:
secondary = cast(bytes, usid.secondary)
s.append(f" Username: [{primary.decode('utf-8')}]")
s.append(f" Password: [{secondary.decode('utf-8')}]")
elif usid.id_type == 3:
s.append(f" Kerberos Service Ticket (not dumped) length: {p_len}")
elif usid.id_type == 4:
s.append(f" SAML Assertion (not dumped) length: {p_len}")
elif usid.id_type == 5:
s.append(f" JSON Web Token (not dumped) length: {p_len}")
if usid.response_requested:
s.append(" Positive Response Requested: Yes")
else:
s.append(" Positive Response Requested: None")
else:
s.append("Requested User Identity Negotiation: None")
s.append(f"{' END A-ASSOCIATE-RQ PDU ':=^76}")
for line in s:
LOGGER.debug(line)
return s
def _receive_data_tf(event: "Event") -> List[str]:
"""Standard logging handler for receiving a P-DATA-TF PDU."""
return []
def _receive_release_rp(event: "Event") -> List[str]:
"""Standard logging handler for receiving an A-RELEASE-RP PDU."""
return []
def _receive_release_rq(event: "Event") -> List[str]:
"""Standard logging handler for receiving an A-RELEASE-RQ PDU."""
return []
def _send_abort(event: "Event") -> List[str]:
"""Standard logging handler for sending an A-ABORT PDU."""
pdu = cast("A_ABORT_RQ", event.pdu)
s = [
"Abort Parameters:",
f"{' OUTGOING A-ABORT PDU ':=^76}",
f"Abort Source: {pdu.source_str}",
f"Abort Reason: {pdu.reason_str}",
f"{' END A-ABORT PDU ':=^76}",
]
for line in s:
LOGGER.debug(line)
return s
def _send_associate_ac(event: "Event") -> List[str]:
"""Standard logging handler for sending an A-ASSOCIATE-AC PDU."""
assoc_ac = cast("A_ASSOCIATE_AC", event.pdu)
req_contexts = {
ii.context_id: ii for ii in event.assoc.requestor.get_contexts("pcdl")
}
# Needs some cleanup
app_context = cast(UID, assoc_ac.application_context_name)
pres_contexts = assoc_ac.presentation_context
user_info = cast("UserInformationItem", assoc_ac.user_information)
async_ops = user_info.async_ops_window
roles = user_info.role_selection
responding_ae = "resp. AE Title"
class_uid = user_info.implementation_class_uid
s = [
"Accept Parameters:",
f"{' OUTGOING A-ASSOCIATE-AC PDU ':=^76}",
f"Our Implementation Class UID: {class_uid}",
]
if user_info.implementation_version_name:
version_name = user_info.implementation_version_name
s.append(f"Our Implementation Version Name: {version_name}")
s.append(f"Application Context Name: {app_context}")
s.append(f"Responding Application Name: {responding_ae}")
s.append(f"Our Max PDU Receive Size: {user_info.maximum_length}")
if pres_contexts:
s.append("Presentation Contexts:")
else:
s.append("Presentation Contexts: None")
# Sort by context ID
for cx in sorted(pres_contexts, key=lambda x: cast(int, x.context_id)):
s.append(f" Context ID: {cx.context_id} ({cx.result_str})")
a_syntax = cast(UID, req_contexts[cx.context_id].abstract_syntax)
s.append(f" Abstract Syntax: ={a_syntax.name}")
# If Presentation Context was accepted
if cx.result == 0:
try:
role = roles[a_syntax]
cx_roles = []
if role.scp_role:
cx_roles.append("SCP")
if role.scu_role:
cx_roles.append("SCU")
scp_scu_role = "/".join(cx_roles)
except KeyError:
scp_scu_role = "Default"
s.append(f" Accepted SCP/SCU Role: {scp_scu_role}")
s.append(
" Accepted Transfer Syntax: "
f"={cast(UID, cx.transfer_syntax).name}"
)
# Extended Negotiation
if user_info.ext_neg:
s.append("Accepted Extended Negotiation:")
for item in user_info.ext_neg:
s.append(f" SOP Class: ={item.uid}")
s.extend([f" {s}" for s in pretty_bytes(cast(bytes, item.app_info))])
else:
s.append("Accepted Extended Negotiation: None")
# Asynchronous Operations
if async_ops:
max_invoked = async_ops.maximum_number_operations_invoked
max_performed = async_ops.maximum_number_operations_performed
s.append("Accepted Asynchronous Operations Window Negotiation:")
s.append(f" Maximum Invoked Operations: {max_invoked}")
s.append(f" Maximum Performed Operations: {max_performed}")
else:
s.append("Accepted Asynchronous Operations Window Negotiation: None")
# User Identity Negotiation
usr_id = "Yes" if user_info.user_identity is not None else "None"
s.append(f"User Identity Negotiation Response: {usr_id}")
s.append(f"{' END A-ASSOCIATE-AC PDU ':=^76}")
for line in s:
LOGGER.debug(line)
return s
def _send_associate_rj(event: "Event") -> List[str]:
"""Standard logging handler for sending an A-ASSOCIATE-RJ PDU."""
assoc_rj = cast("A_ASSOCIATE_RJ", event.pdu)
s = [
"Reject Parameters:",
f"{' OUTGOING A-ASSOCIATE-RJ PDU ':=^76}",
f"Result: {assoc_rj.result_str}",
f"Source: {assoc_rj.source_str}",
f"Reason: {assoc_rj.reason_str}",
f"{' END A-ASSOCIATE-RJ PDU ':=^76}",
]
for line in s:
LOGGER.debug(line)
return s
def _send_associate_rq(event: "Event") -> List[str]:
"""Standard logging handler for sending an A-ASSOCIATE-RQ PDU."""
pdu = cast("A_ASSOCIATE_RQ", event.pdu)
app_context = cast(UID, pdu.application_context_name)
pres_contexts = pdu.presentation_context
user_info = cast("UserInformationItem", pdu.user_information)
class_uid = user_info.implementation_class_uid
s = [
"Request Parameters:",
f"{' OUTGOING A-ASSOCIATE-RQ PDU ':=^76}",
f"Our Implementation Class UID: {class_uid}",
]
if user_info.implementation_version_name:
version_name = user_info.implementation_version_name
s.append(f"Our Implementation Version Name: {version_name}")
s.append(f"Application Context Name: {app_context}")
s.append(f"Calling Application Name: {pdu.calling_ae_title}")
s.append(f"Called Application Name: {pdu.called_ae_title}")
s.append(f"Our Max PDU Receive Size: {user_info.maximum_length}")
# Presentation Contexts
if len(pres_contexts) == 1:
s.append("Presentation Context:")
else:
s.append("Presentation Contexts:")
for context in pres_contexts:
asyntax = cast(UID, context.abstract_syntax)
s.append(f" Context ID: {context.context_id} (Proposed)")
s.append(f" Abstract Syntax: ={asyntax.name}")
# Add SCP/SCU Role Selection Negotiation
# Roles are: SCU, SCP/SCU, SCP, Default
if user_info.role_selection:
try:
role = user_info.role_selection[asyntax]
roles = []
if role.scp_role:
roles.append("SCP")
if role.scu_role:
roles.append("SCU")
scp_scu_role = "/".join(roles)
except KeyError:
scp_scu_role = "Default"
else:
scp_scu_role = "Default"
s.append(f" Proposed SCP/SCU Role: {scp_scu_role}")
# Transfer Syntaxes
if len(context.transfer_syntax) == 1:
s.append(" Proposed Transfer Syntax:")
else:
s.append(" Proposed Transfer Syntaxes:")
s.extend([f" ={ts.name}" for ts in context.transfer_syntax])
# Extended Negotiation
if user_info.ext_neg:
s.append("Requested Extended Negotiation:")
for ia in user_info.ext_neg:
s.append(f" SOP Class: ={ia.uid}")
s.extend([f" {s}" for s in pretty_bytes(cast(bytes, ia.app_info))])
else:
s.append("Requested Extended Negotiation: None")
# Common Extended Negotiation
if user_info.common_ext_neg:
s.append("Requested Common Extended Negotiation:")
for item in user_info.common_ext_neg:
s.append(f" SOP Class: ={cast(UID, item.sop_class_uid).name}")
s.append(f" Service Class: ={cast(UID, item.service_class_uid).name}")
related_uids = item.related_general_sop_class_identification
if related_uids:
s.append(" Related General SOP Class(es):")
s.extend([f" ={sub.name}" for sub in related_uids])
else:
s.append(" Related General SOP Classes: None")
else:
s.append("Requested Common Extended Negotiation: None")
# Asynchronous Operations Window Negotiation
async_ops = user_info.async_ops_window
if async_ops is not None:
max_invoked = async_ops.maximum_number_operations_invoked
max_performed = async_ops.maximum_number_operations_performed
s.append("Requested Asynchronous Operations Window Negotiation:")
s.append(f" Maximum Invoked Operations: {max_invoked}")
s.append(f" Maximum Performed Operations: {max_performed}")
else:
s.append("Requested Asynchronous Operations Window Negotiation: None")
# User Identity
if user_info.user_identity is not None:
usid = cast("UserIdentitySubItemRQ", user_info.user_identity)
primary = cast(bytes, usid.primary)
p_len = len(primary)
s.append("Requested User Identity Negotiation:")
s.append(f" Authentication Mode: {usid.id_type} - {usid.id_type_str}")
if usid.id_type == 1:
s.append(f" Username: [{primary.decode('utf-8')}]")
elif usid.id_type == 2:
secondary = cast(bytes, usid.secondary)
s.append(f" Username: [{primary.decode('utf-8')}]")
s.append(f" Password: [{secondary.decode('utf-8')}]")
elif usid.id_type == 3:
s.append(f" Kerberos Service Ticket (not dumped) length: {p_len}")
elif usid.id_type == 4:
s.append(f" SAML Assertion (not dumped) length: {p_len}")
elif usid.id_type == 5:
s.append(f" JSON Web Token (not dumped) length: {p_len}")
if usid.response_requested:
s.append(" Positive Response Requested: Yes")
else:
s.append(" Positive Response Requested: No")
else:
s.append("Requested User Identity Negotiation: None")
s.append(f"{' END A-ASSOCIATE-RQ PDU ':=^76}")
for line in s:
LOGGER.debug(line)
return s
def _send_data_tf(event: "Event") -> List[str]:
"""Standard logging handler for sending a P-DATA-TF PDU."""
return []
def _send_release_rp(event: "Event") -> List[str]:
"""Standard logging handler for sending an A-RELEASE-RP PDU."""
return []
def _send_release_rq(event: "Event") -> List[str]:
"""Standard logging handler for sending an A-RELEASE-RQ PDU."""
return []
# DIMSE sub-handlers
def _send_c_echo_rq(event: "Event") -> List[str]:
"""Logging handler for when a C-ECHO-RQ is sent.
**C-ECHO Request Parameters**
| (M) Message ID
| (M) Affected SOP Class UID
Parameters
----------
event : events.Event
The evt.EVT_DIMSE_SENT event that occurred.
"""
return []
def _send_c_echo_rsp(event: "Event") -> List[str]:
"""Logging handler for when a C-ECHO-RSP is sent.
**C-ECHO Response Parameters**
| (U) Message ID
| (M) Message ID Being Responded To
| (U) Affected SOP Class UID
| (M) Status
Parameters
----------
event : events.Event
The evt.EVT_DIMSE_SENT event that occurred.
"""
return []
def _send_c_store_rq(event: "Event") -> List[str]:
"""Logging handler when a C-STORE-RQ is sent.
**C-STORE Request Elements**
| (M) Message ID
| (M) Affected SOP Class UID
| (M) Affected SOP Instance UID
| (M) Priority
| (U) Move Originator Application Entity Title
| (U) Move Originator Message ID
| (M) Data Set
Parameters
----------
event : events.Event
The evt.EVT_DIMSE_SENT event that occurred.
"""
msg = event.message
cs = msg.command_set
priority_str = {2: "Low", 0: "Medium", 1: "High"}
priority = priority_str[cast(int, cs.Priority)]
dataset = "None"
if msg.data_set and msg.data_set.getvalue() != b"":
dataset = "Present"
elif msg._data_set_path is not None:
dataset = "Present"
sop_class = cast(UID, cs.AffectedSOPClassUID)
if sop_class.name == "CT Image Storage":
dataset_type = ", (CT)"
elif sop_class.name == "MR Image Storage":
dataset_type = ", (MR)"
else:
dataset_type = ""
LOGGER.info(f"Sending Store Request: MsgID {cs.MessageID}{dataset_type}")
s = [
f"{' OUTGOING DIMSE MESSAGE ':=^76}",
"Message Type : C-STORE RQ",
f"Message ID : {cs.MessageID}",