File: dulfsm.cc

package info (click to toggle)
dcmtk 3.6.4-2.1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 54,480 kB
  • sloc: cpp: 271,774; ansic: 47,307; makefile: 5,280; sh: 4,318; perl: 850; xml: 182; lex: 103
file content (4035 lines) | stat: -rw-r--r-- 142,564 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
/*
 *
 *  Copyright (C) 1994-2018, OFFIS e.V.
 *  All rights reserved.  See COPYRIGHT file for details.
 *
 *  This software and supporting documentation were partly developed by
 *
 *    OFFIS e.V.
 *    R&D Division Health
 *    Escherweg 2
 *    D-26121 Oldenburg, Germany
 *
 *  For further copyrights, see the following paragraphs.
 *
 */

/*
          Copyright (C) 1993, 1994, RSNA and Washington University

          The software and supporting documentation for the Radiological
          Society of North America (RSNA) 1993, 1994 Digital Imaging and
          Communications in Medicine (DICOM) Demonstration were developed
          at the
                  Electronic Radiology Laboratory
                  Mallinckrodt Institute of Radiology
                  Washington University School of Medicine
                  510 S. Kingshighway Blvd.
                  St. Louis, MO 63110
          as part of the 1993, 1994 DICOM Central Test Node project for, and
          under contract with, the Radiological Society of North America.

          THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND NEITHER RSNA NOR
          WASHINGTON UNIVERSITY MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
          PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
          USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
          SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
          THE SOFTWARE IS WITH THE USER.

          Copyright of the software and supporting documentation is
          jointly owned by RSNA and Washington University, and free access
          is hereby granted as a license to use this software, copy this
          software and prepare derivative works based upon this software.
          However, any distribution of this software source code or
          supporting documentation or derivative works (source code and
          supporting documentation) must include the three paragraphs of
          the copyright notice.
*/

/*
**          DICOM 93
**        Electronic Radiology Laboratory
**      Mallinckrodt Institute of Radiology
**    Washington University School of Medicine
**
** Module Name(s):  DUL_InitializeFSM
**      PRV_StateMachine
**      fsmDebug
**
** Author, Date:  Stephen M. Moore, 15-Apr-93
** Intent:        Define tables and provide functions that implement
**                the DICOM Upper Layer (DUL) finite state machine.
*/


#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */

#ifdef HAVE_WINDOWS_H
// on Windows, we need Winsock2 for network functions
#include <winsock2.h>
// and ws2tcpip for socklen_t
#include <ws2tcpip.h>
#endif

#define INCLUDE_CSTDLIB
#define INCLUDE_CSTDIO
#define INCLUDE_CSTRING
#define INCLUDE_CERRNO
#define INCLUDE_CSIGNAL
#define INCLUDE_CTIME
#define INCLUDE_UNISTD
#include "dcmtk/ofstd/ofstdinc.h"

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#endif

BEGIN_EXTERN_C
#ifdef HAVE_NETINET_IN_SYSTM_H
#include <netinet/in_systm.h>   /* prerequisite for netinet/in.h on NeXT */
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>         /* prerequisite for netinet/tcp.h on NeXT */
#endif
#ifdef HAVE_NETINET_TCP_H
#include <netinet/tcp.h>        /* for TCP_NODELAY */
#endif
END_EXTERN_C
#ifdef DCMTK_HAVE_POLL
#include <poll.h>
#endif

#include "dcmtk/ofstd/ofstream.h"
#include "dcmtk/dcmnet/dicom.h"
#include "dcmtk/dcmnet/lst.h"
#include "dcmtk/dcmnet/cond.h"
#include "dcmtk/dcmnet/dul.h"
#include "dulstruc.h"
#include "dulpriv.h"
#include "dulfsm.h"
#include "dcmtk/ofstd/ofbmanip.h"
#include "dcmtk/ofstd/ofconsol.h"
#include "dcmtk/dcmnet/assoc.h"    /* for ASC_MAXIMUMPDUSIZE */
#include "dcmtk/dcmnet/dcmtrans.h"
#include "dcmtk/dcmnet/dcmlayer.h"
#include "dcmtk/dcmnet/diutil.h"
#include "dcmtk/ofstd/ofsockad.h" /* for class OFSockAddr */

/* At least Solaris doesn't define this */
#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif

/* platform independent definition of EINTR */
enum
{
#ifdef HAVE_WINSOCK_H
    DCMNET_EINTR = WSAEINTR
#else
    DCMNET_EINTR = EINTR
#endif
};

static OFCondition
AE_1_TransportConnect(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AE_2_SendAssociateRQPDU(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AE_3_AssociateConfirmationAccept(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AE_4_AssociateConfirmationReject(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AE_5_TransportConnectResponse(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AE_6_ExamineAssociateRequest(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AE_7_SendAssociateAC(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AE_8_SendAssociateRJ(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);

static OFCondition
DT_1_SendPData(PRIVATE_NETWORKKEY ** network,
         PRIVATE_ASSOCIATIONKEY ** associatin, int nextState, void *params);
static OFCondition
DT_2_IndicatePData(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);

static OFCondition
AA_1_SendAAbort(PRIVATE_NETWORKKEY ** network,
         PRIVATE_ASSOCIATIONKEY ** associatin, int nextState, void *params);
static OFCondition
AA_2_CloseTransport(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AA_2_CloseTimeout(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AA_3_IndicatePeerAborted(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AA_4_IndicateAPAbort(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AA_5_StopARTIMtimer(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AA_6_IgnorePDU(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AA_7_State13SendAbort(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AA_8_UnrecognizedPDUSendAbort(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);

static OFCondition
AR_1_SendReleaseRQ(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AR_2_IndicateRelease(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AR_3_ConfirmRelease(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AR_4_SendReleaseRP(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AR_5_StopARTIMtimer(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AR_6_IndicatePData(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AR_7_SendPDATA(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AR_8_IndicateARelease(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AR_9_SendAReleaseRP(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);
static OFCondition
AR_10_ConfirmRelease(PRIVATE_NETWORKKEY ** network,
        PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params);

static OFCondition
requestAssociationTCP(PRIVATE_NETWORKKEY ** network,
                      DUL_ASSOCIATESERVICEPARAMETERS * params,
                      PRIVATE_ASSOCIATIONKEY ** association);
static OFCondition
sendAssociationRQTCP(PRIVATE_NETWORKKEY ** network,
                     DUL_ASSOCIATESERVICEPARAMETERS * params,
                     PRIVATE_ASSOCIATIONKEY ** association);
static OFCondition
sendAssociationACTCP(PRIVATE_NETWORKKEY ** network,
                     DUL_ASSOCIATESERVICEPARAMETERS * params,
                     PRIVATE_ASSOCIATIONKEY ** association);
static OFCondition
sendAssociationRJTCP(PRIVATE_NETWORKKEY ** network,
        DUL_ABORTITEMS * abortItems, PRIVATE_ASSOCIATIONKEY ** association);
static OFCondition
sendAbortTCP(DUL_ABORTITEMS * abortItems,
             PRIVATE_ASSOCIATIONKEY ** association);
static OFCondition sendReleaseRQTCP(PRIVATE_ASSOCIATIONKEY ** association);
static OFCondition sendReleaseRPTCP(PRIVATE_ASSOCIATIONKEY ** association);
static OFCondition
sendPDataTCP(PRIVATE_ASSOCIATIONKEY ** association,
             DUL_PDVLIST * pdvList);
static OFCondition
writeDataPDU(PRIVATE_ASSOCIATIONKEY ** association,
             DUL_DATAPDU * pdu);
static void clearPDUCache(PRIVATE_ASSOCIATIONKEY ** association);
static void closeTransport(PRIVATE_ASSOCIATIONKEY ** association);
static void closeTransportTCP(PRIVATE_ASSOCIATIONKEY ** association);
static OFCondition
readPDUHead(PRIVATE_ASSOCIATIONKEY ** association,
            unsigned char *buffer, unsigned long maxlength,
            DUL_BLOCKOPTIONS block, int timeout,
            unsigned char *PDUtype, unsigned char *PDUreserved,
            unsigned long *PDULength);
static OFCondition
readPDU(PRIVATE_ASSOCIATIONKEY ** association, DUL_BLOCKOPTIONS block,
        int timeout, unsigned char **buffer,
        unsigned char *pduType, unsigned char *pduReserved,
        unsigned long *pduLength);
static OFCondition
readPDUBody(PRIVATE_ASSOCIATIONKEY ** association,
            DUL_BLOCKOPTIONS block, int timeout,
            unsigned char *buffer, unsigned long maxLength,
            unsigned char *pduType, unsigned char *pduReserved,
            unsigned long *pduLength);
static OFCondition
readPDUHeadTCP(PRIVATE_ASSOCIATIONKEY ** association,
               unsigned char *buffer, unsigned long maxLength,
               DUL_BLOCKOPTIONS block, int timeout,
               unsigned char *PDUtype, unsigned char *PDUreserved,
               unsigned long *PDULength);
static OFCondition
readPDUBodyTCP(PRIVATE_ASSOCIATIONKEY ** association,
               DUL_BLOCKOPTIONS block, int timeout,
               unsigned char *buffer, unsigned long maxLength,
               unsigned char *pduType, unsigned char *pduReserved,
               unsigned long *pduLength);
static OFCondition
defragmentTCP(DcmTransportConnection *connection, DUL_BLOCKOPTIONS block, time_t timerStart,
              int timeout, void *b, unsigned long l, unsigned long *rtnLen);

static OFString dump_pdu(const char *type, void *buffer, unsigned long length);

#ifdef _WIN32
static void setTCPBufferLength(SOCKET sock);
#else
static void setTCPBufferLength(int sock);
#endif

OFCondition
translatePresentationContextList(LST_HEAD ** internalList,
                                 LST_HEAD ** SCUSCPRoleList,
                                 LST_HEAD ** userContextList);
DUL_PRESENTATIONCONTEXT *
findPresentationCtx(LST_HEAD ** lst, DUL_PRESENTATIONCONTEXTID contextID);

PRV_SCUSCPROLE *
findSCUSCPRole(LST_HEAD ** lst, char *abstractSyntax);

void destroyPresentationContextList(LST_HEAD ** l);
void destroyUserInformationLists(DUL_USERINFO * userInfo);

static FSM_Event_Description Event_Table[] = {
    {A_ASSOCIATE_REQ_LOCAL_USER, "A-ASSOCIATE request (local user)"},
    {TRANS_CONN_CONFIRM_LOCAL_USER, "Transport conn confirmation (local)"},
    {A_ASSOCIATE_AC_PDU_RCV, "A-ASSOCIATE-AC PDU (on transport)"},
    {A_ASSOCIATE_RJ_PDU_RCV, "A-ASSOCIATE-RJ PDU (on transport)"},
    {TRANS_CONN_INDICATION, "Transport connection indication"},
    {A_ASSOCIATE_RQ_PDU_RCV, "A-ASSOCIATE-RQ PDU (on transport)"},
    {A_ASSOCIATE_RESPONSE_ACCEPT, "A-ASSOCIATE resp prim (accept)"},
    {A_ASSOCIATE_RESPONSE_REJECT, "A-ASSOCIATE resp prim (reject)"},
    {P_DATA_REQ, "P-DATA request primitive"},
    {P_DATA_TF_PDU_RCV, "P-DATA-TF PDU (on transport)"},
    {A_RELEASE_REQ, "A-RELEASE request primitive"},
    {A_RELEASE_RQ_PDU_RCV, "A-RELEASE-RQ PDU (on transport)"},
    {A_RELEASE_RP_PDU_RCV, "A-RELEASE-RP PDU (on transport)"},
    {A_RELEASE_RESP, "A-RELEASE response primitive"},
    {A_ABORT_REQ, "A-ABORT request primitive"},
    {A_ABORT_PDU_RCV, "A-ABORT PDU (on transport)"},
    {TRANS_CONN_CLOSED, "Transport connection closed"},
    {ARTIM_TIMER_EXPIRED, "ARTIM timer expired (rej/rel)"},
    {INVALID_PDU, "Unrecognized/invalid PDU"}
};

static FSM_FUNCTION FSM_FunctionTable[] = {
    {AE_1, AE_1_TransportConnect, "AE 1 Transport Connect"},
    {AE_2, AE_2_SendAssociateRQPDU, "AE 2 Send Associate RQ PDU"},
    {AE_3, AE_3_AssociateConfirmationAccept, "AE 3 Associate Confirmation Accept"},
    {AE_4, AE_4_AssociateConfirmationReject, "AE 4 Associate Confirmation Reject"},
    {AE_5, AE_5_TransportConnectResponse, "AE 5 Transport Connect Response"},
    {AE_6, AE_6_ExamineAssociateRequest, "AE 6 Examine Associate Request"},
    {AE_7, AE_7_SendAssociateAC, "AE 7 Send Associate AC"},
    {AE_8, AE_8_SendAssociateRJ, "AE 8 Send Associate RJ"},

    {DT_1, DT_1_SendPData, "DT 1 Send P DATA PDU"},
    {DT_2, DT_2_IndicatePData, "DT 2 Indicate P DATA PDU Received"},

    {AA_1, AA_1_SendAAbort, "AA 1 Send A ABORT PDU"},
    {AA_2, AA_2_CloseTransport, "AA 2 Close Transport"},
    {AA_2T, AA_2_CloseTimeout, "AA 2 Close Transport (Read Timeout)"},
    {AA_3, AA_3_IndicatePeerAborted, "AA 3 Indicate Peer Aborted"},
    {AA_4, AA_4_IndicateAPAbort, "AA 4 Indicate AP Abort"},
    {AA_5, AA_5_StopARTIMtimer, "AA 5 Stop ARTIM timer"},
    {AA_6, AA_6_IgnorePDU, "AA 6 Ignore PDU"},
    {AA_7, AA_7_State13SendAbort, "AA 7 State 13 Send Abort"},
    {AA_8, AA_8_UnrecognizedPDUSendAbort, "AA 8 Unrecognized PDU Send Abort"},

    {AR_1, AR_1_SendReleaseRQ, "AR 1 Send Release RQ"},
    {AR_2, AR_2_IndicateRelease, "AR 2 Indicate Release"},
    {AR_3, AR_3_ConfirmRelease, "AR 3 Confirm Release"},
    {AR_4, AR_4_SendReleaseRP, "AR 4 Send Release RP"},
    {AR_5, AR_5_StopARTIMtimer, "AR 5 Stop ARTIM timer"},
    {AR_6, AR_6_IndicatePData, "AR 6 Indicate P DATA PDU"},
    {AR_7, AR_7_SendPDATA, "AR 7 Send P DATA PDU"},
    {AR_8, AR_8_IndicateARelease, "AR 8 Indicate A RELEASE"},
    {AR_9, AR_9_SendAReleaseRP, "AR 9 Send A RELEASE RP"},
    {AR_10, AR_10_ConfirmRelease, "AR 10 Confirm Release"}
};

static FSM_ENTRY StateTable[DUL_NUMBER_OF_EVENTS][DUL_NUMBER_OF_STATES] = {
    {
        // EVENT,                    STATE,  ACTION,   NEXT_STATE
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE1, AE_1, STATE4, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE2, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE3, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE5, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE6, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE7, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE8, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE9, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE10, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE11, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE12, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_REQ_LOCAL_USER, STATE13, NOACTION, NOSTATE, "", "", NULL}},

    {
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE2, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE3, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE4, AE_2, STATE5, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE5, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE6, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE7, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE8, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE9, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE10, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE11, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE12, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CONFIRM_LOCAL_USER, STATE13, NOACTION, NOSTATE, "", "", NULL}},

    {
        {A_ASSOCIATE_AC_PDU_RCV, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE2, AA_1, STATE13, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE3, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE5, AE_3, STATE6, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE6, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE7, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE8, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE9, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE10, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE11, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE12, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_AC_PDU_RCV, STATE13, AA_6, STATE13, "", "", NULL}},

    {
        {A_ASSOCIATE_RJ_PDU_RCV, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE2, AA_1, STATE13, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE3, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE5, AE_4, STATE1, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE6, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE7, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE8, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE9, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE10, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE11, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE12, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RJ_PDU_RCV, STATE13, AA_6, STATE13, "", "", NULL}},

    {
        {TRANS_CONN_INDICATION, STATE1, AE_5, STATE2, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE2, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE3, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE5, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE6, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE7, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE8, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE9, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE10, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE11, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE12, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_INDICATION, STATE13, NOACTION, NOSTATE, "", "", NULL}},

    {
        {A_ASSOCIATE_RQ_PDU_RCV, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE2, AE_6, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE3, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE5, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE6, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE7, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE8, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE9, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE10, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE11, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE12, AA_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RQ_PDU_RCV, STATE13, AA_7, STATE13, "", "", NULL}},

    {
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE2, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE3, AE_7, STATE6, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE5, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE6, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE7, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE8, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE9, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE10, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE11, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE12, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_ACCEPT, STATE13, NOACTION, NOSTATE, "", "", NULL}},

    {
        {A_ASSOCIATE_RESPONSE_REJECT, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE2, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE3, AE_8, STATE13, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE5, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE6, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE7, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE8, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE9, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE10, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE11, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE12, NOACTION, NOSTATE, "", "", NULL},
        {A_ASSOCIATE_RESPONSE_REJECT, STATE13, NOACTION, NOSTATE, "", "", NULL}},

    {
        {P_DATA_REQ, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_REQ, STATE2, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_REQ, STATE3, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_REQ, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_REQ, STATE5, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_REQ, STATE6, DT_1, STATE6, "", "", NULL},
        {P_DATA_REQ, STATE7, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_REQ, STATE8, AR_7, STATE8, "", "", NULL},
        {P_DATA_REQ, STATE9, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_REQ, STATE10, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_REQ, STATE11, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_REQ, STATE12, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_REQ, STATE13, NOACTION, NOSTATE, "", "", NULL}},

    {
        {P_DATA_TF_PDU_RCV, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE2, AA_1, STATE13, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE3, AA_8, STATE13, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE5, AA_8, STATE13, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE6, DT_2, STATE6, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE7, AR_6, STATE7, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE8, AA_8, STATE13, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE9, AA_8, STATE13, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE10, AA_8, STATE13, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE11, AA_8, STATE13, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE12, AA_8, STATE13, "", "", NULL},
        {P_DATA_TF_PDU_RCV, STATE13, AA_6, STATE13, "", "", NULL}},

    {
        {A_RELEASE_REQ, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_REQ, STATE2, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_REQ, STATE3, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_REQ, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_REQ, STATE5, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_REQ, STATE6, AR_1, STATE7, "", "", NULL},
        {A_RELEASE_REQ, STATE7, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_REQ, STATE8, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_REQ, STATE9, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_REQ, STATE10, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_REQ, STATE11, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_REQ, STATE12, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_REQ, STATE13, NOACTION, NOSTATE, "", "", NULL}},

    {
        {A_RELEASE_RQ_PDU_RCV, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE2, AA_1, STATE13, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE3, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE5, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE6, AR_2, STATE8, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE7, AR_8, NOSTATE, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE8, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE9, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE10, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE11, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE12, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RQ_PDU_RCV, STATE13, AA_6, STATE13, "", "", NULL}},

    {
        {A_RELEASE_RP_PDU_RCV, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE2, AA_1, STATE13, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE3, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE5, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE6, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE7, AR_3, STATE1, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE8, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE9, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE10, AR_10, STATE12, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE11, AR_3, STATE1, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE12, AA_8, STATE13, "", "", NULL},
        {A_RELEASE_RP_PDU_RCV, STATE13, AA_6, STATE13, "", "", NULL}},

    {
        {A_RELEASE_RESP, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RESP, STATE2, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RESP, STATE3, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RESP, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RESP, STATE5, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RESP, STATE6, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RESP, STATE7, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RESP, STATE8, AR_4, STATE13, "", "", NULL},
        {A_RELEASE_RESP, STATE9, AR_9, STATE11, "", "", NULL},
        {A_RELEASE_RESP, STATE10, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RESP, STATE11, NOACTION, NOSTATE, "", "", NULL},
        {A_RELEASE_RESP, STATE12, AR_4, STATE13, "", "", NULL},
        {A_RELEASE_RESP, STATE13, NOACTION, NOSTATE, "", "", NULL}},

    {
        {A_ABORT_REQ, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {A_ABORT_REQ, STATE2, NOACTION, NOSTATE, "", "", NULL},
        {A_ABORT_REQ, STATE3, AA_1, STATE13, "", "", NULL},
        {A_ABORT_REQ, STATE4, AA_2, STATE1, "", "", NULL},
        {A_ABORT_REQ, STATE5, AA_1, STATE13, "", "", NULL},
        {A_ABORT_REQ, STATE6, AA_1, STATE13, "", "", NULL},
        {A_ABORT_REQ, STATE7, AA_1, STATE13, "", "", NULL},
        {A_ABORT_REQ, STATE8, AA_1, STATE13, "", "", NULL},
        {A_ABORT_REQ, STATE9, AA_1, STATE13, "", "", NULL},
        {A_ABORT_REQ, STATE10, AA_1, STATE13, "", "", NULL},
        {A_ABORT_REQ, STATE11, AA_1, STATE13, "", "", NULL},
        {A_ABORT_REQ, STATE12, AA_1, STATE13, "", "", NULL},
        {A_ABORT_REQ, STATE13, NOACTION, NOSTATE, "", "", NULL}},

    {
        {A_ABORT_PDU_RCV, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE2, AA_2, STATE1, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE3, AA_3, STATE1, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE5, AA_3, STATE1, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE6, AA_3, STATE1, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE7, AA_3, STATE1, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE8, AA_3, STATE1, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE9, AA_3, STATE1, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE10, AA_3, STATE1, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE11, AA_3, STATE1, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE12, AA_3, STATE1, "", "", NULL},
        {A_ABORT_PDU_RCV, STATE13, AA_2, STATE1, "", "", NULL}},

    {
        {TRANS_CONN_CLOSED, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE2, AA_5, STATE1, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE3, AA_4, STATE1, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE4, AA_4, STATE1, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE5, AA_4, STATE1, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE6, AA_4, STATE1, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE7, AA_4, STATE1, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE8, AA_4, STATE1, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE9, AA_4, STATE1, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE10, AA_4, STATE1, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE11, AA_4, STATE1, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE12, AA_4, STATE1, "", "", NULL},
        {TRANS_CONN_CLOSED, STATE13, AR_5, STATE1, "", "", NULL}},

    {
        {ARTIM_TIMER_EXPIRED, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {ARTIM_TIMER_EXPIRED, STATE2, AA_2T, STATE1, "", "", NULL},
        {ARTIM_TIMER_EXPIRED, STATE3, NOACTION, NOSTATE, "", "", NULL},
        {ARTIM_TIMER_EXPIRED, STATE4, NOACTION, NOSTATE, "", "", NULL},

        // DICOM part 8 does not define an action and state for the
        // situation where a timeout occurs while we are waiting for an
        // incoming A-ASSOCIATE-AC or A-ASSOCIATE-RJ. We close the transport
        // connection, return an error code indicating a timeout,
        // and reset the FSM to idle state (STATE1).
        {ARTIM_TIMER_EXPIRED, STATE5, AA_2T, STATE1, "", "", NULL},

        {ARTIM_TIMER_EXPIRED, STATE6, NOACTION, NOSTATE, "", "", NULL},

        // DICOM part 8 does not define an action and state for the
        // situation where a timeout occurs while we are waiting for an
        // incoming A-RELEASE-RSP. We close the transport
        // connection, return an error code indicating a timeout,
        // and reset the FSM to idle state (STATE1).
        {ARTIM_TIMER_EXPIRED, STATE7, AA_2T, STATE1, "", "", NULL},

        {ARTIM_TIMER_EXPIRED, STATE8, NOACTION, NOSTATE, "", "", NULL},
        {ARTIM_TIMER_EXPIRED, STATE9, NOACTION, NOSTATE, "", "", NULL},
        {ARTIM_TIMER_EXPIRED, STATE10, NOACTION, NOSTATE, "", "", NULL},
        {ARTIM_TIMER_EXPIRED, STATE11, NOACTION, NOSTATE, "", "", NULL},
        {ARTIM_TIMER_EXPIRED, STATE12, NOACTION, NOSTATE, "", "", NULL},
        {ARTIM_TIMER_EXPIRED, STATE13, AA_2, STATE1, "", "", NULL}},

    {
        {INVALID_PDU, STATE1, NOACTION, NOSTATE, "", "", NULL},
        {INVALID_PDU, STATE2, AA_1, STATE13, "", "", NULL},
        {INVALID_PDU, STATE3, AA_8, STATE13, "", "", NULL},
        {INVALID_PDU, STATE4, NOACTION, NOSTATE, "", "", NULL},
        {INVALID_PDU, STATE5, AA_8, STATE13, "", "", NULL},
        {INVALID_PDU, STATE6, AA_8, STATE13, "", "", NULL},
        {INVALID_PDU, STATE7, AA_8, STATE13, "", "", NULL},
        {INVALID_PDU, STATE8, AA_8, STATE13, "", "", NULL},
        {INVALID_PDU, STATE9, AA_8, STATE13, "", "", NULL},
        {INVALID_PDU, STATE10, AA_8, STATE13, "", "", NULL},
        {INVALID_PDU, STATE11, AA_8, STATE13, "", "", NULL},
        {INVALID_PDU, STATE12, AA_8, STATE13, "", "", NULL},
        {INVALID_PDU, STATE13, AA_7, STATE13, "", "", NULL}}
};


/* Dul_InitializeFSM
**
** Purpose:
**      Initialize the DUL finite state machine by filling in addresses of
**      functions.
**
** Parameter Dictionary:
**      None
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_InitializeFSM()
{
    unsigned long
        l_index,
        idx2;
    FSM_ENTRY
        * stateEntries;

    stateEntries = (FSM_ENTRY *) StateTable;
    for (l_index = 0; l_index < DUL_NUMBER_OF_EVENTS * DUL_NUMBER_OF_STATES; l_index++) {
        if (stateEntries[l_index].action != NOACTION) {
            for (idx2 = 0; idx2 < DIM_OF(FSM_FunctionTable) &&
                 stateEntries[l_index].actionFunction == NULL; idx2++)
                if (stateEntries[l_index].action == FSM_FunctionTable[idx2].action) {
                    stateEntries[l_index].actionFunction =
                        FSM_FunctionTable[idx2].actionFunction;
                    (void) sprintf(stateEntries[l_index].actionName, "%.*s",
                                 (int)(sizeof(stateEntries[l_index].actionName) - 1),
                                   FSM_FunctionTable[idx2].actionName);
                }
        }
        for (idx2 = 0; idx2 < DIM_OF(Event_Table) &&
             strlen(stateEntries[l_index].eventName) == 0; idx2++) {
            if (stateEntries[l_index].event == Event_Table[idx2].event)
                (void) sprintf(stateEntries[l_index].eventName, "%.*s",
                               (int)(sizeof(stateEntries[l_index].eventName) - 1),
                               Event_Table[idx2].eventName);
        }
    }

    return EC_Normal;
}



/* PRV_StateMachine
**
** Purpose:
**      Execute the action function, given the current state and the event.
**
** Parameter Dictionary:
**      network         Handle to the network environment
**      association     Handle to the Association
**      event           The event that will trigger this action
**      state           Current state of the finite state machine.
**      params          Service parameters describing this Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
PRV_StateMachine(PRIVATE_NETWORKKEY ** network,
                 PRIVATE_ASSOCIATIONKEY ** association, int event, int state,
                 void *params)
{
    FSM_ENTRY
        * entry;

    /* check if the given event is valid, if not return an error */
    if (event < 0 || event >= DUL_NUMBER_OF_EVENTS)
    {
      char buf1[256];
      sprintf(buf1, "DUL Finite State Machine Error: Bad event, state %d event %d", state, event);
      return makeDcmnetCondition(DULC_FSMERROR, OF_error, buf1);
    }

    /* check if the given state is valid, if not return an error */
    if (state < 1 || state > DUL_NUMBER_OF_STATES)
    {
      char buf1[256];
      sprintf(buf1, "DUL Finite State Machine Error: Bad state, state %d event %d", state, event);
      return makeDcmnetCondition(DULC_FSMERROR, OF_error, buf1);
    }

    /* depending on the given event and state, determine the state table's entry (the state */
    /* table implements the state transition table of DICOM's Upper Layer State Machine which */
    /* in turn implements the DICOM upper layer protocol) (see DICOM standard (year 2000) part */
    /* 8, section 9) (or the corresponding section in a later version of the standard) */
    entry = &StateTable[event][state - 1];

    /* dump information if required */
    DCMNET_TRACE("DUL  FSM Table: State: " << state << " Event: " << event << OFendl
            << "DUL  Event:  " << entry->eventName << OFendl
            << "DUL  Action: " << entry->actionName);

    /* if the state table's entry specifies an action function, execute this function and return */
    /* it's result value. If there is no action function defined, return a corresponding error. */
    if (entry->actionFunction != NULL)
        return entry->actionFunction(network, association, entry->nextState, params);
    else
    {
      char buf1[256];
      sprintf(buf1, "DUL Finite State Machine Error: No action defined, state %d event %d", state, event);
      return makeDcmnetCondition(DULC_FSMERROR, OF_error, buf1);
    }
}

/* ============================================================
**
**  Private functions (local to this module) defined below.
*/

/* AE_1_TransportConnect
**
** Purpose:
**      Issue a TRANSPORT_CONNECT request primitive to local transport
**      service.
**
** Parameter Dictionary:
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AE_1_TransportConnect(PRIVATE_NETWORKKEY ** network,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params)
{
    DUL_ASSOCIATESERVICEPARAMETERS
    * service;
    OFCondition cond = EC_Normal;

    service = (DUL_ASSOCIATESERVICEPARAMETERS *) params;
    clearPDUCache(association);
    cond = requestAssociationTCP(network, service, association);
    (*association)->protocolState = nextState;
    return cond;
}

/* AE_2_SendAssociateRQPDU
**
** Purpose:
**      Send A-ASSOCIATE-RQ PDU.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AE_2_SendAssociateRQPDU(PRIVATE_NETWORKKEY ** network,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params)
{
    DUL_ASSOCIATESERVICEPARAMETERS
    * service;
    OFCondition cond = EC_Normal;

    service = (DUL_ASSOCIATESERVICEPARAMETERS *) params;

    cond = sendAssociationRQTCP(network, service, association);
    (*association)->protocolState = nextState;
    return cond;
}


/* AE_3_AssociateConfirmationAccept
**
** Purpose:
**      Issue an A-ASSOCIATE confirmation (Accept) primitive
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AE_3_AssociateConfirmationAccept(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params)
{
    DUL_ASSOCIATESERVICEPARAMETERS
    * service;
    unsigned char
        * buffer = NULL,
        pduType,
        pduReserve;
    unsigned long
        pduLength;
    PRV_ASSOCIATEPDU
        assoc;
    PRV_PRESENTATIONCONTEXTITEM
        * prvCtx;
    DUL_PRESENTATIONCONTEXT
        * userPresentationCtx,
        * requestedPresentationCtx;
    DUL_SUBITEM
        * subItem;
    PRV_SCUSCPROLE
        * scuscpRole;

    service = (DUL_ASSOCIATESERVICEPARAMETERS *) params;
    OFCondition cond = readPDU(association, DUL_BLOCK, 0, &buffer, &pduType, &pduReserve, &pduLength);

    if (cond.bad())
    {
       if (buffer) free(buffer);
       return cond;
    }

    /* cond is good so we know that buffer exists */

    DCMNET_DEBUG(dump_pdu("Associate Accept", buffer, pduLength + 6));

    if (pduType == DUL_TYPEASSOCIATEAC)
    {
        if ((*association)->associatePDUFlag)
        {
          // copy A-ASSOCIATE-AC PDU
          (*association)->associatePDU = new char[pduLength+6];
          if ((*association)->associatePDU)
          {
            memcpy((*association)->associatePDU, buffer, (size_t) pduLength+6);
            (*association)->associatePDULength = pduLength+6;
          }
        }

        cond = parseAssociate(buffer, pduLength, &assoc);
        free(buffer);
        if (cond.bad()) return makeDcmnetSubCondition(DULC_ILLEGALPDU, OF_error, "DUL Illegal or ill-formed PDU", cond);

        OFStandard::strlcpy(service->respondingAPTitle, assoc.calledAPTitle, sizeof(service->respondingAPTitle));
        OFStandard::strlcpy(service->callingAPTitle, assoc.callingAPTitle, sizeof(service->callingAPTitle));
        OFStandard::strlcpy(service->applicationContextName, assoc.applicationContext.data, sizeof(service->applicationContextName));

        if ((service->acceptedPresentationContext = LST_Create()) == NULL) return EC_MemoryExhausted;

        prvCtx = (PRV_PRESENTATIONCONTEXTITEM*)LST_Head(&assoc.presentationContextList);
        if (prvCtx != NULL)
            (void) LST_Position(&assoc.presentationContextList, (LST_NODE*)prvCtx);
        while (prvCtx != NULL) {
            userPresentationCtx = (DUL_PRESENTATIONCONTEXT*)malloc(sizeof(DUL_PRESENTATIONCONTEXT));
            if (userPresentationCtx == NULL) return EC_MemoryExhausted;

            (void) memset(userPresentationCtx, 0, sizeof(DUL_PRESENTATIONCONTEXT));
            userPresentationCtx->result = prvCtx->result;
            userPresentationCtx->presentationContextID = prvCtx->contextID;
            userPresentationCtx->proposedTransferSyntax = NULL;
            requestedPresentationCtx = findPresentationCtx(
                 &service->requestedPresentationContext, prvCtx->contextID);
            if (requestedPresentationCtx != NULL) {
                OFStandard::strlcpy(userPresentationCtx->abstractSyntax,
                    requestedPresentationCtx->abstractSyntax,
                    sizeof(userPresentationCtx->abstractSyntax));
                userPresentationCtx->proposedSCRole =
                    requestedPresentationCtx->proposedSCRole;
            }
            userPresentationCtx->acceptedSCRole = DUL_SC_ROLE_DEFAULT;
            scuscpRole = findSCUSCPRole(&assoc.userInfo.SCUSCPRoleList,
                                        userPresentationCtx->abstractSyntax);
            if (scuscpRole != NULL) {
                if ((scuscpRole->SCURole == 0) && (scuscpRole->SCPRole == 0))
                    userPresentationCtx->acceptedSCRole = DUL_SC_ROLE_NONE;
                else if ((scuscpRole->SCURole == 1) && (scuscpRole->SCPRole == 1))
                    userPresentationCtx->acceptedSCRole = DUL_SC_ROLE_SCUSCP;
                else if (scuscpRole->SCURole == 1)
                    userPresentationCtx->acceptedSCRole = DUL_SC_ROLE_SCU;
                else  // SCPRole == 1
                    userPresentationCtx->acceptedSCRole = DUL_SC_ROLE_SCP;
            }
            if (prvCtx->transferSyntaxList == NULL)
            {
              char buf1[256];
              sprintf(buf1, "DUL Peer supplied illegal number of transfer syntaxes (%d)", 0);
              free(userPresentationCtx);
              return makeDcmnetCondition(DULC_PEERILLEGALXFERSYNTAXCOUNT, OF_error, buf1);
            }

            if ((prvCtx->result == DUL_PRESENTATION_ACCEPT) && (LST_Count(&prvCtx->transferSyntaxList) != 1))
            {
              char buf2[256];
              sprintf(buf2, "DUL Peer supplied illegal number of transfer syntaxes (%ld)", LST_Count(&prvCtx->transferSyntaxList));
              free(userPresentationCtx);
              return makeDcmnetCondition(DULC_PEERILLEGALXFERSYNTAXCOUNT, OF_error, buf2);
            }
            subItem = (DUL_SUBITEM*)LST_Head(&prvCtx->transferSyntaxList);
            if (subItem != NULL)
                OFStandard::strlcpy(userPresentationCtx->acceptedTransferSyntax,
                              subItem->data, sizeof(userPresentationCtx->acceptedTransferSyntax));
            LST_Enqueue(&service->acceptedPresentationContext, (LST_NODE*)userPresentationCtx);

            prvCtx = (PRV_PRESENTATIONCONTEXTITEM*)LST_Next(&assoc.presentationContextList);

        }

        /* extended negotiation */
        if (assoc.userInfo.extNegList != NULL) {
            service->acceptedExtNegList = new SOPClassExtendedNegotiationSubItemList;
            if (service->acceptedExtNegList == NULL)  return EC_MemoryExhausted;
            appendList(*assoc.userInfo.extNegList, *service->acceptedExtNegList);
        }

        /* user identity negotiation */
        if (assoc.userInfo.usrIdent != NULL) {
          service->ackUserIdentNeg =
            new UserIdentityNegotiationSubItemAC( *(OFstatic_cast(UserIdentityNegotiationSubItemAC*, assoc.userInfo.usrIdent)));
          if (service->ackUserIdentNeg == NULL)  return EC_MemoryExhausted;

        }

        destroyPresentationContextList(&assoc.presentationContextList);
        destroyUserInformationLists(&assoc.userInfo);
        service->peerMaxPDU = assoc.userInfo.maxLength.maxLength;
        (*association)->maxPDV = assoc.userInfo.maxLength.maxLength;
        (*association)->maxPDVAcceptor =
            assoc.userInfo.maxLength.maxLength;
        OFStandard::strlcpy(service->calledImplementationClassUID,
               assoc.userInfo.implementationClassUID.data, DICOM_UI_LENGTH + 1);
        OFStandard::strlcpy(service->calledImplementationVersionName,
               assoc.userInfo.implementationVersionName.data, 16 + 1);

        (*association)->associationState = DUL_ASSOC_ESTABLISHED;
        (*association)->protocolState = nextState;
        return EC_Normal;
    }
    return DUL_UNEXPECTEDPDU;
}

/* AE_4_AssociateConfirmationReject
**
** Purpose:
**      Issue A-ASSOCIATE confirmation reject primitive and close transport
**      connection.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AE_4_AssociateConfirmationReject(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params)
{
    DUL_ASSOCIATESERVICEPARAMETERS
    * service;
    unsigned char
        buffer[128],
        pduType,
        pduReserve;
    unsigned long
        pduLength;

    service = (DUL_ASSOCIATESERVICEPARAMETERS *) params;
    OFCondition cond = readPDUBody(association, DUL_BLOCK, 0, buffer, sizeof(buffer),
                       &pduType, &pduReserve, &pduLength);
    if (cond.bad())
        return cond;

    if (pduType == DUL_TYPEASSOCIATERJ) {
        service->result = buffer[1];
        service->resultSource = buffer[2];
        service->diagnostic = buffer[3];
        (*association)->protocolState = nextState;
        closeTransport(association);
        cond = DUL_ASSOCIATIONREJECTED;
    } else cond = DUL_UNEXPECTEDPDU;

    return cond;
}


/* AE_5_TransportConnectResponse
**
** Purpose:
**      Issue Transport connection response primitive and start ARTIM timer.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:

**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AE_5_TransportConnectResponse(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    clearPDUCache(association);
    (*association)->protocolState = nextState;

    /* Start the timer (?) */

    return EC_Normal;
}



/* AE_6_ExamineAssociateRequest
**
** Purpose:
**      Stop ARTIM timer and if A-ASSOCIATE-RQ acceptable by service-provider,
**      issue A-ASSOCIATE indication primitive else issue A-ASSOCIATE
**      indication primitive.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AE_6_ExamineAssociateRequest(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int /*nextState*/, void *params)
{
    DUL_ASSOCIATESERVICEPARAMETERS
    * service;
    unsigned char
        *buffer=NULL,
        pduType,
        pduReserve;
    unsigned long
        pduLength;
    PRV_ASSOCIATEPDU
        assoc;

    (*association)->timerStart = 0;
    service = (DUL_ASSOCIATESERVICEPARAMETERS *) params;
    OFCondition cond = readPDU(association, DUL_BLOCK, 0, &buffer,
                   &pduType, &pduReserve, &pduLength);

    if (cond.bad())
    {
       if (buffer) free(buffer);
       return cond;
    }

    /* cond is good so we know that buffer exists */

    if (pduType == DUL_TYPEASSOCIATERQ)
    {
        if ((*association)->associatePDUFlag)
        {
          // copy A-ASSOCIATE-RQ PDU
          (*association)->associatePDU = new char[pduLength+6];
          if ((*association)->associatePDU)
          {
            memcpy((*association)->associatePDU, buffer, (size_t) pduLength+6);
            (*association)->associatePDULength = pduLength+6;
          }
        }

        DCMNET_DEBUG(dump_pdu("Associate Request", buffer, pduLength + 6));
        cond = parseAssociate(buffer, pduLength, &assoc);
        free(buffer);
        buffer = NULL;

        if (cond.bad()) {
            if (cond == DUL_UNSUPPORTEDPEERPROTOCOL)    /* Make it look OK */
                (*association)->protocolState = STATE3;
            return cond;
        }
        OFStandard::strlcpy(service->calledAPTitle, assoc.calledAPTitle, sizeof(service->calledAPTitle));
        OFStandard::strlcpy(service->callingAPTitle, assoc.callingAPTitle, sizeof(service->callingAPTitle));
        OFStandard::strlcpy(service->applicationContextName, assoc.applicationContext.data, sizeof(service->applicationContextName));

        if ((service->requestedPresentationContext = LST_Create()) == NULL) return EC_MemoryExhausted;
        if (translatePresentationContextList(&assoc.presentationContextList,
                                             &assoc.userInfo.SCUSCPRoleList,
                                             &service->requestedPresentationContext).bad())
        {
            return DUL_PCTRANSLATIONFAILURE;
        }

        /* extended negotiation */
        if (assoc.userInfo.extNegList != NULL) {
            service->requestedExtNegList = new SOPClassExtendedNegotiationSubItemList;
            if (service->requestedExtNegList == NULL) return EC_MemoryExhausted;
            appendList(*assoc.userInfo.extNegList, *service->requestedExtNegList);
        }

        /* user identity negotiation: Remember request values in association parameters (copy)*/
        if (assoc.userInfo.usrIdent != NULL) {
          service->reqUserIdentNeg = new UserIdentityNegotiationSubItemRQ();
          if (service->reqUserIdentNeg == NULL) return EC_MemoryExhausted;
            *(service->reqUserIdentNeg) = *(OFstatic_cast(UserIdentityNegotiationSubItemRQ*,assoc.userInfo.usrIdent));
        }

        service->peerMaxPDU = assoc.userInfo.maxLength.maxLength;
        (*association)->maxPDV = assoc.userInfo.maxLength.maxLength;
        (*association)->maxPDVRequestor =
            assoc.userInfo.maxLength.maxLength;
        OFStandard::strlcpy(service->callingImplementationClassUID,
               assoc.userInfo.implementationClassUID.data, DICOM_UI_LENGTH + 1);
        OFStandard::strlcpy(service->callingImplementationVersionName,
               assoc.userInfo.implementationVersionName.data, 16 + 1);
        (*association)->associationState = DUL_ASSOC_ESTABLISHED;

        destroyPresentationContextList(&assoc.presentationContextList);
        destroyUserInformationLists(&assoc.userInfo);

        /* If this PDU is ok with us */
        (*association)->protocolState = STATE3;

        return EC_Normal;
    }
    return DUL_UNEXPECTEDPDU;
}


/* AE_7_SendAssociateAC
**
** Purpose:
**      Send A-ASSOCIATE-AC PDU.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AE_7_SendAssociateAC(PRIVATE_NETWORKKEY ** network,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params)
{
    DUL_ASSOCIATESERVICEPARAMETERS
    * service;
    OFCondition cond = EC_Normal;

    service = (DUL_ASSOCIATESERVICEPARAMETERS *) params;
    cond = sendAssociationACTCP(network, service, association);
    (*association)->protocolState = nextState;
    return cond;
}


/* AE_8_SendAssociateRJ
**
** Purpose:
**      Send A-ASSOCIATE-RJ PDU and start ARTIM timer.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AE_8_SendAssociateRJ(PRIVATE_NETWORKKEY ** network,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params)
{
    DUL_ABORTITEMS
    * abortItems;
    OFCondition cond = EC_Normal;

    abortItems = (DUL_ABORTITEMS *) params;
    cond = sendAssociationRJTCP(network, abortItems, association);
    (*association)->protocolState = nextState;

    /* Start the timer (?) */

    return cond;
}

/* DT_1_SendPData
**
** Purpose:
**      Send P-DATA-TF PDU
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
DT_1_SendPData(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params)
{
    OFCondition cond = EC_Normal;
    DUL_PDVLIST
        * pdvList;

    /* Remember that params used to be a variable of type DUL_PDVLIST * and restore this variable */
    pdvList = (DUL_PDVLIST *) params;

    /* send the data which is contained in pdvList over the network */
    cond = sendPDataTCP(association, pdvList);

    /* and go to the next specified state */
    (*association)->protocolState = nextState;

    /* return return value */
    return cond;
}

/* DT_2_IndicatePData
**
** Purpose:
**      Send P-DATA indication primitive.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
DT_2_IndicatePData(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    unsigned char
        pduType,
        pduReserved;
    unsigned long
        pduLength,
        pdvLength,
        pdvCount;
    long
        length;
    unsigned char
       *p;

    /* determine the finite state machine's next state */
    (*association)->protocolState = nextState;

    /* read PDU body information from the incoming socket stream. In case the incoming */
    /* PDU's header information has not yet been read, also read this information. */
    OFCondition cond = readPDUBody(association, DUL_BLOCK, 0,
                       (*association)->fragmentBuffer,
                       (*association)->fragmentBufferLength,
                       &pduType, &pduReserved, &pduLength);

    /* return error if there was one */
    if (cond.bad())
        return cond;

    /* count the amount of PDVs in the current PDU */
    length = pduLength;                     //set length to the PDU's length
    pdvCount = 0;                           //set counter variable to 0
    p = (*association)->fragmentBuffer;     //set p to the buffer which contains the PDU's PDVs
    while (length >= 4) {                   //as long as length is at least 4 (= a length field can be read)
        EXTRACT_LONG_BIG(p, pdvLength);     //determine the length of the current PDV (the PDV p points to)
        p += 4 + pdvLength;                 //move p so that it points to the next PDV (move p 4 bytes over the length field plus the amount of bytes which is captured in the PDV's length field (over presentation context.Id, message information header and data fragment))
        length -= 4 + pdvLength;            //update length (i.e. determine the length of the buffer which has not been evaluated yet.)
        pdvCount++;                         //increase counter by one, since we've found another PDV

        // There must be at least a presentation context ID and a message
        // control header (see below), else the calculation pdvLength - 2 below
        // will underflow.
        if (pdvLength < 2)
        {
           char buf[256];
           sprintf(buf, "PDV with invalid length %lu encountered. This probably indicates a malformed P DATA PDU.", pdvLength);
           return makeDcmnetCondition(DULC_ILLEGALPDULENGTH, OF_error, buf);
        }
    }

    /* if after having counted the PDVs the length variable does not equal */
    /* 0, the PDV lengths did not add up correctly. Something is fishy. */
    if (length != 0)
    {
       char buf[256];
       sprintf(buf, "PDV lengths don't add up correctly: %d PDVs. This probably indicates a malformed P-DATA PDU. PDU type is %02x.", (int)pdvCount, (unsigned int) pduType);
       return makeDcmnetCondition(DULC_ILLEGALPDU, OF_error, buf);
    }

    /* let the the association indicate how many PDVs are contained in the PDU */
    (*association)->pdvCount = (int)pdvCount;

    /* if at least one PDV is contained in the PDU, the association's pdvIndex has to be set to 0 */
    if (pdvCount > 0)
        (*association)->pdvIndex = 0;
    else
    {
        /* if there is no PDV contained in the PDU, the association's pdvIndex has to be set to -1 */
        (*association)->pdvIndex = -1;

        /* bugfix by wilkens 01/10/12: return error if PDU does not contain any PDVs: */
        /* Additionally, it is not allowed to have a PDU that does not contain any PDVs. */
        /* Hence, return an error (see DICOM standard (year 2000) part 8, section 9.3.1, */
        /* figure 9-2) (or the corresponding section in a later version of the standard) */
       char buf[256];
       sprintf(buf, "PDU without any PDVs encountered. In DT_2_IndicatePData.  This probably indicates a  malformed P DATA PDU." );
       return makeDcmnetCondition(DULC_ILLEGALPDU, OF_error, buf);
    }

    /* at this point we need to set the association's currentPDV variable so that it contains the data */
    /* of the next unprocessed PDV (currentPDV shall always contain the next unprocessed PDV's data.) */

    /* set the fragment buffer (the buffer which contains all PDVs of the current PDU) to a local variable */
    p = (*association)->fragmentBuffer;

    /* The variable (*association)->pdvPointer always points to the buffer */
    /* address where the information of the PDV which is represented by the */
    /* association's currentPDV variable can be found. Set this variable. */
    (*association)->pdvPointer = p;

    /* determine the value in the PDV length field of the next (unprocessed) PDV */
    EXTRACT_LONG_BIG(p, pdvLength);

    /* set the data fragment length in the association's currentPDV.fragmentLength variable */
    /* (we start now overwriting all the entries in (*association)->currentPDV). The actual */
    /* length of the data fragment of the next (unprocessed) PDV equals the above determined */
    /* length minus 1 byte (for the presentation context ID) and minus another byte (for the */
    /* message control header). */
    (*association)->currentPDV.fragmentLength = pdvLength - 2;

    /* set the presentation context ID value in the association's currentPDV.presentationContextID */
    /* variable. This value is 1 byte wide and contained in the 5th byte of p (the first four bytes */
    /* contain the PDV length value, the fifth byte the presentation context ID value) */
    (*association)->currentPDV.presentationContextID = p[4];

    /* now determine if the next (unprocessed) PDV contains the last fragment of a data set or DIMSE */
    /* command and if the next (unprocessed) PDV is a data set PDV or command PDV. This information */
    /* is captured in the 6th byte of p: */
    unsigned char u = p[5];
    if (u & 2)
        (*association)->currentPDV.lastPDV = OFTrue;            //if bit 1 of the message control header is 1, this fragment does contain the last fragment of a data set or command
    else
        (*association)->currentPDV.lastPDV = OFFalse;           //if bit 1 of the message control header is 0, this fragment does not contain the last fragment of a data set or command

    if (u & 1)
        (*association)->currentPDV.pdvType = DUL_COMMANDPDV;    //if bit 0 of the message control header is 1, this is a command PDV
    else
        (*association)->currentPDV.pdvType = DUL_DATASETPDV;    //if bit 0 of the message control header is 0, this is a data set PDV

    /* now assign the data fragment of the next (unprocessed) PDV to the association's */
    /* currentPDV.data variable. The fragment starts 6 bytes to the right of the address */
    /* p currently points to. */
    (*association)->currentPDV.data = p + 6;

    /* return ok */
    return DUL_PDATAPDUARRIVED;
}


/* AR_1_SendReleaseRQ
**
** Purpose:
**      Send A-RELEASE-RQ PDU.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AR_1_SendReleaseRQ(PRIVATE_NETWORKKEY ** /* network */,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    OFCondition cond = EC_Normal;

    cond = sendReleaseRQTCP(association);
    (*association)->protocolState = nextState;
    return cond;
}

/* AR_2_IndicateRelease
**
** Purpose:
**      Issue A-RELEASE indication primitive.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AR_2_IndicateRelease(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    unsigned char
        buffer[128],
        pduType,
        pduReserve;
    unsigned long
        pduLength;

    /* Read remaining unimportant bytes of the A-RELEASE-RQ PDU */
    OFCondition cond = readPDUBody(association, DUL_BLOCK, 0, buffer, sizeof(buffer),
                       &pduType, &pduReserve, &pduLength);
    if (cond.bad())
        return cond;

    if (pduLength == 4)
    {
      unsigned long mode = buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];
      if ((*association)->modeCallback && !((mode & DUL_MAXPDUCOMPAT) ^ DUL_DULCOMPAT))
      {
        (*association)->modeCallback->callback(mode);
      }
    }

    (*association)->protocolState = nextState;
    return DUL_PEERREQUESTEDRELEASE;
}

/* AR_3_ConfirmRelease
**
** Purpose:
**      Issue A-RELEASE confirmation primitive and close transport connection.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AR_3_ConfirmRelease(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    unsigned char
        buffer[128],
        pduType,
        pduReserve;
    unsigned long
        pduLength;

    /* Read remaining unimportant bytes of the A-RELEASE-RSP PDU */
    OFCondition cond = readPDUBody(association, DUL_BLOCK, 0, buffer, sizeof(buffer),
                       &pduType, &pduReserve, &pduLength);

    closeTransport(association);
    (*association)->protocolState = nextState;
    return cond;
}

/* AR_4_SendReleaseRP
**
** Purpose:
**      Issue A-RELEASE-RP PDU and start ARTIM timer.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AR_4_SendReleaseRP(PRIVATE_NETWORKKEY ** /* network */,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    OFCondition cond = EC_Normal;

    cond = sendReleaseRPTCP(association);
    (*association)->timerStart = time(NULL);
    (*association)->protocolState = nextState;
    return cond;
}

/* AR_5_StopARTTIMtimer
**
** Purpose:
**      Stop ARTIM timer.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:

**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AR_5_StopARTIMtimer(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int /*nextState*/, void * /*params*/)
{
    (*association)->timerStart = 0;
    return EC_Normal;
}

/* AR_6_IndicatePData
**
** Purpose:
**      Issue P-DATA indication.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AR_6_IndicatePData(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** /*association*/, int /*nextState*/, void * /*params*/)
{
    return DUL_PDATAPDUARRIVED;
}

/* AR_7_SendPData
**
** Purpose:
**      Issue P-DATA-TF PDU
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AR_7_SendPDATA(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void *params)
{
    OFCondition cond = EC_Normal;
    DUL_PDVLIST
        * pdvList;

    pdvList = (DUL_PDVLIST *) params;
    cond = sendPDataTCP(association, pdvList);
    (*association)->protocolState = nextState;
    return cond;
}

/* AR_8_IndicateARelease
**
** Purpose:
**      Issue A-RELEASE indication (release collision):
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AR_8_IndicateARelease(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int /*nextState*/, void * /*params*/)
{
/*    if (strcmp((*association)->applicationType, AE_REQUESTOR) == 0) */

    unsigned char
        buffer[128],
        pduType,
        pduReserve;
    unsigned long
        pduLength;

    /* Read remaining unimportant bytes of the A-RELEASE-RQ PDU */
    OFCondition cond = readPDUBody(association, DUL_BLOCK, 0, buffer, sizeof(buffer),
                       &pduType, &pduReserve, &pduLength);
    if (cond.bad())
        return cond;

    if ((*association)->applicationFunction == DICOM_APPLICATION_REQUESTOR)
        (*association)->protocolState = STATE9;
    else
        (*association)->protocolState = STATE10;

    return DUL_PEERREQUESTEDRELEASE;
}

/* AR_9_SendAReleaseRP
**
** Purpose:
**      Send A-RELEASE-RP PDU
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AR_9_SendAReleaseRP(PRIVATE_NETWORKKEY ** /* network */,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    OFCondition cond = sendReleaseRPTCP(association);
    (*association)->protocolState = nextState;
    return cond;
}

/* AR_10_ConfirmRelease
**
** Purpose:
**      Issue A-RELEASE confirmation primitive.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AR_10_ConfirmRelease(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    (*association)->protocolState = nextState;
    return EC_Normal;
}


/* AA_1_SendAbort
**
** Purpose:
**      Send A-ABORT PDU (service-user source) and start (or restart if
**      already started) ARTIM timer.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AA_1_SendAAbort(PRIVATE_NETWORKKEY ** /* network */,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    DUL_ABORTITEMS abortItems;

    abortItems.result = 0x00;
    abortItems.source = DUL_ABORTSERVICEUSER;
    abortItems.reason = 0x00;

    OFCondition cond = sendAbortTCP(&abortItems, association);
    (*association)->protocolState = nextState;
    (*association)->timerStart = time(NULL);
    return cond;
}

/* AA_2_CloseTransport
**
** Purpose:
**      Close transport connection.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:

**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AA_2_CloseTransport(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    (*association)->timerStart = 0;
    closeTransport(association);
    (*association)->protocolState = nextState;
    return EC_Normal;
}

/* AA_2_CloseTimeout
**
** Purpose:
**      Stop ARTIM timer.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AA_2_CloseTimeout(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    (*association)->timerStart = 0;
    closeTransport(association);
    (*association)->protocolState = nextState;
    return DUL_READTIMEOUT;
}


/* AA_3_IndicatePeerAborted
**
** Purpose:
**      If (service-user initiated abort)
**         - issue A-ABORT indication and close transport connection
**      otherwise (service provider initiated abort)
**         - issue A-P-ABORT indication and close transport connection.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AA_3_IndicatePeerAborted(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    unsigned char
        buffer[128],
        pduType,
        pduReserve;
    unsigned long
        pduLength;

    /* Read remaining unimportant bytes of the A-ABORT PDU */
    OFCondition cond = readPDUBody(association, DUL_BLOCK, 0, buffer, sizeof(buffer),
                       &pduType, &pduReserve, &pduLength);
    if (cond.bad()) return cond;

    if (pduLength == 4)
    {
      unsigned long mode = pduReserve << 24 | buffer[0] << 16 | buffer[1] << 8 | buffer[3];
      if ((*association)->modeCallback && !((mode & DUL_MAXPDUCOMPAT) ^ DUL_DULCOMPAT))
      {
        (*association)->modeCallback->callback(mode);
      }
    }

    closeTransport(association);
    (*association)->protocolState = nextState;
    return DUL_PEERABORTEDASSOCIATION;
}


/* AA_4_IndicateAPAbort
**
** Purpose:
**      Issue A-P-ABORT indication primitive.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AA_4_IndicateAPAbort(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    closeTransport(association);
    (*association)->protocolState = nextState;
    return DUL_PEERABORTEDASSOCIATION;
}


/* AA_5_StopARTIMtimer
**
** Purpose:
**      Stop ARTIM timer.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AA_5_StopARTIMtimer(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    (*association)->timerStart = 0;
    (*association)->protocolState = nextState;
    return EC_Normal;
}


/* AA_6_IgnorePDU
**
** Purpose:
**      Ignore PDU
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/


static OFCondition
AA_6_IgnorePDU(PRIVATE_NETWORKKEY ** /*network*/,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    unsigned char
        buffer[1024],
        PDUType,
        PDUReserved;
    long
        PDULength;
    unsigned long
        l;

    (*association)->protocolState = nextState;
    OFCondition cond = readPDUHead(association, buffer, sizeof(buffer), DUL_NOBLOCK,
                    PRV_DEFAULTTIMEOUT, &PDUType, &PDUReserved, &l);
    if (cond.bad()) {
        return cond;
    }
    PDULength = l;
    while (PDULength > 0 && cond.good())
    {
        cond = defragmentTCP((*association)->connection,
                             DUL_NOBLOCK, (*association)->timerStart,
                   (*association)->timeout, buffer, sizeof(buffer), &l);
        if (cond.bad()) return cond;
        PDULength -= l;
    }
    return EC_Normal;
}


/* AA_7_State13SendAbort
**
** Purpose:
**      SendA-ABORT PDU
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
AA_7_State13SendAbort(PRIVATE_NETWORKKEY ** /* network */,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    DUL_ABORTITEMS abortItems;

    abortItems.result = 0x00;
    abortItems.source = DUL_ABORTSERVICEPROVIDER;
    abortItems.reason = DUL_ABORTUNEXPECTEDPDU;

    OFCondition cond = sendAbortTCP(&abortItems, association);
    (*association)->protocolState = nextState;
    return cond;
}


/* AA_8_UnrecognizedPDUSendAbort
**
** Purpose:
**      Send A-ABORT PDU (service provider source), issue an A-P-ABORT
**      indication and start timer.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      association     Handle to the Association
**      nextState       The next state to be reached from the current state
**      params          Service parameters describing the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
AA_8_UnrecognizedPDUSendAbort(PRIVATE_NETWORKKEY ** /* network */,
         PRIVATE_ASSOCIATIONKEY ** association, int nextState, void * /*params*/)
{
    DUL_ABORTITEMS abortItems;

    abortItems.result = 0x00;
    abortItems.source = DUL_ABORTSERVICEPROVIDER;
    abortItems.reason = DUL_ABORTUNEXPECTEDPDU;

    OFCondition cond = sendAbortTCP(&abortItems, association);
    (*association)->protocolState = nextState;
    (*association)->timerStart = time(0);
    return cond;
}

/* requestAssociationTCP
**
** Purpose:
**      Request a TCP Association
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      params          Service parameters describing the Association
**      association     Handle to the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/


static OFCondition
requestAssociationTCP(PRIVATE_NETWORKKEY ** network,
                      DUL_ASSOCIATESERVICEPARAMETERS * params,
                      PRIVATE_ASSOCIATIONKEY ** association)
{
    char node[128];
    int  port;
    OFSockAddr server;
#ifdef _WIN32
    SOCKET s;
#else
    int s;
#endif
    struct linger sockarg;

    if (sscanf(params->calledPresentationAddress, "%[^:]:%d", node, &port) != 2)
    {
        char buf[1024];
        sprintf(buf,"Illegal service parameter: %s", params->calledPresentationAddress);
        return makeDcmnetCondition(DULC_ILLEGALSERVICEPARAMETER, OF_error, buf);
    }

    /*
     * At least officially, gethostbyname will not accept an IP address on many
     * operating systems (e.g. Windows or FreeBSD), so we need to explicitly
     * handle the IP address case.
     */
    unsigned long addr = inet_addr(node);
    if (addr != INADDR_NONE)
    {
        // it is an IPv4 address
        server.setFamily(AF_INET);
        struct sockaddr_in *sa = server.getSockaddr_in();
        sa->sin_addr.s_addr = addr;
    }
    else
    {
        // must be a host name or an IPv6 address
        OFStandard::getAddressByHostname(node, server);
        if (server.getFamily() == 0)
        {
          char buf2[4095]; // node could be a long string
          sprintf(buf2, "Attempt to connect to unknown host: %s", node);
          return makeDcmnetCondition(DULC_UNKNOWNHOST, OF_error, buf2);
        }
    }
    server.setPort(OFstatic_cast(unsigned short, htons(port)));

    // get global connection timeout
    Sint32 connectTimeout = dcmConnectionTimeout.get();

    s = socket(server.getFamily(), SOCK_STREAM, 0);
#ifdef _WIN32
    if (s == INVALID_SOCKET)
#else
    if (s < 0)
#endif
    {
      OFString msg = "TCP Initialization Error: ";
      msg += OFStandard::getLastNetworkErrorCode().message();
      return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
    }

#ifdef HAVE_WINSOCK_H
    u_long arg = TRUE;
#else
    int flags = 0;
#endif

    if (connectTimeout >= 0)
    {
      // user has specified a timeout, switch socket to non-blocking mode
#ifdef HAVE_WINSOCK_H
      ioctlsocket(s, FIONBIO, (u_long FAR *) &arg);
#else
      flags = fcntl(s, F_GETFL, 0);
      fcntl(s, F_SETFL, O_NONBLOCK | flags);
#endif
    }

    // depending on the socket mode, connect will block or return immediately
    int rc;
    do {
        rc = connect(s, server.getSockaddr(), server.size());
    } while (rc == -1 && OFStandard::getLastNetworkErrorCode().value() == DCMNET_EINTR);

#ifdef HAVE_WINSOCK_H
    if (rc == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
#else
    if (rc < 0 && errno == EINPROGRESS)
#endif
    {
#ifndef DCMTK_HAVE_POLL
        // we're in non-blocking mode. Prepare to wait for timeout.
        fd_set fdSet;
        FD_ZERO(&fdSet);
#ifdef __MINGW32__
        // on MinGW, FD_SET expects an unsigned first argument
        FD_SET((unsigned int) s, &fdSet);
#else
        FD_SET(s, &fdSet);
#endif /* __MINGW32__ */
#endif /* DCMTK_HAVE_POLL */

        struct timeval timeout;
        timeout.tv_sec = connectTimeout;
        timeout.tv_usec = 0;

        do {
#ifdef DCMTK_HAVE_POLL
            struct pollfd pfd[] =
            {
                { s, POLLOUT, 0 }
            };
            rc = poll(pfd, 1, timeout.tv_sec*1000+(timeout.tv_usec/1000));
#else
            // the typecast is safe because Windows ignores the first select() parameter anyway
            rc = select(OFstatic_cast(int, s + 1), NULL, &fdSet, NULL, &timeout);
#endif
        } while (rc == -1 && OFStandard::getLastNetworkErrorCode().value() == DCMNET_EINTR);

        if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
        {
            DU_logSelectResult(rc);
        }

        // reset socket to blocking mode
#ifdef HAVE_WINSOCK_H
        arg = FALSE;
        ioctlsocket(s, FIONBIO, (u_long FAR *) &arg);
#else
        fcntl(s, F_SETFL, flags);
#endif
        if (rc == 0)
        {
            // timeout reached, bail out with error return code
#ifdef HAVE_WINSOCK_H
            (void) shutdown(s,  1 /* SD_SEND */);
            (void) closesocket(s);
#else
            (void) close(s);
#endif
            (*association)->networkState = NETWORK_DISCONNECTED;
            if ((*association)->connection) delete (*association)->connection;
            (*association)->connection = NULL;

            OFString msg = "TCP Initialization Error: ";
            msg += OFStandard::getLastNetworkErrorCode().message();
            msg += " (Timeout)";
            return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
  }
#ifndef HAVE_WINSOCK_H
        else if (rc > 0)
        {
            // select reports that our connection request has proceeded.
            // This could either mean success or an asynchronous error condition.
            // use getsockopt to check the socket status.
            int socketError = 0;

#ifdef HAVE_DECLARATION_SOCKLEN_T
            // some platforms (e.g. Solaris 7) declare socklen_t
            socklen_t socketErrorLen = sizeof(socketError);
#elif defined(HAVE_INTP_GETSOCKOPT)
            // some platforms (e.g. Solaris 2.5.1) prefer int
            int socketErrorLen = (int) sizeof(socketError);
#else
            // some platforms (e.g. OSF1 4.0) prefer size_t
            size_t socketErrorLen = sizeof(socketError);
#endif

            // Solaris 2.5.1 expects a char * as argument 4 of getsockopt. Most other
            // platforms expect void *, so casting to a char * should be safe.
            getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)(&socketError), &socketErrorLen);
            if (socketError)
            {
                // asynchronous error on our socket, bail out.
                (void) close(s);
                (*association)->networkState = NETWORK_DISCONNECTED;
                if ((*association)->connection) delete (*association)->connection;
                (*association)->connection = NULL;

                char buf[256];
                OFString msg = "TCP Initialization Error: ";
                msg += OFStandard::strerror(socketError, buf, sizeof(buf));
                return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
            }
        }
#endif
    }
    else
    {
        // The connect() returned without using the select(), reset the socket if needed
        if (connectTimeout >= 0)
        {
            // reset socket to blocking mode
#ifdef HAVE_WINSOCK_H
            arg = FALSE;
            ioctlsocket(s, FIONBIO, (u_long FAR *) &arg);
#else
            fcntl(s, F_SETFL, flags);
#endif
        }
    }

    if (rc < 0)
    {
        // an error other than timeout in non-blocking mode has occurred,
        // either in connect() or in select().
#ifdef HAVE_WINSOCK_H
        (void) shutdown(s,  1 /* SD_SEND */);
        (void) closesocket(s);
#else
        (void) close(s);
#endif
        (*association)->networkState = NETWORK_DISCONNECTED;
        if ((*association)->connection) delete (*association)->connection;
        (*association)->connection = NULL;

        OFString msg = "TCP Initialization Error: ";
        msg += OFStandard::getLastNetworkErrorCode().message();
        return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
    } else {
        // success - we've opened a TCP transport connection

        (*association)->networkState = NETWORK_CONNECTED;
        if ((*association)->connection) delete (*association)->connection;

        if (network && (*network) && ((*network)->networkSpecific.TCP.tLayer))
        {
          (*association)->connection = ((*network)->networkSpecific.TCP.tLayer)->createConnection(s, params->useSecureLayer);
        }
        else (*association)->connection = NULL;

        if ((*association)->connection == NULL)
        {
#ifdef HAVE_WINSOCK_H
          (void) shutdown(s,  1 /* SD_SEND */);
          (void) closesocket(s);
#else
          (void) close(s);
#endif
          (*association)->networkState = NETWORK_DISCONNECTED;

          OFString msg = "TCP Initialization Error: ";
          msg += OFStandard::getLastNetworkErrorCode().message();
          return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
        }
        sockarg.l_onoff = 0;
        sockarg.l_linger = 0;

        if (setsockopt(s, SOL_SOCKET, SO_LINGER, (char *) &sockarg, (int) sizeof(sockarg)) < 0)
        {
          OFString msg = "TCP Initialization Error: ";
          msg += OFStandard::getLastNetworkErrorCode().message();
          return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
        }
        //setTCPBufferLength(s);

        /*
         * Disable the so-called Nagle algorithm (if requested).
         * This might provide a better network performance on some systems/environments.
         * By default, the algorithm is not disabled unless DISABLE_NAGLE_ALGORITHM is defined.
         * The default behavior can be changed by setting the environment variable TCP_NODELAY.
         */

#ifdef DONT_DISABLE_NAGLE_ALGORITHM
#warning The macro DONT_DISABLE_NAGLE_ALGORITHM is not supported anymore. See "macros.txt" for details.
#endif

#ifdef DISABLE_NAGLE_ALGORITHM
        int tcpNoDelay = 1; // disable
#else
        int tcpNoDelay = 0; // don't disable
#endif
        char* tcpNoDelayString = NULL;
        DCMNET_TRACE("checking whether environment variable TCP_NODELAY is set");
        if ((tcpNoDelayString = getenv("TCP_NODELAY")) != NULL)
        {
          if (sscanf(tcpNoDelayString, "%d", &tcpNoDelay) != 1)
          {
            DCMNET_WARN("DULFSM: cannot parse environment variable TCP_NODELAY=" << tcpNoDelayString);
          }
        } else
          DCMNET_TRACE("  environment variable TCP_NODELAY not set, using the default value (" << tcpNoDelay << ")");
        if (tcpNoDelay) {
#ifdef DISABLE_NAGLE_ALGORITHM
          DCMNET_DEBUG("DULFSM: disabling Nagle algorithm as defined at compilation time (DISABLE_NAGLE_ALGORITHM)");
#else
          DCMNET_DEBUG("DULFSM: disabling Nagle algorithm as requested at runtime (TCP_NODELAY=" << tcpNoDelayString << ")");
#endif
          if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char*)&tcpNoDelay, sizeof(tcpNoDelay)) < 0)
          {
            OFString msg = "TCP Initialization Error: ";
            msg += OFStandard::getLastNetworkErrorCode().message();
            return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
          }
#ifdef DISABLE_NAGLE_ALGORITHM
        } else {
          DCMNET_DEBUG("DULFSM: do not disable Nagle algorithm as requested at runtime (TCP_NODELAY=" << tcpNoDelayString << ")");
#endif
        }

       DcmTransportLayerStatus tcsStatus;
       if (TCS_ok != (tcsStatus = (*association)->connection->clientSideHandshake()))
       {
         DCMNET_ERROR("TLS client handshake failed");
         OFString msg = "DUL secure transport layer: ";
         msg += (*association)->connection->errorString(tcsStatus);
         return makeDcmnetCondition(DULC_TLSERROR, OF_error, msg.c_str());
       }
       return EC_Normal;
    }
}


/* sendAssociationRQTCP
**
** Purpose:
**      Send a TCP association request PDU.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      params          Service parameters describing the Association
**      association     Handle to the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
sendAssociationRQTCP(PRIVATE_NETWORKKEY ** /*network*/,
                     DUL_ASSOCIATESERVICEPARAMETERS * params,
                     PRIVATE_ASSOCIATIONKEY ** association)
{
    PRV_ASSOCIATEPDU
    associateRequest;
    unsigned char
        buffer[4096],
       *b;
    unsigned long
        length;
    int
        nbytes;

    OFBitmanipTemplate<char>::zeroMem((char *)&associateRequest, sizeof(PRV_ASSOCIATEPDU)); // initialize PDU
    // associateRequest.presentationContextList = NULL;
    OFCondition cond = constructAssociatePDU(params, DUL_TYPEASSOCIATERQ,
                                 &associateRequest);
    if (cond.bad())
    {
        DCMNET_ERROR(cond.text());
        return cond;
    }
    if (associateRequest.length + 6 <= sizeof(buffer))
        b = buffer;
    else {
        b = (unsigned char*)malloc(size_t(associateRequest.length + 6));
        if (b == NULL)  return EC_MemoryExhausted;
    }
    cond = streamAssociatePDU(&associateRequest, b,
                              associateRequest.length + 6, &length);

    if ((*association)->associatePDUFlag)
    {
      // copy A-ASSOCIATE-RQ PDU
      (*association)->associatePDU = new char[length];
      if ((*association)->associatePDU)
      {
        memcpy((*association)->associatePDU, b, (size_t) length);
        (*association)->associatePDULength = length;
      }
    }

    destroyPresentationContextList(&associateRequest.presentationContextList);
    destroyUserInformationLists(&associateRequest.userInfo);
    if (cond.bad())
        return cond;

    do {
      nbytes = (*association)->connection ? (*association)->connection->write((char*)b, size_t(associateRequest.length + 6)) : 0;
    } while (nbytes == -1 && OFStandard::getLastNetworkErrorCode().value() == DCMNET_EINTR);
    if ((unsigned long) nbytes != associateRequest.length + 6)
    {
      OFString msg = "TCP I/O Error (";
      msg += OFStandard::getLastNetworkErrorCode().message();
      msg += ") occurred in routine: sendAssociationRQTCP";
      return makeDcmnetCondition(DULC_TCPIOERROR, OF_error, msg.c_str());
    }
    if (b != buffer) free(b);
    return EC_Normal;
}

/* sendAssociationACTCP
**
** Purpose:
**      Send an Association ACK on a TCP connection
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      params          Service parameters describing the Association
**      association     Handle to the Association
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
sendAssociationACTCP(PRIVATE_NETWORKKEY ** /*network*/,
                     DUL_ASSOCIATESERVICEPARAMETERS * params,
                     PRIVATE_ASSOCIATIONKEY ** association)
{
    PRV_ASSOCIATEPDU
    associateReply;
    unsigned char
        buffer[4096],
       *b;
    unsigned long length = 0;
    int nbytes;
    DUL_ASSOCIATESERVICEPARAMETERS localService;

    OFBitmanipTemplate<char>::zeroMem((char *)&associateReply, sizeof(PRV_ASSOCIATEPDU)); // initialize PDU
    // associateReply.presentationContextList = NULL;

    localService = *params;
    OFCondition cond = constructAssociatePDU(&localService, DUL_TYPEASSOCIATEAC,
                                 &associateReply);
    if (cond.bad())
    {
        DCMNET_ERROR(cond.text());
        return cond;
    }

    // we need to have length+6 bytes in buffer, but 4 bytes reserve won't hurt
    if (associateReply.length + 10 <= sizeof(buffer)) b = buffer;
    else {
        b = (unsigned char*)malloc(size_t(associateReply.length + 10));
        if (b == NULL)  return EC_MemoryExhausted;
    }
    cond = streamAssociatePDU(&associateReply, b,
                              associateReply.length + 10, &length);

    if ((*association)->associatePDUFlag)
    {
      // copy A-ASSOCIATE-AC PDU
      (*association)->associatePDU = new char[length];
      if ((*association)->associatePDU)
      {
        memcpy((*association)->associatePDU, b, (size_t) length);
        (*association)->associatePDULength = length;
      }
    }

    destroyPresentationContextList(&associateReply.presentationContextList);
    destroyUserInformationLists(&associateReply.userInfo);

    if (cond.bad()) return cond;

    do {
      nbytes = (*association)->connection ? (*association)->connection->write((char*)b, size_t(associateReply.length + 6)) : 0;
    } while (nbytes == -1 && OFStandard::getLastNetworkErrorCode().value() == DCMNET_EINTR);
    if ((unsigned long) nbytes != associateReply.length + 6)
    {
      OFString msg = "TCP I/O Error (";
      msg += OFStandard::getLastNetworkErrorCode().message();
      msg += ") occurred in routine: sendAssociationACTCP";
      return makeDcmnetCondition(DULC_TCPIOERROR, OF_error, msg.c_str());
    }
    if (b != buffer) free(b);
    return EC_Normal;
}

/* sendAssociationRJTCP
**
** Purpose:
**      Send an Association Reject PDU on a TCP connection.
**
** Parameter Dictionary:
**
**      network         Handle to the network environment
**      abortItems      Pointer to structure holding information regarding
**                      the reason for rejection, the source and result.
**      association     Handle to the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
sendAssociationRJTCP(PRIVATE_NETWORKKEY ** /*network*/,
         DUL_ABORTITEMS * abortItems, PRIVATE_ASSOCIATIONKEY ** association)
{

    DUL_REJECTRELEASEABORTPDU
        pdu;
    unsigned char
        buffer[64],
       *b;
    unsigned long
        length;
    int
        nbytes;


    OFCondition cond = constructAssociateRejectPDU((unsigned char) abortItems->result,
        (unsigned char) abortItems->source, (unsigned char) abortItems->reason, &pdu);
    if (pdu.length + 6 <= sizeof(buffer))
        b = buffer;
    else {
        b = (unsigned char*)malloc(size_t(pdu.length + 6));
        if (b == NULL)  return EC_MemoryExhausted;
    }
    cond = streamRejectReleaseAbortPDU(&pdu, b, pdu.length + 6, &length);

    if ((*association)->associatePDUFlag)
    {
      // copy A-ASSOCIATE-RJ PDU
      (*association)->associatePDU = new char[length];
      if ((*association)->associatePDU)
      {
        memcpy((*association)->associatePDU, b, (size_t) length);
        (*association)->associatePDULength = length;
      }
    }

    if (cond.good())
    {
        do {
          nbytes = (*association)->connection ? (*association)->connection->write((char*)b, size_t(pdu.length + 6)) : 0;
        } while (nbytes == -1 && OFStandard::getLastNetworkErrorCode().value() == DCMNET_EINTR);
        if ((unsigned long) nbytes != pdu.length + 6)
        {
          OFString msg = "TCP I/O Error (";
          msg += OFStandard::getLastNetworkErrorCode().message();
          msg += ") occurred in routine: sendAssociationRJTCP";
          return makeDcmnetCondition(DULC_TCPIOERROR, OF_error, msg.c_str());
        }
    }
    if (b != buffer) free(b);
    return cond;
}

/* sendAbortTCP
**
** Purpose:
**      Send an ABORT PDU over a TCP connection.
**
** Parameter Dictionary:
**      abortItems      Pointer to structure holding information regarding
**                      the reason for rejection, the source and result.
**      association     Handle to the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
sendAbortTCP(DUL_ABORTITEMS * abortItems,
             PRIVATE_ASSOCIATIONKEY ** association)
{
    DUL_REJECTRELEASEABORTPDU
    pdu;
    unsigned char
        buffer[64],
       *b;
    unsigned long
        length;
    int
        nbytes;

    OFCondition cond = constructAbortPDU(abortItems->source, abortItems->reason, &pdu, (*association)->compatibilityMode);
    if (cond.bad())
        return cond;

    if (pdu.length + 6 <= sizeof(buffer))
        b = buffer;
    else {
        b = (unsigned char*)malloc(size_t(pdu.length + 6));
        if (b == NULL)  return EC_MemoryExhausted;
    }
    cond = streamRejectReleaseAbortPDU(&pdu, b, pdu.length + 6, &length);
    if (cond.good()) {
        do {
          nbytes = (*association)->connection ? (*association)->connection->write((char*)b, size_t(pdu.length + 6)) : 0;
        } while (nbytes == -1 && OFStandard::getLastNetworkErrorCode().value() == DCMNET_EINTR);
        if ((unsigned long) nbytes != pdu.length + 6)
        {
          OFString msg = "TCP I/O Error (";
          msg += OFStandard::getLastNetworkErrorCode().message();
          msg += ") occurred in routine: sendAbortTCP";
          return makeDcmnetCondition(DULC_TCPIOERROR, OF_error, msg.c_str());
        }
    }
    if (b != buffer) free(b);

    return cond;
}


/* sendReleaseRQTCP
**
** Purpose:
**      Send a Release request PDU over a TCP connection
**
** Parameter Dictionary:
**
**      association     Handle to the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
sendReleaseRQTCP(PRIVATE_ASSOCIATIONKEY ** association)
{
    DUL_REJECTRELEASEABORTPDU
    pdu;
    unsigned char
        buffer[64],
       *b;
    unsigned long
        length;
    int
        nbytes;

    OFCondition cond = constructReleaseRQPDU(&pdu, (*association)->compatibilityMode);
    if (cond.bad())
        return cond;

    if (pdu.length + 6 <= sizeof(buffer))
        b = buffer;
    else {
        b = (unsigned char*)malloc(size_t(pdu.length + 6));
        if (b == NULL)  return EC_MemoryExhausted;
    }
    cond = streamRejectReleaseAbortPDU(&pdu, b, pdu.length + 6, &length);
    if (cond.good()) {
        do {
          nbytes = (*association)->connection ? (*association)->connection->write((char*)b, size_t(pdu.length + 6)) : 0;
        } while (nbytes == -1 && OFStandard::getLastNetworkErrorCode().value() == DCMNET_EINTR);
        if ((unsigned long) nbytes != pdu.length + 6)
        {
          OFString msg = "TCP I/O Error (";
          msg += OFStandard::getLastNetworkErrorCode().message();
          msg += ") occurred in routine: sendReleaseRQTCP";
          return makeDcmnetCondition(DULC_TCPIOERROR, OF_error, msg.c_str());
        }
    }
    if (b != buffer)
        free(b);

    return cond;
}



/* sendReleaseRPTCP
**
** Purpose:
**      Send a release response PDU over a TCP connection
**
** Parameter Dictionary:
**
**      association     Handle to the Association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
sendReleaseRPTCP(PRIVATE_ASSOCIATIONKEY ** association)
{
    DUL_REJECTRELEASEABORTPDU
    pdu;
    unsigned char buffer[64],
       *b;
    unsigned long
        length;
    int
        nbytes;

    OFCondition cond = constructReleaseRPPDU(&pdu);
    if (cond.bad())
        return cond;

    if (pdu.length + 6 <= sizeof(buffer))
        b = buffer;
    else {
        b = (unsigned char*)malloc(size_t(pdu.length + 6));
        if (b == NULL)  return EC_MemoryExhausted;
    }
    cond = streamRejectReleaseAbortPDU(&pdu, b, pdu.length + 6, &length);
    if (cond.good()) {
        do {
          nbytes = (*association)->connection ? (*association)->connection->write((char*)b, size_t(pdu.length + 6)) : 0;
        } while (nbytes == -1 && OFStandard::getLastNetworkErrorCode().value() == DCMNET_EINTR);
        if ((unsigned long) nbytes != pdu.length + 6)
        {
          OFString msg = "TCP I/O Error (";
          msg += OFStandard::getLastNetworkErrorCode().message();
          msg += ") occurred in routine: sendReleaseRPTCP";
          return makeDcmnetCondition(DULC_TCPIOERROR, OF_error, msg.c_str());
        }
    }
    if (b != buffer) free(b);

    return cond;
}


/* SendPDataTCP
**
** Purpose:
**      Send a data PDU over a TCP connection.
**
** Parameter Dictionary:
**
**      association     Handle to the Association
**      pdvList         Pointer to structure holding a list of PDVs
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
sendPDataTCP(PRIVATE_ASSOCIATIONKEY ** association,
             DUL_PDVLIST * pdvList)
{
    DUL_PDV *pdv;
    unsigned long
        count,
        length,
        pdvLength,
        maxLength;

    OFBool localLast;
    unsigned char *p;
    DUL_DATAPDU dataPDU;
    OFBool firstTrip;

    /* assign the amount of PDVs in the array and the PDV array itself to local variables */
    count = pdvList->count;
    pdv = pdvList->pdv;

    /* determine the maximum size (length) of a PDU which can be sent over the network. */
    /* Note that the name "maxPDV" here is misleading. This field contains the maxPDU */
    /* size which is max PDV size +6 or max PDV data field + 12. */
    maxLength = (*association)->maxPDV;

    /* send the error indicator variable to ok */
    OFCondition cond = EC_Normal;

    /* adjust maxLength (maximum length of a PDU) */
    if (maxLength == 0) maxLength = ASC_MAXIMUMPDUSIZE - 12;
    else if (maxLength < 14)
    {
       char buf[256];
       sprintf(buf, "DUL Cannot send P-DATA PDU because receiver's max PDU size of %lu is illegal (must be > 12)", maxLength);
       cond = makeDcmnetCondition(DULC_ILLEGALPDULENGTH, OF_error, buf);
    }
    else maxLength -= 12;

    /* start a loop iterate over all PDVs in the given */
    /* list and send every PDVs data over the network */
    while (cond.good() && count > 0)
    {
        --count;
        /* determine length of PDV */
        length = pdv->fragmentLength;
        /* determine data to be set */
        p = (unsigned char *) pdv->data;
        /* because the current PDV's length can be greater than maxLength, we need */
        /* to start another loop so that we are able to send data gradually. So, */
        /* as long as this is the first iteration or length is greater than 0 and */
        /* at the same time no error occurred, do the following */
        firstTrip = OFTrue;
        while ((firstTrip || (length > 0)) && (cond.good())) {
            /* indicate that the first iteration has been executed */
            firstTrip = OFFalse;
            /* determine the length of the data fragment that will be sent */
            pdvLength = (length <= maxLength) ? length : maxLength;
            /* determine if the following fragment will be the last fragment to send */
            localLast = ((pdvLength == length) && pdv->lastPDV);
            /* construct a data PDU */
            cond = constructDataPDU(p, pdvLength, pdv->pdvType,
                           pdv->presentationContextID, localLast, &dataPDU);
            /* send the constructed PDU over the network */
            cond = writeDataPDU(association, &dataPDU);

            /* adjust the pointer to the data, so that he points to data which still has to be sent */
            p += pdvLength;
            /* adjust the length of the fragment which still has to be sent */
            length -= pdvLength;
        }
        /* advance to the next PDV */
        pdv++;

    }
    /* return corresponding result value */
    return cond;
}

/* writeDataPDU
**
** Purpose:
**      Send the data through the socket interface (for TCP).
**
** Parameter Dictionary:
**
**      association     Handle to the Association
**      pdu             The data unit that is to be sent thru the socket
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
writeDataPDU(PRIVATE_ASSOCIATIONKEY ** association,
             DUL_DATAPDU * pdu)
{
    unsigned char
        head[24];
    unsigned long
        length;
    int
        nbytes;

    /* construct a stream variable that will contain PDU head information */
    /* (in detail, this variable will contain PDU type, PDU reserved field, */
    /* PDU length, PDV length, presentation context ID, message control header) */
    /* (note that our representation of a PDU can only contain one PDV.) */
    OFCondition cond = streamDataPDUHead(pdu, head, sizeof(head), &length);
    if (cond.bad()) return cond;

    /* send the PDU head information (see above) */
    do
    {
      nbytes = (*association)->connection ? (*association)->connection->write((char*)head, size_t(length)) : 0;
    } while (nbytes == -1 && OFStandard::getLastNetworkErrorCode().value() == DCMNET_EINTR);

    /* if not all head information was sent, return an error */
    if ((unsigned long) nbytes != length)
    {
        OFString msg = "TCP I/O Error (";
        msg += OFStandard::getLastNetworkErrorCode().message();
        msg += ") occurred in routine: writeDataPDU";
        return makeDcmnetCondition(DULC_TCPIOERROR, OF_error, msg.c_str());
    }

    /* send the PDU's PDV data (note that our representation of a PDU can only contain one PDV.) */
    do
    {
      nbytes = (*association)->connection ? (*association)->connection->write((char*)pdu->presentationDataValue.data,
        size_t(pdu->presentationDataValue.length - 2)) : 0;
    } while (nbytes == -1 && OFStandard::getLastNetworkErrorCode().value() == DCMNET_EINTR);

        /* if not all head information was sent, return an error */
    if ((unsigned long) nbytes != pdu->presentationDataValue.length - 2)
    {
        OFString msg = "TCP I/O Error (";
        msg += OFStandard::getLastNetworkErrorCode().message();
        msg += ") occurred in routine: writeDataPDU";
        return makeDcmnetCondition(DULC_TCPIOERROR, OF_error, msg.c_str());
    }

    /* return ok */
    return EC_Normal;
}

/* closeTransport
**
** Purpose:
**      Close the transport connection.
**
** Parameter Dictionary:
**
**      association     Handle to the Association
**
** Return Values:
**      None.
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static void
closeTransport(PRIVATE_ASSOCIATIONKEY ** association)
{
    closeTransportTCP(association);
}

/* closeTransportTCP
**
** Purpose:
**      Close the TCP transport connection.
**
** Parameter Dictionary:
**
**      association     Handle to the Association
**
** Return Values:
**      None
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static void
closeTransportTCP(PRIVATE_ASSOCIATIONKEY ** association)
{
  if ((*association)->connection)
  {
   (*association)->connection->close();
   delete (*association)->connection;
   (*association)->connection = NULL;
  }
}


/* clearPDUCache()
**
** Purpose:
**      Clear the Association of any PDUs.
**
** Parameter Dictionary:
**
**      association     Handle to the Association
**
** Return Values:
**      None.
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static void
clearPDUCache(PRIVATE_ASSOCIATIONKEY ** association)
{
    (*association)->inputPDU = NO_PDU;
}

/* PRV_NextPDUType
**
** Purpose:
**      Get the next PDU's type.
**
** Parameter Dictionary:
**
**      association     Handle to the Association
**      block           Option for blocking/non-blocking
**      timeout         Timeout interval within to get the Type of the next
**                      PDU
**      pduType         The type of next PDU returned to caller.
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

OFCondition
PRV_NextPDUType(PRIVATE_ASSOCIATIONKEY ** association, DUL_BLOCKOPTIONS block,
                int timeout, unsigned char *pduType)
{
    OFCondition cond = EC_Normal;

    /* if the association does not contain PDU header information, do something */
    if ((*association)->inputPDU == NO_PDU) {
        /* try to receive a PDU header on the network */
        cond = readPDUHead(association, (*association)->pduHead,
                           sizeof((*association)->pduHead),
                           block, timeout, &(*association)->nextPDUType,
                           &(*association)->nextPDUReserved,
                           &(*association)->nextPDULength);
        /* if receiving was not successful, return this error */
        if (cond.bad())
            return cond;
        /* indicate that the association does contain PDU header information */
        (*association)->inputPDU = PDU_HEAD;
    }
    /* determine PDU type and assign it to reference parameter */
    *pduType = (*association)->nextPDUType;

    /* return ok */
    return EC_Normal;
}

/* readPDU
**
** Purpose:
**      Read the PDU from the incoming stream.
**
** Parameter Dictionary:
**      association     Handle to the Association
**      block           Blocking/non-blocking options for reading
**      timeout         Timeout interval for reading
**      buffer          Buffer holding the PDU (returned to the caller)
**      PDUType         Type of the PDU (returned to the caller)
**      PDUReserved     Reserved field of the PDU (returned to caller)
**      PDULength       Length of PDU read (returned to caller)
**
**
** Return Values:
**
**
** Notes:
**    The buffer is allocated (malloc) when the PDU size is known.
**    If malloc fails, EC_MemoryExhausted is returned.
**    Otherwise, the buffer must be released (free) by the caller!
**
**    This function is only used to receive incoming A-ASSOCIATE-RQ
**    and A-ASSOCIATE-AC PDUs.
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
readPDU(PRIVATE_ASSOCIATIONKEY ** association, DUL_BLOCKOPTIONS block,
        int timeout, unsigned char **buffer,
        unsigned char *pduType, unsigned char *pduReserved,
        unsigned long *pduLength)
{
    OFCondition cond = EC_Normal;
    unsigned long maxLength;

    *buffer = NULL;
    if ((*association)->inputPDU == NO_PDU) {
        cond = readPDUHead(association, (*association)->pduHead,
                           sizeof((*association)->pduHead),
                           block, timeout, &(*association)->nextPDUType,
                           &(*association)->nextPDUReserved,
                           &(*association)->nextPDULength);
        if (cond.bad())
            return cond;
        (*association)->inputPDU = PDU_HEAD;
    }

    size_t limit = dcmAssociatePDUSizeLimit.get();
    if ((limit > 0) && ((*association)->nextPDULength > limit))
    {
      DCMNET_ERROR("A-ASSOCIATE PDU too large: " << (*association)->nextPDULength << " bytes, refusing." );
      return NET_EC_AssociatePDUTooLarge;
    }

    maxLength = ((*association)->nextPDULength)+100;
    *buffer = (unsigned char *)malloc(size_t(maxLength));
    if (*buffer)
    {
      (void) memcpy(*buffer, (*association)->pduHead, sizeof((*association)->pduHead));
      cond = readPDUBody(association, block, timeout,
        (*buffer) + sizeof((*association)->pduHead),
        maxLength - sizeof((*association)->pduHead),
        pduType, pduReserved, pduLength);
    } else cond = EC_MemoryExhausted;
    return cond;
}


/* readPDUHead
**
** Purpose:
**      Read the header from the PDU. The type of protocol is obtained from
**      the Association handle.
**
** Parameter Dictionary:
**      association     Handle to the Association
**      buffer          Buffer holding the PDU
**      maxLength       Maximum allowable length of the header
**      block           Blocking/non-blocking options for reading
**      timeout         Timeout interval for reading
**      PDUType         Type of the PDU (returned to the caller)
**      PDUReserved     Reserved field of the PDU (returned to caller)
**      PDULength       Length of PDU header read (returned to caller)
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
readPDUHead(PRIVATE_ASSOCIATIONKEY ** association,
            unsigned char *buffer, unsigned long maxLength,
            DUL_BLOCKOPTIONS block, int timeout,
            unsigned char *PDUType, unsigned char *PDUReserved,
            unsigned long *PDULength)
{
    /* initialize return value */
    OFCondition cond = EC_Normal;

    /* if the association does not already contain PDU header */
    /* information, we need to try to receive a PDU on the network */
    if ((*association)->inputPDU == NO_PDU)
    {
        /* try to receive data */
        cond = readPDUHeadTCP(association, buffer, maxLength, block, timeout,
             &(*association)->nextPDUType, &(*association)->nextPDUReserved, &(*association)->nextPDULength);
    }
    /* if everything was ok */
    if (cond.good()) {
        /* indicate that the association does contain PDU header information */
        (*association)->inputPDU = PDU_HEAD;
        /* determine PDU type and the PDU's value in the reserved field and */
        /* in the PDU length field and assign it to reference parameter */
        *PDUType = (*association)->nextPDUType;
        *PDUReserved = (*association)->nextPDUReserved;
        *PDULength = (*association)->nextPDULength;

        /* check if the value in the length field of the PDU shows a legal value; */
        /* there is a maximum length for PDUs which shall be sent over the network. */
        /* the length of this PDU must not be greater than the specified maximum length. */
        /* (bugfix - thanks to B. Gorissen, Philips Medical Systems) */
        if ((*PDUType == DUL_TYPEDATA) && (*PDULength > (*association)->maxPDVInput))
        {
          char buf1[256];
          sprintf(buf1, "DUL Illegal PDU Length %ld.  Max expected %ld", *PDULength, (*association)->maxPDVInput);
          cond = makeDcmnetCondition(DULC_ILLEGALPDULENGTH, OF_error, buf1);
        }
    }

    /* return result value */
    return cond;
}


/* readPDUBody
**
** Purpose:
**      Read the body of the incoming PDU.
**
** Parameter Dictionary:
**      association     Handle to the Association
**      block           For blocking/non-blocking read
**      timeout         Timeout interval for reading
**      buffer          Buffer to hold the PDU
**      maxLength       MAximum number of bytes to read
**      pduType         PDU Type of the incoming PDU (returned to caller)
**      pduReserved     Reserved field in the PDU
**      pduLength       Actual number of bytes read
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
readPDUBody(PRIVATE_ASSOCIATIONKEY ** association,
            DUL_BLOCKOPTIONS block, int timeout,
            unsigned char *buffer, unsigned long maxLength,
            unsigned char *pduType, unsigned char *pduReserved,
            unsigned long *pduLength)
{
    OFCondition cond = EC_Normal;

    /* read PDU body information */
    cond = readPDUBodyTCP(association, block, timeout, buffer, maxLength,
                          pduType, pduReserved, pduLength);

    /* indicate that the association does not contain PDU information any more */
    /* (in detail we indicate that the association can be used to store new PDU */
    /* information, since the current PDU's information is available through */
    /* the variables pduType, pduReserved, pduLength, and buffer now. */
    (*association)->inputPDU = NO_PDU;

    /* return return value */
    return cond;
}

/* readPDUHeadTCP
**
** Purpose:
**      Read the TCP header.
**
** Parameter Dictionary:
**      association     Handle to the Association
**      buffer          Buffer containing the header
**      maxLength       Maximum length of the header
**      block           For blocking/non-blocking read
**      timeout         Timeout interval for reading
**      type            One of the many DUL PDU types
**      reserved        For reserved field
**      pduLength       Length of the header finally read in.
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/


static OFCondition
readPDUHeadTCP(PRIVATE_ASSOCIATIONKEY ** association,
               unsigned char *buffer, unsigned long maxLength,
               DUL_BLOCKOPTIONS block, int timeout,
     unsigned char *type, unsigned char *reserved, unsigned long *pduLength)
{
    unsigned long
        length;
    static unsigned char
        legalPDUTypes[] = {
        DUL_TYPEASSOCIATERQ, DUL_TYPEASSOCIATEAC,
        DUL_TYPEASSOCIATERJ, DUL_TYPEDATA,
        DUL_TYPERELEASERQ, DUL_TYPERELEASERP,
        DUL_TYPEABORT
    };
    int
        found;
    unsigned long
        idx;

    /* check if the buffer is too small to capture the PDU head we are about to receive */
    if (maxLength < 6)
    {
        return makeDcmnetCondition(DULC_CODINGERROR, OF_error, "Coding Error in DUL routine: buffer too small in readPDUTCPHead");
    }

    /* (for non-blocking reading) if the timeout refers to */
    /* the default timeout, set timeout correspondingly */
    if (timeout == PRV_DEFAULTTIMEOUT)
        timeout = (*association)->timeout;

    /* try to receive PDU header (6 bytes) over the network, mind blocking */
    /* options; in the end, buffer will contain the 6 bytes that were read. */
    OFCondition cond = defragmentTCP((*association)->connection, block, (*association)->timerStart, timeout, buffer, 6, &length);

    /* if receiving was not successful, return the corresponding error value */
    if (cond.bad()) return cond;

    DCMNET_TRACE("Read PDU HEAD TCP:" << STD_NAMESPACE hex << STD_NAMESPACE setfill('0')
              << " " << STD_NAMESPACE setw(2) << (unsigned short)(buffer[0])
              << " " << STD_NAMESPACE setw(2) << (unsigned short)(buffer[1])
              << " " << STD_NAMESPACE setw(2) << (unsigned short)(buffer[2])
              << " " << STD_NAMESPACE setw(2) << (unsigned short)(buffer[3])
              << " " << STD_NAMESPACE setw(2) << (unsigned short)(buffer[4])
              << " " << STD_NAMESPACE setw(2) << (unsigned short)(buffer[5]));

    /* determine PDU type (captured in byte 0 of buffer) and assign it to reference parameter */
    *type = *buffer++;

    /* determine value in the PDU header's reserved field (captured */
    /* in byte 1 of buffer) and assign it to reference parameter */
    *reserved = *buffer++;

    /* check if the PDU which was received shows a legal PDU type */
    for (idx = found = 0; !found && idx < sizeof(legalPDUTypes); idx++) {
        found = (*type == legalPDUTypes[idx]);
    }

    /* if the PDU's type was not legal, return a corresponding message */
    if (!found)
    {
        char buf[256];
        sprintf(buf, "Unrecognized PDU type: %2x", *type);
        return makeDcmnetCondition(DULC_UNRECOGNIZEDPDUTYPE, OF_error, buf);
    }

    /* determine the value in the PDU length field of the PDU */
    /* which was received and assign it to reference parameter */
    EXTRACT_LONG_BIG(buffer, length);
    buffer += 4;
    *pduLength = length;

    DCMNET_TRACE("Read PDU HEAD TCP: type: "
              << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << (unsigned short)(*type)
              << ", length: " << STD_NAMESPACE dec << (*pduLength) << " ("
              << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << (unsigned int)*pduLength
              << ")");

    /* return ok */
    return EC_Normal;
}


/* readPDUBodyTCP
**
** Purpose:
**      Read the PDU from a TCP socket interface.
**
** Parameter Dictionary:
**      association     Handle to the Association
**      block           For blocking/non-blocking read
**      timeout         Timeout interval for reading
**      buffer          Buffer to hold the PDU
**      maxLength       Maximum number of bytes to read
**      pduType         PDU Type of the incoming PDU (returned to caller)
**      pduReserved     Reserved field in the PDU
**      pduLength       Actual number of bytes read
**
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
readPDUBodyTCP(PRIVATE_ASSOCIATIONKEY ** association,
               DUL_BLOCKOPTIONS block, int timeout,
               unsigned char *buffer, unsigned long maxLength,
               unsigned char *pduType, unsigned char *pduReserved,
               unsigned long *pduLength)
{
    OFCondition cond = EC_Normal;
    unsigned long
        length;

    /* check if the association does not already contain PDU head information. */
    if ((*association)->inputPDU == NO_PDU) {
        /* If it does not, we need to try to receive PDU head information over the network */
        cond = readPDUHead(association, (*association)->pduHead,
                           sizeof((*association)->pduHead),
                           block, timeout, &(*association)->nextPDUType,
                           &(*association)->nextPDUReserved,
                           &(*association)->nextPDULength);
        /* return error if there was one */
        if (cond.bad())
            return cond;
    }
    /* determine PDU type and its values in the reserved field and in the PDU length field */
    *pduType = (*association)->nextPDUType;
    *pduReserved = (*association)->nextPDUReserved;
    *pduLength = (*association)->nextPDULength;

    /* (for non-blocking reading) if the timeout refers to */
    /* the default timeout, set timeout correspondingly */
    if (timeout == PRV_DEFAULTTIMEOUT)
        timeout = (*association)->timeout;

    /* bugfix by meichel 97/04/28: test if PDU fits into buffer */
    if (*pduLength > maxLength)
    {
      /* if it doesn't, set error indicator variable */
      cond = DUL_ILLEGALPDULENGTH;
    } else {
      /* if it does, read the current PDU's PDVs from the incoming socket stream. (Note that the */
      /* PDVs of the current PDU are (*association)->nextPDULength bytes long. Hence, in detail */
      /* we want to try to receive (*association)->nextPDULength bytes of data on the network) */
      /* The information that was received will be available through the buffer variable. */
      cond = defragmentTCP((*association)->connection,
                         block, (*association)->timerStart, timeout,
                         buffer, (*association)->nextPDULength, &length);
    }

    /* return result value */
    return cond;
}


/* defragmentTCP
**
** Purpose:
**      Actually read the desired number of bytes  of the PDU from the
**      incoming socket stream.
**
** Parameter Dictionary:
**      sock            Socket descriptor
**      block           Blocking/non-blocking option
**      timerStart      Time at which the reading operation is started.
**      timeout         Timeout interval for reading
**      p               Buffer to hold the information
**      l               Maximum number of bytes to read
**      rtnLength       Actual number of bytes that were read (returned
**                      to the caller)
**
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/


static OFCondition
defragmentTCP(DcmTransportConnection *connection, DUL_BLOCKOPTIONS block, time_t timerStart,
              int timeout, void *p, unsigned long l, unsigned long *rtnLen)
{
    unsigned char *b;
    int bytesRead;

    /* assign buffer to local variable */
    b = (unsigned char *) p;

    /* if reference parameter is a valid pointer, initialize its value */
    if (rtnLen != NULL)
        *rtnLen = 0;

    /* if there is no network connection, return an error */
    if (connection == NULL) return DUL_NULLKEY;

    int timeToWait = 0;
    if (block == DUL_NOBLOCK)
    {
        /* figure out how long we want to wait: if timerStart equals 0 we want to wait exactly */
        /* timeout seconds starting from the call to select(...) within the below called function; */
        /* if timerStart does not equal 0 we want to subtract the time which has already passed */
        /* after the timer was started from timeout and wait the resulting amount of seconds */
        /* starting from the call to select(...) within the below called function. */
        if (timerStart == 0) timerStart = time(NULL);
    }

    /* start a loop: since we want to receive l bytes of data over the network, */
    /* we won't stop waiting for data until we actually did receive l bytes. */
    while (l > 0)
    {
        /* receive data from the network connection; wait until */
        /* we actually did receive data or an error occurred */
        do
        {
            /* if DUL_NOBLOCK is specified as a blocking option, we only want to wait a certain
             * time for receiving data over the network. If no data was received during that time,
             * DUL_READTIMEOUT shall be returned. Note that if DUL_BLOCK is specified the application
             * will not stop waiting until data is actually received over the network.
             */
            if (block == DUL_NOBLOCK)
            {
                /* determine remaining time to wait */
                timeToWait = timeout - (int) (time(NULL) - timerStart);

                /* go ahead and see if within timeout seconds data will be received over the network. */
                /* if not, return DUL_READTIMEOUT, if yes, stay in this function. */
                if (!connection->networkDataAvailable(timeToWait)) return DUL_READTIMEOUT;
            }

            /* data has become available, now call read(). */
            bytesRead = connection->read((char*)b, size_t(l));

        } while (bytesRead == -1 && OFStandard::getLastNetworkErrorCode().value() == DCMNET_EINTR);

        /* if we actually received data, move the buffer pointer to its own end, update the variable */
        /* that determines the end of the first loop, and update the reference parameter return variable */
        if (bytesRead > 0) {
            b += bytesRead;
            l -= (unsigned long) bytesRead;
            if (rtnLen != NULL)
                *rtnLen += (unsigned long) bytesRead;
        } else {
            /* in case we did not receive any data, an error must have occurred; return a corresponding result value */
            return DUL_NETWORKCLOSED;
        }
    }
    return EC_Normal;
}

/* dump_pdu
**
** Purpose:
**      Debugging routine for dumping a pdu
**
** Parameter Dictionary:
**      type            PDU type
**      buffer          Buffer holding the PDU
**      length          Length of the PDU
**
** Return Values:
**      None
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFString
dump_pdu(const char *type, void *buffer, unsigned long length)
{
    unsigned char
       *p;
    int
        position = 0;
    OFOStringStream
        str;

    str << "PDU Type: " << type << ", PDU Length: " << length-6 << " + 6 bytes PDU header" << OFendl;
    if (length > 512) {
        str << "Only dumping 512 bytes." << OFendl;
        length = 512;
    }
    p = (unsigned char*)buffer;

    while (length-- > 0) {
        str << "  "
            << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << ((unsigned int)(*p++))
            << STD_NAMESPACE dec;
        if ((++position) % 16 == 0) str << OFendl;
    }
    str << OFStringStream_ends;
    OFSTRINGSTREAM_GETOFSTRING(str, ret)
    return ret;
}



/* setTCPBufferLength
**
** Purpose:
**      This routine checks for the existence of an environment
**      variable (TCP_BUFFER_LENGTH).  If that variable is defined (and
**      is a legal integer), this routine sets the socket SNDBUF and RCVBUF
**      variables to the value defined in TCP_BUFFER_LENGTH.
**
** Parameter Dictionary:
**      sock            Socket descriptor (identifier)
**
** Return Values:
**      None
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

#ifdef _WIN32
static void setTCPBufferLength(SOCKET sock)
#else
static void setTCPBufferLength(int sock)
#endif
{
    char *TCPBufferLength;
    int bufLen;

    /*
     * check whether environment variable TCP_BUFFER_LENGTH is set.
     * If not, the the operating system is responsible for selecting
     * appropriate values for the TCP send and receive buffer lengths.
     */
    DCMNET_TRACE("checking whether environment variable TCP_BUFFER_LENGTH is set");
    if ((TCPBufferLength = getenv("TCP_BUFFER_LENGTH")) != NULL) {
        if (sscanf(TCPBufferLength, "%d", &bufLen) == 1) {
#if defined(SO_SNDBUF) && defined(SO_RCVBUF)
            if (bufLen == 0)
                bufLen = 65536; // a socket buffer size of 64K gives good throughput for image transmission
            DCMNET_DEBUG("DULFSM: setting TCP buffer length to " << bufLen << " bytes");
            (void) setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *) &bufLen, sizeof(bufLen));
            (void) setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *) &bufLen, sizeof(bufLen));
#else
            DCMNET_WARN("DULFSM: setTCPBufferLength: cannot set TCP buffer length socket option: "
                << "code disabled because SO_SNDBUF and SO_RCVBUF constants are unknown");
#endif // SO_SNDBUF and SO_RCVBUF
        } else
            DCMNET_WARN("DULFSM: cannot parse environment variable TCP_BUFFER_LENGTH=" << TCPBufferLength);
    } else
        DCMNET_TRACE("  environment variable TCP_BUFFER_LENGTH not set, using the system defaults");
}

/* translatePresentationContextList
**
** Purpose:
**      Translate the internal list into a user context list and a
**      SCU-SCP role list
**
** Parameter Dictionary:
**      internalList            Input list from which the two output lists
**                              are derived
**      SCUSCPRoleList          Role list (returned to the caller)
**      userContextList         User context list (returned to the caller)
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
translatePresentationContextList(LST_HEAD ** internalList,
                                 LST_HEAD ** SCUSCPRoleList,
                                 LST_HEAD ** userContextList)
{
    PRV_PRESENTATIONCONTEXTITEM
        * context;
    DUL_PRESENTATIONCONTEXT
        * userContext;
    DUL_SUBITEM
        * subItem;
    DUL_TRANSFERSYNTAX
        * transfer;
    PRV_SCUSCPROLE
        * scuscpRole;
    OFCondition cond = EC_Normal;

    context = (PRV_PRESENTATIONCONTEXTITEM*)LST_Head(internalList);
    (void) LST_Position(internalList, (LST_NODE*)context);
    while (context != NULL) {
        userContext = (DUL_PRESENTATIONCONTEXT*)malloc(sizeof(DUL_PRESENTATIONCONTEXT));
        if (userContext == NULL) return EC_MemoryExhausted;
        if ((userContext->proposedTransferSyntax = LST_Create()) == NULL) return EC_MemoryExhausted;

        userContext->acceptedTransferSyntax[0] = '\0';
        userContext->presentationContextID = context->contextID;
        OFStandard::strlcpy(userContext->abstractSyntax, context->abstractSyntax.data, sizeof(userContext->abstractSyntax));
        userContext->proposedSCRole = DUL_SC_ROLE_DEFAULT;
        userContext->acceptedSCRole = DUL_SC_ROLE_DEFAULT;

        scuscpRole = findSCUSCPRole(SCUSCPRoleList,
                                    userContext->abstractSyntax);
        if (scuscpRole != NULL) {
            if (scuscpRole->SCURole == scuscpRole->SCPRole) {
                userContext->proposedSCRole = DUL_SC_ROLE_SCUSCP;
                if (scuscpRole->SCURole == 0)
                    DCMNET_WARN("DULFSM: both role fields are 0 in SCP/SCU role selection sub-item");
            }
            else if (scuscpRole->SCURole == 1)
                userContext->proposedSCRole = DUL_SC_ROLE_SCU;
            else  // SCPRole == 1
                userContext->proposedSCRole = DUL_SC_ROLE_SCP;
        }
        subItem = (DUL_SUBITEM*)LST_Head(&context->transferSyntaxList);
        if (subItem == NULL)
        {
            char buf1[256];
            sprintf(buf1, "DUL Peer supplied illegal number of transfer syntaxes (%d)", 0);
            free(userContext);
            return makeDcmnetCondition(DULC_PEERILLEGALXFERSYNTAXCOUNT, OF_error, buf1);
        }
        (void) LST_Position(&context->transferSyntaxList, (LST_NODE*)subItem);
        while (subItem != NULL) {
            transfer = (DUL_TRANSFERSYNTAX*)malloc(sizeof(DUL_TRANSFERSYNTAX));
            if (transfer == NULL) return EC_MemoryExhausted;
            OFStandard::strlcpy(transfer->transferSyntax, subItem->data, sizeof(transfer->transferSyntax));

            LST_Enqueue(&userContext->proposedTransferSyntax, (LST_NODE*)transfer);
            subItem = (DUL_SUBITEM*)LST_Next(&context->transferSyntaxList);
        }
        LST_Enqueue(userContextList, (LST_NODE*)userContext);
        context = (PRV_PRESENTATIONCONTEXTITEM*)LST_Next(internalList);
    }
    return EC_Normal;
}

/* findPresentationCtx
**
** Purpose:
**      Find the requested presentation context using the contextID as the
**      key
**
** Parameter Dictionary:
**      list            List to be searched
**      contextID       The search key
**
** Return Values:
**      A presentation context list (if found) else NULL.
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
DUL_PRESENTATIONCONTEXT *
findPresentationCtx(
                    LST_HEAD ** lst, DUL_PRESENTATIONCONTEXTID contextID)
{
    DUL_PRESENTATIONCONTEXT
    * ctx;

    if ((ctx = (DUL_PRESENTATIONCONTEXT*)LST_Head(lst)) == NULL)
        return NULL;

    (void) LST_Position(lst, (LST_NODE*)ctx);
    while (ctx != NULL) {
        if (ctx->presentationContextID == contextID)
            return ctx;

        ctx = (DUL_PRESENTATIONCONTEXT*)LST_Next(lst);
    }
    return NULL;
}


/* findSCUSCPRole
**
** Purpose:
**      Search for a SCUSCP role list, given the abstract syntax as the
**      key.
**
** Parameter Dictionary:
**      list            List to be searched
**      abstractSyntax  The search key
**
** Return Values:
**      The role list, if found, else NULL
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
PRV_SCUSCPROLE
*
findSCUSCPRole(LST_HEAD ** lst, char *abstractSyntax)
{
    PRV_SCUSCPROLE
        * role;

    role = (PRV_SCUSCPROLE*)LST_Head(lst);
    if (role != NULL)
        (void) LST_Position(lst, (LST_NODE*)role);

    while (role != NULL) {
        if (strcmp(role->SOPClassUID, abstractSyntax) == 0)
            return role;

        role = (PRV_SCUSCPROLE*)LST_Next(lst);
    }
    return NULL;
}

void
destroyPresentationContextList(LST_HEAD ** l)
{
    PRV_PRESENTATIONCONTEXTITEM
    * prvCtx;
    DUL_SUBITEM
        * subItem;

    if (*l == NULL)
        return;

    prvCtx = (PRV_PRESENTATIONCONTEXTITEM*)LST_Dequeue(l);
    while (prvCtx != NULL) {
        subItem = (DUL_SUBITEM*)LST_Dequeue(&prvCtx->transferSyntaxList);
        while (subItem != NULL) {
            free(subItem);
            subItem = (DUL_SUBITEM*)LST_Dequeue(&prvCtx->transferSyntaxList);
        }
        LST_Destroy(&prvCtx->transferSyntaxList);
        free(prvCtx);
        prvCtx = (PRV_PRESENTATIONCONTEXTITEM*)LST_Dequeue(l);
    }
    LST_Destroy(l);
}

void
destroyUserInformationLists(DUL_USERINFO * userInfo)
{
    PRV_SCUSCPROLE
    * role;

    role = (PRV_SCUSCPROLE*)LST_Dequeue(&userInfo->SCUSCPRoleList);
    while (role != NULL) {
        free(role);
        role = (PRV_SCUSCPROLE*)LST_Dequeue(&userInfo->SCUSCPRoleList);
    }
    LST_Destroy(&userInfo->SCUSCPRoleList);

    /* extended negotiation */
    delete userInfo->extNegList; userInfo->extNegList = NULL;

    /* user identity negotiation */
    delete userInfo->usrIdent; userInfo->usrIdent = NULL;
}