File: dul.cc

package info (click to toggle)
dcmtk 3.6.9-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 95,648 kB
  • sloc: ansic: 426,874; cpp: 318,177; makefile: 6,401; sh: 4,341; yacc: 1,026; xml: 482; lex: 321; perl: 277
file content (2875 lines) | stat: -rw-r--r-- 97,648 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
/*
 *
 *  Copyright (C) 1994-2024, 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_InitializeNetwork
**                DUL_DropNetwork
**                DUL_RequestAssociation
**                DUL_ReceiveAssociationRQ
**                DUL_AcknowledgeAssociateRQ
**                DUL_RejectAssociateRQ
**                DUL_ReleaseAssociation
**                DUL_AbortAssociation
**                DUL_DropAssociation
**                DUL_WritePDVs
**                DUL_ReadPDVs
** Author, Date:  Stephen M. Moore, 14-Apr-93
** Intent:        This module contains the public entry points for the
**                DICOM Upper Layer (DUL) protocol package.
*/


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

#ifdef HAVE_WINDOWS_H
#include <winsock2.h>  /* for SO_EXCLUSIVEADDRUSE */
#include <ws2tcpip.h>  /* for socklen_t */
#endif

#include "dcmtk/dcmnet/diutil.h"

BEGIN_EXTERN_C
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
/* sys/socket.h included via "dcmtk/ofstd/ofsockad.h" - needed for Ultrix */
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#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
#ifdef WITH_TCPWRAPPER
#include <tcpd.h>               /* for hosts_ctl */
int dcmtk_hosts_access(struct request_info *req);
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>              /* for FD_CLOEXEC */
#endif

/* declare extern "C" typedef for signal handler function pointer */
typedef void(*mySIG_TYP)(int);
END_EXTERN_C

#ifdef DCMTK_HAVE_POLL
#include <poll.h>
#endif


#include "dcmtk/ofstd/ofstream.h"
#include "dcmtk/dcmnet/dcompat.h"
#include "dcmtk/dcmnet/dicom.h"
#include "dcmtk/dcmnet/cond.h"
#include "dcmtk/dcmnet/lst.h"
#include "dcmtk/ofstd/ofconsol.h"
#include "dcmtk/ofstd/ofstd.h"
#include "dcmtk/ofstd/ofsockad.h" /* for class OFSockAddr and SOCK_CLOEXEC */

#include "dcmtk/dcmnet/dul.h"
#include "dcmtk/dcmnet/dulstruc.h"
#include "dulpriv.h"
#include "dulfsm.h"
#include "dcmtk/dcmnet/dcmtrans.h"
#include "dcmtk/dcmnet/dcmlayer.h"
#include "dcmtk/ofstd/ofstd.h"

OFGlobal<OFBool> dcmDisableGethostbyaddr(OFFalse);
OFGlobal<Sint32> dcmConnectionTimeout(-1);
OFGlobal<DcmNativeSocketType> dcmExternalSocketHandle(DCMNET_INVALID_SOCKET);
OFGlobal<const char *> dcmTCPWrapperDaemonName((const char *)NULL);
OFGlobal<unsigned long> dcmEnableBackwardCompatibility(0);
OFGlobal<size_t> dcmAssociatePDUSizeLimit(0x100000);

static int networkInitialized = 0;

static OFCondition
createNetworkKey(const char *mode, int timeout, unsigned long opt,
                 PRIVATE_NETWORKKEY ** k);
static OFCondition
createAssociationKey(PRIVATE_NETWORKKEY ** network, const char *node,
                     unsigned long maxPDU,
                     PRIVATE_ASSOCIATIONKEY ** assoc);
static OFCondition initializeNetworkTCP(PRIVATE_NETWORKKEY ** k, void *p);
static OFCondition
receiveTransportConnection(PRIVATE_NETWORKKEY ** network,
                           DUL_BLOCKOPTIONS block,
                           int timeout,
                           DUL_ASSOCIATESERVICEPARAMETERS * params,
                           PRIVATE_ASSOCIATIONKEY ** association);
static OFCondition
receiveTransportConnectionTCP(PRIVATE_NETWORKKEY ** network,
                              DUL_BLOCKOPTIONS block,
                              int timeout,
                              DUL_ASSOCIATESERVICEPARAMETERS * params,
                              PRIVATE_ASSOCIATIONKEY ** association);


static void destroyAssociationKey(PRIVATE_ASSOCIATIONKEY ** key);
#if 0
static OFCondition writeDataPDU(PRIVATE_ASSOCIATIONKEY ** key, DUL_DATAPDU * pdu);
static OFCondition dropPDU(PRIVATE_ASSOCIATIONKEY ** association, unsigned long l);
#endif
static OFCondition
get_association_parameter(void *paramAddress,
  DUL_DATA_TYPE paramType, size_t paramLength,
  DUL_DATA_TYPE outputType, void *outputAddress, size_t outputLength);

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

static OFCondition checkNetwork(PRIVATE_NETWORKKEY ** networkKey);
static OFCondition checkAssociation(PRIVATE_ASSOCIATIONKEY ** association);
static OFString dump_presentation_ctx(LST_HEAD ** l);
static OFString dump_uid(const char *UID, const char *indent);
static void clearRequestorsParams(DUL_ASSOCIATESERVICEPARAMETERS * params);
static void clearPresentationContext(LST_HEAD ** l);

#define MIN_PDU_LENGTH  4*1024
#define MAX_PDU_LENGTH  128*1024

static OFBool processIsForkedChild = OFFalse;
static OFBool shouldFork = OFFalse;

#ifdef _WIN32
static char **command_argv = NULL;
static int command_argc = 0;
#endif

OFBool DUL_processIsForkedChild()
{
  return processIsForkedChild;
}

void DUL_markProcessAsForkedChild()
{
  processIsForkedChild = OFTrue;
}

OFCondition DUL_readSocketHandleAsForkedChild()
{
  OFCondition result = EC_Normal;

#ifdef _WIN32
  // we are a child process
  DUL_markProcessAsForkedChild();

  char buf[256];
  DWORD bytesRead = 0;
  HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);

  // read socket handle number from stdin, i.e. the anonymous pipe
  // to which our parent process has written the handle number.
  if (ReadFile(hStdIn, buf, sizeof(buf) - 1, &bytesRead, NULL))
  {
    // make sure buffer is zero terminated
    buf[bytesRead] = '\0';
    unsigned __int64 socketHandle = 0;
    sscanf(buf, "%llu", &socketHandle);
    // socketHandle is always 64-bit because we always use this type to
    // pass the handle between parent and chile. Type DcmNativeSocketType
    // can be 32-bit on a 32-bit Windows, however. We, therefore, cast to the
    // appropriate type. This is safe because the handle in the parent
    // also had type DcmNativeSocketType.
    dcmExternalSocketHandle.set(OFstatic_cast(DcmNativeSocketType, socketHandle));
  }
  else
  {
    DCMNET_ERROR("cannot read socket handle: " << GetLastError());
    result = DUL_CANNOTREADSOCKETHANDLE;
  }
#endif

  return result;
}


void DUL_requestForkOnTransportConnectionReceipt(int argc, char *argv[])
{
  shouldFork = OFTrue;
#ifdef _WIN32
  command_argc = argc;
  command_argv = argv;
#else
  // Work around "Unused parameters"
  (void) argc;
  (void) argv;
#endif
}

void DUL_activateAssociatePDUStorage(DUL_ASSOCIATIONKEY *dulassoc)
{
  if (dulassoc)
  {
    PRIVATE_ASSOCIATIONKEY *assoc = (PRIVATE_ASSOCIATIONKEY *)dulassoc;
    assoc->associatePDUFlag = 1;
  }
}

void DUL_activateCompatibilityMode(DUL_ASSOCIATIONKEY *dulassoc, unsigned long mode)
{
  if (dulassoc)
  {
    PRIVATE_ASSOCIATIONKEY *assoc = (PRIVATE_ASSOCIATIONKEY *)dulassoc;
    assoc->compatibilityMode = mode;
  }
}

void DUL_activateCallback(DUL_ASSOCIATIONKEY *dulassoc, DUL_ModeCallback *cb)
{
  if (dulassoc)
  {
    PRIVATE_ASSOCIATIONKEY *assoc = (PRIVATE_ASSOCIATIONKEY *)dulassoc;
    assoc->modeCallback = cb;
  }
}

void DUL_returnAssociatePDUStorage(DUL_ASSOCIATIONKEY *dulassoc, void *& pdu, unsigned long& pdusize)
{
  if (dulassoc)
  {
    PRIVATE_ASSOCIATIONKEY *assoc = (PRIVATE_ASSOCIATIONKEY *)dulassoc;
    pdu = assoc->associatePDU;
    pdusize = assoc->associatePDULength;
    assoc->associatePDUFlag = 0;
    assoc->associatePDU = NULL;
    assoc->associatePDULength = 0;
  } else {
    pdu = NULL;
    pdusize = 0;
  }
}

unsigned long DUL_getPeerCertificate(DUL_ASSOCIATIONKEY *dulassoc, void *buf, unsigned long bufLen)
{
  PRIVATE_ASSOCIATIONKEY *assoc = (PRIVATE_ASSOCIATIONKEY *)dulassoc;
  if (assoc && assoc->connection)
  {
    return assoc->connection->getPeerCertificate(buf, bufLen);
  }
  return 0;
}

unsigned long DUL_getPeerCertificateLength(DUL_ASSOCIATIONKEY *dulassoc)
{
  PRIVATE_ASSOCIATIONKEY *assoc = (PRIVATE_ASSOCIATIONKEY *)dulassoc;
  if (assoc && assoc->connection)
  {
    return assoc->connection->getPeerCertificateLength();
  }
  return 0;
}


/* DUL_InitializeNetwork
**
** Purpose:
**  Identify and initialize a network to request or accept Associations.
**  The caller identifies
**  whether the application wishes to be an Acceptor (AE_ACCEPTOR) or a
**  Requestor (AE_REQUESTOR) or both (AE_BOTH).  Upon successful
**  initialization of the network, the function returns a key to be used
**  for further network access.
**
** Parameter Dictionary:
**      mode              NULL terminated string identifying the application
**                        as a requestor or acceptor.
**      networkParameter  A parameter which is specific to the network type,
**                        which may be needed to initialize the network.
**      timeout           Length of time in seconds for TIMER timeout.
**                        If 0, the function will use a default value.
**      opt               Bitmask which describes options to be used when
**                        initializing the network.
**      networkKey        The handle created by this function and returned
**                        to the caller to access this network environment
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_InitializeNetwork(const char *mode,
                      void *networkParameter, int timeout, unsigned long opt,
                      DUL_NETWORKKEY ** networkKey)
{
    // default return value if something goes wrong
    *networkKey = NULL;

    // a few initializations must only be done the first time this function is called.
    if (! networkInitialized)
    {
      // make sure "Broken Pipe" signals don't terminate the application
#ifdef SIGPIPE
      (void) signal(SIGPIPE, (mySIG_TYP)SIG_IGN);
#endif

      // initialize DUL FSM
      (void) DUL_InitializeFSM();

      ++networkInitialized;
    }

    // create PRIVATE_NETWORKKEY structure
    PRIVATE_NETWORKKEY *key = NULL;
    OFCondition cond = createNetworkKey(mode, timeout, opt, &key);

    // initialize network
    if (cond.good()) cond = initializeNetworkTCP(&key, networkParameter);

    if (cond.good())
    {
      // everything worked well, return network key
      *networkKey = (DUL_NETWORKKEY *) key;
    }
    else
    {
      // initializeNetworkTCP has failed, destroy PRIVATE_NETWORKKEY structure
      PRIVATE_NETWORKKEY **pkey = &key;
      (void) DUL_DropNetwork((DUL_NETWORKKEY **) pkey);
    }

    return cond;
}


/* DUL_DropNetwork
**
** Purpose:
**      This function drops the network connection established by
**      by DUL_InitializeNetwork.  The caller passes the pointer to the
**      network key.  The network connection is closed and the caller's
**      key is zeroed to prevent misuse.
**
** Parameter Dictionary:
**      callerNetworkKey  Caller's handle to the network environment
**
** Return Values:
**
**
** Algorithm:
**      Close the socket and free the memory occupied by the network key
*/
OFCondition
DUL_DropNetwork(DUL_NETWORKKEY ** callerNetworkKey)
{
    PRIVATE_NETWORKKEY
        ** networkKey;

    networkKey = (PRIVATE_NETWORKKEY **) callerNetworkKey;

    OFCondition cond = checkNetwork(networkKey);
    if (cond.bad()) return cond;

    if ((*networkKey)->networkSpecific.TCP.tLayerOwned) delete (*networkKey)->networkSpecific.TCP.tLayer;

    if ((*networkKey)->applicationFunction & DICOM_APPLICATION_ACCEPTOR)
    {
#ifdef HAVE_WINSOCK_H
            (void) shutdown((*networkKey)->networkSpecific.TCP.listenSocket, 1 /* SD_SEND */);
            (void) closesocket((*networkKey)->networkSpecific.TCP.listenSocket);
#else
            (void) close((*networkKey)->networkSpecific.TCP.listenSocket);
#endif
    }

    free(*networkKey);
    *networkKey = NULL;
    return EC_Normal;
}


/* DUL_RequestAssociation
**
** Purpose:
**      This function requests an Association with another node.  The caller
**      identifies the network to be used, the name of the other node, a
**      network dependent parameter and a structure which defines the
**      Association parameters needed to establish an Association (the
**      syntax items).  This function establishes the Association and
**      returns the modified list of Association parameters and a key to
**      be used to access this Association.  If the caller does not choose
**      to recognize the parameters returned by the Acceptor, the caller
**      should abort the Association.
**
** Parameter Dictionary:
**      callerNetworkKey    Caller's handle to the network environment.
**      block               Flag indicating blocking/non-blocking mode.
**      timeout             When blocking mode is non-blocking, the timeout in
**                          seconds.
**      params              Pointer to list of parameters which describe the type
**                          of Association requested by the caller.
**      callerAssociation   Handle created by this function which describes the
**                          Association; returned to the caller.
**      activatePDUStorage
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_RequestAssociation(
  DUL_NETWORKKEY ** callerNetworkKey,
  DUL_BLOCKOPTIONS block,
  int timeout,
  DUL_ASSOCIATESERVICEPARAMETERS * params,
  DUL_ASSOCIATIONKEY ** callerAssociation,
  int activatePDUStorage)
{
    PRIVATE_ASSOCIATIONKEY
        ** association;
    PRIVATE_NETWORKKEY
        ** network;
    unsigned char
        pduType;
    int
        event;

    network = (PRIVATE_NETWORKKEY **) callerNetworkKey;
    association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;
    OFCondition cond = checkNetwork(network);
    if (cond.bad()) return cond;

    if (((*network)->applicationFunction & DICOM_APPLICATION_REQUESTOR) == 0)
    {
        return DUL_ILLEGALREQUEST;
    }

    if (params->maxPDU < MIN_PDU_LENGTH || params->maxPDU > MAX_PDU_LENGTH)
    {
        return makeDcmnetCondition(DULC_ILLEGALPARAMETER, OF_error, "DUL Illegal parameter (maxPDU) in function DUL_RequestAssociation");
    }

    cond = createAssociationKey(network, "", params->maxPDU, association);
    if (cond.bad())
        return cond;

    if (block == DUL_NOBLOCK)
        DCMNET_TRACE("setting association request timeout to " << timeout << " seconds");

    if (activatePDUStorage) DUL_activateAssociatePDUStorage(*association);

    /* send a request primitive */
    cond = PRV_StateMachine(network, association,
             A_ASSOCIATE_REQ_LOCAL_USER, (*network)->protocolState, params);

    if (cond.bad())
    {
        /*
         * In case of an error, close the connection and go to the initial
         * state
         */
        OFCondition cond2 = PRV_StateMachine(network, association, TRANS_CONN_CLOSED, (*association)->protocolState, NULL);
        destroyAssociationKey(association);
        return cond;
    }
    cond = PRV_StateMachine(network, association,
      TRANS_CONN_CONFIRM_LOCAL_USER, (*association)->protocolState, params);
    if (cond.bad()) {
        destroyAssociationKey(association);
        return cond;
    }

    /* if no timeout is passed, use the default one (do not wait forever) */
    if ((block == DUL_BLOCK) && ((*association)->timeout > 0))
    {
        block = DUL_NOBLOCK;
        timeout = (*association)->timeout;
        DCMNET_TRACE("setting timeout for first PDU to be read to " << timeout << " seconds");
    }
    /* Find the next event */
    cond = PRV_NextPDUType(association, block, timeout, &pduType);

    if (cond == DUL_NETWORKCLOSED)
        event = TRANS_CONN_CLOSED;
    else if (cond == DUL_READTIMEOUT)
        event = ARTIM_TIMER_EXPIRED;
    else if (cond.bad()) {
        destroyAssociationKey(association);
        return cond;
    } else {
        switch (pduType) {
        case DUL_TYPEASSOCIATERQ:
            event = A_ASSOCIATE_RQ_PDU_RCV;
            break;
        case DUL_TYPEASSOCIATEAC:
            event = A_ASSOCIATE_AC_PDU_RCV;
            break;
        case DUL_TYPEASSOCIATERJ:
            event = A_ASSOCIATE_RJ_PDU_RCV;
            break;
        case DUL_TYPEDATA:
            event = P_DATA_TF_PDU_RCV;
            break;
        case DUL_TYPERELEASERQ:
            event = A_RELEASE_RQ_PDU_RCV;
            break;
        case DUL_TYPERELEASERP:
            event = A_RELEASE_RP_PDU_RCV;
            break;
        case DUL_TYPEABORT:
            event = A_ABORT_PDU_RCV;
            break;
        default:
            event = INVALID_PDU;
            break;
        }
    }

    cond = PRV_StateMachine(network, association, event, (*association)->protocolState, params);
    if (cond.bad() && (cond != DUL_PEERREQUESTEDRELEASE))
    {
        destroyAssociationKey(association);
        return cond;
    }
    return cond;
}


/* DUL_ReceiveAssociationRQ
**
** Purpose:
**      This function allows a caller to ask to receive an Association Request.
**      If the function does receive such a request, it returns a list of
**      Association Items which describe the proposed Association and an
**      AssociationKey used to access this Association.  The user should call
**      DUL_AcknowledgeAssociateRQ if the Association is to be accepted.
**
** Parameter Dictionary:
**      callerNetworkKey    Caller's handle to the network environment.
**      block               Flag indicating blocking/non-blocking mode.
**      timeout             When blocking mode is non-blocking, the timeout in
**                          seconds.
**      params              Pointer to a structure holding parameters which
**                          describe this Association.
**      callerAssociation   Caller handle for this association that is created
**                          by this function.
**      activatePDUStorage
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_ReceiveAssociationRQ(
  DUL_NETWORKKEY ** callerNetworkKey,
  DUL_BLOCKOPTIONS block,
  int timeout,
  DUL_ASSOCIATESERVICEPARAMETERS * params,
  DUL_ASSOCIATIONKEY ** callerAssociation,
  int activatePDUStorage)
{
    PRIVATE_NETWORKKEY
        ** network;
    PRIVATE_ASSOCIATIONKEY
        ** association;
    unsigned char
        pduType;
    int
        event;
    DUL_ABORTITEMS
        abortItems;

    network = (PRIVATE_NETWORKKEY **) callerNetworkKey;
    association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;
    OFCondition cond = checkNetwork(network);
    if (cond.bad()) return cond;

    if (((*network)->applicationFunction & DICOM_APPLICATION_ACCEPTOR) == 0) {
        return DUL_ILLEGALACCEPT;
    }

    if (params->maxPDU < MIN_PDU_LENGTH || params->maxPDU > MAX_PDU_LENGTH)
        return makeDcmnetCondition(DULC_ILLEGALPARAMETER, OF_error, "DUL Illegal parameter (maxPDU) in function DUL_ReceiveAssociationRQ");

    cond = createAssociationKey(network, "", params->maxPDU, association);
    if (cond.bad())
        return cond;

    if (block == DUL_NOBLOCK)
        DCMNET_TRACE("setting association receive timeout to " << timeout << " seconds");

    if (activatePDUStorage) DUL_activateAssociatePDUStorage(*association);
    clearRequestorsParams(params);

    cond = receiveTransportConnection(network, block, timeout, params, association);

    if (cond.bad() || (cond.code() == DULC_FORKEDCHILD))
    {
        destroyAssociationKey(association);
        *association = NULL;
        return cond;
    }

    cond = PRV_StateMachine(network, association,
                  TRANS_CONN_INDICATION, (*network)->protocolState, params);
    if (cond.bad())
        return cond;

    /* This is the first time we read from this new connection, so in case it
     * doesn't speak DICOM, we shouldn't wait forever (= DUL_NOBLOCK).
     */
    DCMNET_TRACE("setting timeout for first PDU to be read to " << (*association)->timeout << " seconds");
    cond = PRV_NextPDUType(association, DUL_NOBLOCK, (*association)->timeout, &pduType);

    if (cond == DUL_NETWORKCLOSED)
        event = TRANS_CONN_CLOSED;
    else if (cond == DUL_READTIMEOUT)
        event = ARTIM_TIMER_EXPIRED;
    else if (cond.bad())
        return cond;
    else {
        switch (pduType) {
        case DUL_TYPEASSOCIATERQ:
            event = A_ASSOCIATE_RQ_PDU_RCV;
            break;
        case DUL_TYPEASSOCIATEAC:
            event = A_ASSOCIATE_AC_PDU_RCV;
            break;
        case DUL_TYPEASSOCIATERJ:
            event = A_ASSOCIATE_RJ_PDU_RCV;
            break;
        case DUL_TYPEDATA:
            event = P_DATA_TF_PDU_RCV;
            break;
        case DUL_TYPERELEASERQ:
            event = A_RELEASE_RQ_PDU_RCV;
            break;
        case DUL_TYPERELEASERP:
            event = A_RELEASE_RP_PDU_RCV;
            break;
        case DUL_TYPEABORT:
            event = A_ABORT_PDU_RCV;
            break;
        default:
            event = INVALID_PDU;
            break;
        }
    }
    cond = PRV_StateMachine(network, association, event,
                            (*association)->protocolState, params);
    if (cond == DUL_UNSUPPORTEDPEERPROTOCOL) {
        abortItems.result = DUL_REJECT_PERMANENT;
        abortItems.source = DUL_ULSP_ACSE_REJECT;
        abortItems.reason = DUL_ULSP_ACSE_UNSUP_PROTOCOL;
        (void) PRV_StateMachine(NULL, association,
                                A_ASSOCIATE_RESPONSE_REJECT,
                                (*association)->protocolState, &abortItems);
    }
    return cond;
}


/* DUL_AcknowledgeAssociationRQ
**
** Purpose:
**      This function is used by an Acceptor to acknowledge an Association
**      Request.  The caller passes the partially completed Association Key
**      and the Association Items (syntax items) which describe the Association.
**      This function constructs an Acknowledge PDU and sends it to the
**      Requestor.  At this point, an Association is established.
**
** Parameter Dictionary:
**      callerAssociation   Caller's handle to the Association that is to be
**                          acknowledged and hence established.
**      params              Parameters that describe the type of service handled
**                          by this Association.
**      activatePDUStorage
**
** Return Values:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_AcknowledgeAssociationRQ(
  DUL_ASSOCIATIONKEY ** callerAssociation,
  DUL_ASSOCIATESERVICEPARAMETERS * params,
  int activatePDUStorage)
{
    PRIVATE_ASSOCIATIONKEY
        ** association;

    association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;
    OFCondition cond = checkAssociation(association);
    if (cond.bad()) return cond;

    if (activatePDUStorage) DUL_activateAssociatePDUStorage(*association);

    cond = PRV_StateMachine(NULL, association,
        A_ASSOCIATE_RESPONSE_ACCEPT, (*association)->protocolState, params);

    return cond;

}


/* DUL_RejectAssociationRQ
**
** Purpose:
**      This function is used to reject an Association Request and destroy
**      the corresponding Association Key.  The caller indicates if the
**      reject is permanent or transient and the reason for the reject.
**      This function constructs a Reject PDU and sends it to the connected
**      peer.  The Association Key is then destroyed and the caller's reference
**      to the key destroyed to prevent misuse.
**
** Parameter Dictionary:
**      callerAssociation   Caller's handle to the association that is to be
**                          rejected.
**      params              Pointer to a structure that gives the reasons for
**                          rejecting this Association.
**      activatePDUStorage
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_RejectAssociationRQ(
  DUL_ASSOCIATIONKEY ** callerAssociation,
  DUL_ABORTITEMS * params,
  int activatePDUStorage)
{
    PRIVATE_ASSOCIATIONKEY
        ** association;
    DUL_ABORTITEMS
        localParams;

    association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;
    OFCondition cond = checkAssociation(association);
    if (cond.bad()) return cond;

    if (activatePDUStorage) DUL_activateAssociatePDUStorage(*association);

    localParams = *params;
    /* check "Source" field */
    {
        unsigned char sourcetable[] = {0x01, 0x02, 0x03};
        int l_index;
        OFBool found = OFFalse;
        for (l_index = 0; l_index < (int) DIM_OF(sourcetable) && !found; l_index++)
            found = (localParams.source == sourcetable[l_index]);

        if (!found)
        {
            OFOStringStream stream;
            stream << "DUL Illegal source for rejecting Association: "
                   << localParams.source << OFStringStream_ends;
            OFSTRINGSTREAM_GETOFSTRING(stream, msg)
            return makeDcmnetCondition(DULC_ILLEGALREJECTSOURCE, OF_error, msg.c_str());
        }
    }
    /* check "Reason/Diag." field */
    {
        OFBool found = OFFalse;
        switch (localParams.source)
        {
            case ASC_SOURCE_SERVICEUSER:                            /* 0x01 */
                found = (localParams.reason == 0x01) || (localParams.reason == 0x02) ||
                        (localParams.reason == 0x03) || (localParams.reason == 0x07);
                break;
            case ASC_SOURCE_SERVICEPROVIDER_ACSE_RELATED:           /* 0x02 */
                found = (localParams.reason == 0x01) || (localParams.reason == 0x02);
                break;
            case ASC_SOURCE_SERVICEPROVIDER_PRESENTATION_RELATED:   /* 0x03 */
                found = (localParams.reason == 0x01) || (localParams.reason == 0x02);
                break;
        }

        if (!found)
        {
            OFOStringStream stream;
            stream << "DUL Illegal reason for rejecting Association: "
                   << localParams.reason << OFStringStream_ends;
            OFSTRINGSTREAM_GETOFSTRING(stream, msg)
            return makeDcmnetCondition(DULC_ILLEGALREJECTREASON, OF_error, msg.c_str());
        }
    }
    /* check "Result" field */
    {
        unsigned char resulttable[] = {0x01, 0x02};
        int l_index;
        OFBool found = OFFalse;
        for (l_index = 0; l_index < (int) DIM_OF(resulttable) && !found; l_index++)
            found = (localParams.result == resulttable[l_index]);

        if (!found)
        {
            OFOStringStream stream;
            stream << "DUL Illegal result for rejecting Association: "
                   << localParams.result << OFStringStream_ends;
            OFSTRINGSTREAM_GETOFSTRING(stream, msg)
            return makeDcmnetCondition(DULC_ILLEGALREJECTRESULT, OF_error, msg.c_str());
        }
    }
    cond = PRV_StateMachine(NULL, association,
                            A_ASSOCIATE_RESPONSE_REJECT, (*association)->protocolState, &localParams);

    return cond;
}


/* DUL_DropAssociation
**
** Purpose:
**      This function drops an Association without notifying the peer
**      application and destroys the Association Key.  The caller's
**      reference to the Association Key is also destroyed to prevent misuse.
**      This routine is called if a peer disconnects from you or if you
**      want to drop an Association without notifying the peer (can be
**      used in the unix environment if you use the fork call and have
**      two open channels to the peer).
**
** Parameter Dictionary:
**      callerAssociation  Caller's handle to the Association that is to
**                         be dropped.
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_DropAssociation(DUL_ASSOCIATIONKEY ** callerAssociation)
{
    PRIVATE_ASSOCIATIONKEY
        ** association;

    association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;
    OFCondition cond = checkAssociation(association);
    if (cond.bad()) return cond;

    if ((*association)->connection)
    {
     (*association)->connection->close();
     delete (*association)->connection;
     (*association)->connection = NULL;
    }
    destroyAssociationKey(association);
    return EC_Normal;
}


/* DUL_CloseTransportConnection
**
** Purpose:
**      This function closes the transport connection of an Association
**      without notifying the peer application. This routine should only
**      be used by the parent process after an association has been
**      delegated to a forked child.
**
** Parameter Dictionary:
**      callerAssociation  Caller's handle to the Association that is to
**                         be dropped.
**
** Return Values:
**
**
*/
OFCondition
DUL_CloseTransportConnection(DUL_ASSOCIATIONKEY ** callerAssociation)
{
    PRIVATE_ASSOCIATIONKEY ** association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;
    OFCondition cond = checkAssociation(association);
    if (cond.bad()) return cond;

    if ((*association)->connection)
    {
     (*association)->connection->closeTransportConnection();
     delete (*association)->connection;
     (*association)->connection = NULL;
    }
    destroyAssociationKey(association);
    return EC_Normal;
}


/* DUL_ReleaseAssociation
**
** Purpose:
**      Request the orderly release of an Association.
**
** Parameter Dictionary:
**      callerAssociation  Caller's handle to the Association to be released.
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_ReleaseAssociation(DUL_ASSOCIATIONKEY ** callerAssociation)
{
    PRIVATE_ASSOCIATIONKEY
        ** association;
    unsigned char
        pduType;
    int
        event;

    association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;
    OFCondition cond = checkAssociation(association);
    if (cond.bad()) return cond;

    cond = PRV_StateMachine(NULL, association,
                        A_RELEASE_REQ, (*association)->protocolState, NULL);
    if (cond.bad())
        return cond;

    cond = PRV_NextPDUType(association, DUL_NOBLOCK, PRV_DEFAULTTIMEOUT, &pduType);
    if (cond == DUL_NETWORKCLOSED)
        event = TRANS_CONN_CLOSED;
    else if (cond == DUL_READTIMEOUT)
        event = ARTIM_TIMER_EXPIRED;
    else if (cond.bad())
        return cond;
    else {
        switch (pduType) {
        case DUL_TYPEASSOCIATERQ:
            event = A_ASSOCIATE_RQ_PDU_RCV;
            break;
        case DUL_TYPEASSOCIATEAC:
            event = A_ASSOCIATE_AC_PDU_RCV;
            break;
        case DUL_TYPEASSOCIATERJ:
            event = A_ASSOCIATE_RJ_PDU_RCV;
            break;
        case DUL_TYPEDATA:
            event = P_DATA_TF_PDU_RCV;
            break;
        case DUL_TYPERELEASERQ:
            event = A_RELEASE_RQ_PDU_RCV;
            break;
        case DUL_TYPERELEASERP:
            event = A_RELEASE_RP_PDU_RCV;
            break;
        case DUL_TYPEABORT:
            event = A_ABORT_PDU_RCV;
            break;
        default:
            event = INVALID_PDU;
            break;
        }
    }
    return PRV_StateMachine(NULL, association, event,(*association)->protocolState, NULL);
}


/* DUL_AcknowledgeRelease
**
** Purpose:
**      Send Acknowledgement to the Release request
**
** Parameter Dictionary:
**      callerAssociation  Caller's handle to the Association whose
**                         release is acknowledged.
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_AcknowledgeRelease(DUL_ASSOCIATIONKEY ** callerAssociation)
{
    PRIVATE_ASSOCIATIONKEY
        ** association;

    association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;
    OFCondition cond = checkAssociation(association);
    if (cond.bad()) return cond;

    cond = PRV_StateMachine(NULL, association,
                       A_RELEASE_RESP, (*association)->protocolState, NULL);
    if (cond.bad())
        return cond;
//    cond = PRV_StateMachine(NULL, association,
//                ARTIM_TIMER_EXPIRED, (*association)->protocolState, NULL);
    return cond;
}


/* DUL_AbortAssociation
**
** Purpose:
**      Abort an association by sending an A-ABORT PDU and waiting for the
**      network to close.
**
** Parameter Dictionary:
**      callerAssociation  The handle for the association to be aborted.
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_AbortAssociation(DUL_ASSOCIATIONKEY ** callerAssociation)
{
    DUL_ABORTITEMS abortItems = { 0, DUL_SCU_INITIATED_ABORT, 0 };
    int event = 0;
    unsigned char pduType = 0;
    OFCondition tcpError = makeDcmnetCondition(DULC_TCPIOERROR, OF_error, "");

    PRIVATE_ASSOCIATIONKEY ** association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;
    OFCondition cond = checkAssociation(association);
    if (cond.bad()) return cond;

    cond = PRV_StateMachine(NULL, association, A_ABORT_REQ, (*association)->protocolState, &abortItems);
    if (cond.bad()) return cond;

    OFBool done = OFFalse;
    while (!done)
    {
        cond = PRV_NextPDUType(association, DUL_NOBLOCK, PRV_DEFAULTTIMEOUT, &pduType); // may return DUL_NETWORKCLOSED.

        if (cond == DUL_NETWORKCLOSED) event = TRANS_CONN_CLOSED;
        else if (cond == DUL_READTIMEOUT) event = ARTIM_TIMER_EXPIRED;
        else
        {
            switch (pduType)
            {
              case DUL_TYPEASSOCIATERQ:
                event = A_ASSOCIATE_RQ_PDU_RCV;
                break;
              case DUL_TYPEASSOCIATEAC:
                event = A_ASSOCIATE_AC_PDU_RCV;
                break;
              case DUL_TYPEASSOCIATERJ:
                event = A_ASSOCIATE_RJ_PDU_RCV;
                break;
              case DUL_TYPEDATA:
                event = P_DATA_TF_PDU_RCV;
                break;
              case DUL_TYPERELEASERQ:
                event = A_RELEASE_RQ_PDU_RCV;
                break;
              case DUL_TYPERELEASERP:
                event = A_RELEASE_RP_PDU_RCV;
                break;
              case DUL_TYPEABORT:
                event = A_ABORT_PDU_RCV;
                break;
              default:
                event = INVALID_PDU;
                break;
            }
        }

        cond = PRV_StateMachine(NULL, association, event, (*association)->protocolState, NULL);
        if (cond.bad()) // cond may be DUL_NETWORKCLOSED.
        {
          if (cond == DUL_NETWORKCLOSED) event = TRANS_CONN_CLOSED;
          else if (cond == DUL_READTIMEOUT) event = ARTIM_TIMER_EXPIRED;
          else event = INVALID_PDU;
          cond = PRV_StateMachine(NULL, association, event, (*association)->protocolState, NULL);
        }
        // the comparison with tcpError prevents a potential infinite loop if
        // we are receiving garbage over the network connection.
        if (cond.good() || (cond == tcpError)) done = OFTrue;
    }
    return EC_Normal;
}


/* DUL_WritePDVs
**
** Purpose:
**      Write a list of PDVs on an active Association.
**
** Parameter Dictionary:
**      callerAssociation  Caller's handle to the Association
**      pdvList            Pointer to a structure which describes the
**                         list of PDVs to be written on the active
**                         Association.
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_WritePDVs(DUL_ASSOCIATIONKEY ** callerAssociation,
              DUL_PDVLIST * pdvList)
{
    PRIVATE_ASSOCIATIONKEY
        ** association;

    /* assign association to local variable */
    association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;

    /* check if association is valid, if not return an error */
    OFCondition cond = checkAssociation(association);
    if (cond.bad()) return cond;

    /* call the finite state machine to invoke an action function given the current */
    /* event (P_DATA_REQ) and state (captured in (*association)->protocolState) */
    cond = PRV_StateMachine(NULL, association, P_DATA_REQ,
                            (*association)->protocolState, pdvList);

    return cond;
}


/* DUL_ReadPDVs
**
** Purpose:
**      Read the next available PDU.
**
** Parameter Dictionary:
**      callerAssociation  Caller's handle for the Association.
**      pdvList            Pointer to a structure which describes the
**                         list of PDVs to be read from the active
**                         Association.
**      block              Option used for blocking/non-blocking read.
**      timeout            Timeout interval.
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_ReadPDVs(DUL_ASSOCIATIONKEY ** callerAssociation,
             DUL_PDVLIST * pdvList, DUL_BLOCKOPTIONS block, int timeout)
{
    PRIVATE_ASSOCIATIONKEY
        ** association;
    unsigned char
        pduType;
    int
        event;

    /* assign the association to local variable */
    association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;

    /* check if association is valid, if not return an error */
    OFCondition cond = checkAssociation(association);
    if (cond.bad()) return cond;

    /* determine the type of the next PDU (in case the association */
    /* does not contain PDU header information yet, we need to try */
    /* to receive PDU header information on the network) */
    cond = PRV_NextPDUType(association, block, timeout, &pduType);

    /* evaluate the return value of the above called function */
    if (cond == DUL_NETWORKCLOSED) event = TRANS_CONN_CLOSED;
    else if ((cond == DUL_READTIMEOUT) && (block == DUL_NOBLOCK)) return cond;
    else if (cond == DUL_READTIMEOUT) event = ARTIM_TIMER_EXPIRED;
    else if (cond.bad()) return cond;
    else
    {
        /* if we successfully determined the type of the next PDU, */
        /* we need to set the event variable correspondingly */
        switch (pduType)
        {
          case DUL_TYPEASSOCIATERQ:
            event = A_ASSOCIATE_RQ_PDU_RCV;
            break;
          case DUL_TYPEASSOCIATEAC:
            event = A_ASSOCIATE_AC_PDU_RCV;
            break;
          case DUL_TYPEASSOCIATERJ:
            event = A_ASSOCIATE_RJ_PDU_RCV;
            break;
          case DUL_TYPEDATA:
            event = P_DATA_TF_PDU_RCV;
            break;
          case DUL_TYPERELEASERQ:
            event = A_RELEASE_RQ_PDU_RCV;
            break;
          case DUL_TYPERELEASERP:
            event = A_RELEASE_RP_PDU_RCV;
            break;
          case DUL_TYPEABORT:
            event = A_ABORT_PDU_RCV;
            break;
          default:
            event = INVALID_PDU;
            break;
        }
    }

    /* call the finite state machine to invoke an action function given the current */
    /* event and state (captured in (*association)->protocolState) */
    cond = PRV_StateMachine(NULL, association, event,
                            (*association)->protocolState, pdvList);

    /* return result value */
    return cond;
}


/* DUL_AssociationParameter
**
** Purpose:
**      This function examines the Association parameters and returns
**      a single parameter requested by the caller.
**
** Parameter Dictionary:
**      callerAssociation  Caller's handle to the Association.
**      param              The only supported value is DUL_K_MAX_PDV_XMIT.
**      type               The TYPE of the parameter requested.
**      address            Requested parameter to be obtained from the
**                         Association key.
**      length             The size of the parameter requested.
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_AssociationParameter(DUL_ASSOCIATIONKEY ** callerAssociation,
                         DUL_ASSOCIATION_PARAMETER param, DUL_DATA_TYPE type,
                         void *address, size_t length)
{
    PRIVATE_ASSOCIATIONKEY
        ** association;

    association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;
    OFCondition cond = checkAssociation(association);
    if (cond.bad()) return cond;

    switch (param)
    {
    case DUL_K_MAX_PDV_XMIT:
        if ((*association)->applicationFunction == DICOM_APPLICATION_ACCEPTOR)
        {
            cond = get_association_parameter(
                                         &((*association)->maxPDVRequestor),
                     DUL_K_INTEGER, sizeof((*association)->maxPDVRequestor),
                                             type, address, length);
        } else {
            cond = get_association_parameter(
                                          &((*association)->maxPDVAcceptor),
                      DUL_K_INTEGER, sizeof((*association)->maxPDVAcceptor),
                                             type, address, length);
        }
        if (cond.bad()) return cond;
        break;
    }
    return cond;
}


/* DUL_NextPDV
**
** Purpose:
**      Return the next PDV to the caller.
**
** Parameter Dictionary:
**      callerAssociation  Caller's handle to the Association
**      pdv                The next PDU to be returned
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_NextPDV(DUL_ASSOCIATIONKEY ** callerAssociation, DUL_PDV * pdv)
{
    PRIVATE_ASSOCIATIONKEY
        ** association;
    unsigned char
       *p;
    unsigned long
        pdvLength;

    /* assign the association to local variable */
    association = (PRIVATE_ASSOCIATIONKEY **) callerAssociation;

    /* check if association is valid, if not return an error */
    OFCondition cond = checkAssociation(association);
    if (cond.bad()) return cond;

    /* check if the association does currently not contain any */
    /* (unprocessed) PDVs, return a corresponding result value */
    if ((*association)->pdvIndex == -1)
     /* in this special case we want to avoid a message on the
        condition stack because this is no real error, but normal
        behaviour - A callback function registered in the condition stack
        would (unnecessarily) be called once for each PDV.
        the #ifdef allows to mimic the old behaviour.
      */
    return DUL_NOPDVS;

    /* if there is an unprocessed PDV, assign it to the out parameter */
    *pdv = (*association)->currentPDV;

    /* indicate that the current PDV was read by increasing the association's PDV index variable */
    (*association)->pdvIndex++;

    /* if the association's pdvIndex does now show a value equal to or greater */
    /* than pdvCount there are no more unprocessed PDVs contained in the association. */
    /* Indicate this fact by setting the association's pdvIndex to -1.*/
    if ((*association)->pdvIndex >= (*association)->pdvCount)
        (*association)->pdvIndex = -1;
    else {
        /* if the association still contains unprocessed PDVs, we need to reset the association's */
        /* currentPDV variable so that it contains the data of the next unprocessed PDV */
        /* (currentPDV shall always contain the next unprocessed PDV.) */

        /* 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. Remember this address in a local variable. */
        p = (*association)->pdvPointer;

        /* move this pointer to the next (unprocessed) PDV which is contained in the association. */
        /* (We need to move the pointer 4 bytes to the right (over the PDV length field of the */
        /* current PDV), another 2 bytes to the right (over the presentation context ID and */
        /* message control header field of the current PDV) and another currentPDV.fragmentLength */
        /* bytes to the right (over the actual data fragment of the current PDV). */
        p += (*association)->currentPDV.fragmentLength + 2 + 4;

        /* 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;

        /* and finally, after the association's currentPDV variable has been completely set to the next */
        /* (unprocessed) PDV, we need to update the association's pdvPointer, so that it again points */
        /* to the address of the PDV which is represented by the association's currentPDV variable. */
        (*association)->pdvPointer += 4 + pdvLength;
    }
    return EC_Normal;
}


/* DUL_ClearServiceParameters
**
** Purpose:
**      DUL_ClearServiceParameters is used to clear the lists that were
**      constructed in a DUL_ASSOCIATEDSERVICEPARAMETERS structure.  The
**      lists in that structure were built to contain the requested
**      and accepted Presentation Contexts.  Once the lists were built,
**      an Association request could be made.  After the Association
**      has been closed, the Presentation Contexts need to be discarded
**      so that the same structure can be reused for a new Association.
**      This function removes all of the nodes from the requested
**      and accepted Presentation Context lists and then destroys the
**      lists themselves.
**
** Parameter Dictionary:
**      params  Pointer to a DUL_ASSOCIATESERVICEPARAMETERS structure
**              to be cleared.
**
** Return Values:
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFCondition
DUL_ClearServiceParameters(DUL_ASSOCIATESERVICEPARAMETERS * params)
{
    // Clear requested and accepted presentation contexts
    clearPresentationContext(&params->requestedPresentationContext);
    clearPresentationContext(&params->acceptedPresentationContext);
    // Delete structures of Extended SOP Class Negotiation request
    if (params->requestedExtNegList)
    {
      deleteListMembers(*params->requestedExtNegList);
      delete params->requestedExtNegList; params->requestedExtNegList = NULL;
    }
    // Delete structures of Extended SOP Class Negotiation acknowledge
    if (params->acceptedExtNegList)
    {
      deleteListMembers(*params->acceptedExtNegList);
      delete params->acceptedExtNegList; params->acceptedExtNegList = NULL;
    }
    // Delete User Identity Negotiation request and ack structures
    delete params->reqUserIdentNeg; params->reqUserIdentNeg = NULL;
    delete params->ackUserIdentNeg; params->ackUserIdentNeg = NULL;
    return EC_Normal;
}


/*  ========================================================================
 *  Private functions not meant for users of the package are included below.
 */


/* receiveTransportConnection
**
** Purpose:
**      Receive a transport connection and fill in various fields of the
**      service parameters and Association handle.
** Parameter Dictionary:
**      network      Pointer to a structure maintaining information about
**                   the network environment.
**      block        Option indicating blocking/non-blocking mode
**      timeout      When blocking mode is non-blocking, the timeout in seconds
**      params       Pointer to structure describing the services for the
**                   Association.
**      association  Handle to the association
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
receiveTransportConnection(PRIVATE_NETWORKKEY ** network,
                           DUL_BLOCKOPTIONS block,
                           int timeout,
                           DUL_ASSOCIATESERVICEPARAMETERS * params,
                           PRIVATE_ASSOCIATIONKEY ** association)
{
  return receiveTransportConnectionTCP(network, block, timeout, params, association);
}


/* receiveTransportConnectionTCP
**
** Purpose:
**      Receive a TCP transport connection and fill in the fields of the
**      service parameters and the Association handle.
**
** Parameter Dictionary:
**      network      Pointer to a structure maintaining information about
**                   the network environment.
**      block        Option indicating blocking/non-blocking mode
**      timeout      When blocking mode is non-blocking, the timeout in seconds
**      params       Pointer to structure describing the services for the
**                   Association.
**      association  Handle to the association
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
receiveTransportConnectionTCP(PRIVATE_NETWORKKEY ** network,
                              DUL_BLOCKOPTIONS block,
                              int timeout,
                              DUL_ASSOCIATESERVICEPARAMETERS * params,
                              PRIVATE_ASSOCIATIONKEY ** association)
{
#ifndef DCMTK_HAVE_POLL
    fd_set fdset;
#endif
    struct timeval timeout_val;
    socklen_t len;
    int nfound, connected;
    struct sockaddr from;
    struct linger sockarg;

#ifdef HAVE_FORK
    pid_t pid = -1;
#endif

    (void) memset(&sockarg, 0, sizeof(sockarg));

    int reuse = 1;

#ifdef _WIN32
    SOCKET sock = dcmExternalSocketHandle.get();
    if (sock != INVALID_SOCKET)
#else
    int sock = dcmExternalSocketHandle.get();
    if (sock > 0)
#endif
    {
      // use the socket file descriptor provided to us externally
      // instead of calling accept().
      connected = 1;

      len = sizeof(from);
      if (getpeername(sock, &from, &len))
      {
          OFOStringStream stream;
          stream << "TCP Initialization Error: " << OFStandard::getLastNetworkErrorCode().message()
                 << ", getpeername failed on socket " << sock << OFStringStream_ends;
          OFSTRINGSTREAM_GETOFSTRING(stream, msg)
          return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
      }
    }
    else
    {
        if (block == DUL_NOBLOCK)
        {
            connected = 0;
#ifdef DCMTK_HAVE_POLL
            struct pollfd pfd[] =
            {
                { (*network)->networkSpecific.TCP.listenSocket, POLLIN, 0 }
            };
#else
             FD_ZERO(&fdset);
#ifdef __MINGW32__
            // on MinGW, FD_SET expects an unsigned first argument
            FD_SET((unsigned int)((*network)->networkSpecific.TCP.listenSocket), &fdset);
#else
            FD_SET((*network)->networkSpecific.TCP.listenSocket, &fdset);
#endif /* __MINGW32__ */
#endif /* DCMTK_HAVE_POLL */

            timeout_val.tv_sec = timeout;
            timeout_val.tv_usec = 0;

#ifdef DCMTK_HAVE_POLL
            nfound = poll(pfd, 1, timeout_val.tv_sec*1000+(timeout_val.tv_usec/1000));
#else
            // On Win32, it is safe to cast the first parameter to int
            // because Windows ignores this parameter anyway.
            nfound = select(
              OFstatic_cast(int, (*network)->networkSpecific.TCP.listenSocket + 1),
                           &fdset, NULL, NULL, &timeout_val);
#endif /* DCMTK_HAVE_POLL*/

            if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
            {
                DU_logSelectResult(nfound);
            }
            if (nfound > 0) {
#ifdef DCMTK_HAVE_POLL
                if (pfd[0].revents & POLLIN)
                    connected++;
#else
                if (FD_ISSET((*network)->networkSpecific.TCP.listenSocket, &fdset))
                    connected++;
#endif
            }
            if (!connected) return DUL_NOASSOCIATIONREQUEST;
        }
        else
        {
            connected = 0;
            do {
#ifdef DCMTK_HAVE_POLL
                struct pollfd pfd[]=
                {
                    { (*network)->networkSpecific.TCP.listenSocket, POLLIN, 0 }
                };
#else
                FD_ZERO(&fdset);
#ifdef __MINGW32__
                // on MinGW, FD_SET expects an unsigned first argument
                FD_SET((unsigned int)((*network)->networkSpecific.TCP.listenSocket), &fdset);
#else
                FD_SET((*network)->networkSpecific.TCP.listenSocket, &fdset);
#endif /* __MINGW32__ */
#endif /* DCMTK_HAVE_POLL */
                timeout_val.tv_sec = 5;
                timeout_val.tv_usec = 0;
#ifdef DCMTK_HAVE_POLL
                nfound = poll(pfd, 1, timeout_val.tv_sec*1000+(timeout_val.tv_usec/1000));
#else
                // On Win32, it is safe to cast the first parameter to int
                // because Windows ignores this parameter anyway.
                nfound = select(
                  OFstatic_cast(int, (*network)->networkSpecific.TCP.listenSocket + 1),
                                &fdset, NULL, NULL, &timeout_val);
#endif /* DCMTK_HAVE_POLL */
                if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL))
                {
                    DU_logSelectResult(nfound);
                }
                if (nfound > 0) {
#ifdef DCMTK_HAVE_POLL
                    if (pfd[0].revents & POLLIN)
                        connected++;
#else
                    if (FD_ISSET((*network)->networkSpecific.TCP.listenSocket, &fdset))
                        connected++;
#endif
                }
            } while (!connected);
        }

        len = sizeof(from);
        do
        {
            sock = accept((*network)->networkSpecific.TCP.listenSocket, &from, &len);
#ifdef _WIN32
        } while (sock == INVALID_SOCKET && WSAGetLastError() == WSAEINTR);
        if (sock == INVALID_SOCKET)
#else
        } while (sock == -1 && errno == EINTR);
        if (sock < 0)
#endif
        {
            OFOStringStream stream;
            stream << "TCP Initialization Error: " << OFStandard::getLastNetworkErrorCode().message()
                   << ", accept failed on socket " << sock << OFStringStream_ends;
            OFSTRINGSTREAM_GETOFSTRING(stream, msg)
            return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
        }

#ifdef FD_CLOEXEC
        // prevent socket leakage to child programs executed with exec()
        int flags = fcntl(sock, F_GETFD, 0);
        fcntl(sock, F_SETFD, FD_CLOEXEC | flags);
#endif
    }

#ifdef HAVE_FORK
    if (shouldFork)
    {
        // fork for unix
        pid = fork();
        if (pid > 0)
        {
            // we're the parent process, close accepted socket and return
            close(sock);

            OFOStringStream stream;
            stream << "New child process started with pid " << pid << OFStringStream_ends;
            OFSTRINGSTREAM_GETOFSTRING(stream, msg)
            return makeDcmnetCondition(DULC_FORKEDCHILD, OF_ok, msg.c_str());
        }
        else if (pid < 0)
        {
            // fork failed, return error code
            close(sock);

            OFString msg = "Multi-Process Error: ";
            msg += OFStandard::getLastSystemErrorCode().message();
            msg += ", fork failed";
            return makeDcmnetCondition(DULC_CANNOTFORK, OF_error, msg.c_str());
        }
        else
        {
          // we're the child process, continue normally
          processIsForkedChild = OFTrue;
        }
    }
#elif defined(_WIN32)
    if (shouldFork && (command_argc > 0) && command_argv)
    {
        // win32 code to create new child process
        HANDLE childSocketHandle;
        HANDLE hChildStdInRead;
        HANDLE hChildStdInWrite;
        HANDLE hChildStdInWriteDup;

        SECURITY_ATTRIBUTES sa;
        sa.nLength = sizeof(SECURITY_ATTRIBUTES);
        sa.bInheritHandle = TRUE;
        sa.lpSecurityDescriptor = NULL;

        // prepare the command line
        OFString cmdLine = command_argv[0];
        cmdLine += " --forked-child";
        for (int i=1; i < command_argc; ++i)
        {
            /* copy each argv value and surround it with double quotes
             * to keep option values containing a space glued together
             */
            cmdLine += " \"";
            cmdLine += command_argv[i];
            /* if last character in argument value is a backslash, escape it
             * since otherwise it would escape the quote appended in the following
             * step, i.e. make sure that something like '\my\dir\' does not become
             * '"\my\dir\"' but instead ends up as '"\my\dir\\"' (single quotes for
             *  demonstration purposes). Make sure nobody passes a zero length string.
             */
            size_t len2 = strlen(command_argv[i]);
            if ((len2 > 0) && (command_argv[i][len2 - 1] == '\\'))
            {
                cmdLine += "\\";
            }
            cmdLine += "\"";
        }

        // create anonymous pipe
        if (!CreatePipe(&hChildStdInRead, &hChildStdInWrite, &sa,0))
        {
            OFOStringStream stream;
            stream << "Multi-Process Error: Creating anonymous pipe failed with error code "
                   << GetLastError() << OFStringStream_ends;
            OFSTRINGSTREAM_GETOFSTRING(stream, msg)
            return makeDcmnetCondition(DULC_CANNOTFORK, OF_error, msg.c_str());
        }

        // create duplicate of write end handle of pipe
        if (!DuplicateHandle(GetCurrentProcess(), hChildStdInWrite,
                             GetCurrentProcess(), &hChildStdInWriteDup, 0,
                             FALSE, DUPLICATE_SAME_ACCESS))
        {
            return makeDcmnetCondition(DULC_CANNOTFORK, OF_error, "Multi-Process Error: Duplicating handle failed");
        }

        // destroy original write end handle of pipe
        CloseHandle(hChildStdInWrite);

        // we need a STARTUPINFO and a PROCESS_INFORMATION structure for CreateProcess.
        STARTUPINFOA si;
        PROCESS_INFORMATION pi;
        memset(&pi,0,sizeof(pi));
        memset(&si,0,sizeof(si));

        // prepare startup info for child process:
        // the child uses the same stdout and stderr as the parent, but
        // stdin is the read end of our anonymous pipe.
        si.cb = sizeof(si);
        si.dwFlags |= STARTF_USESTDHANDLES;
        si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
        si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
        si.hStdInput = hChildStdInRead;

        // create child process.
        if (!CreateProcessA(NULL,OFconst_cast(char *, cmdLine.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
        {
            OFOStringStream stream;
            stream << "Multi-Process Error: Creating process failed with error code "
                   << GetLastError() << OFStringStream_ends;
            OFSTRINGSTREAM_GETOFSTRING(stream, msg)
            return makeDcmnetCondition(DULC_CANNOTFORK, OF_error, msg.c_str());
        }
        else
        {
            // call OpenProcess to retrieve the REAL process handle.  using
            // GetCurrentProcess() only returns a pseudo handle which may not
            // allow DuplicateHandle to create the child process socket with
            // sufficient permissions on certain versions of Windows.
            HANDLE hParentProcessHandle = OpenProcess(PROCESS_DUP_HANDLE, FALSE, GetCurrentProcessId());
            if (hParentProcessHandle == NULL)
            {
                // unable to get process handle...
                // ...this should really never happen as we are opening the current process.
                CloseHandle(pi.hProcess);
                CloseHandle(pi.hThread);
                CloseHandle((HANDLE)sock);

                OFOStringStream stream;
                stream << "Multi-Process Error: Opening process to get real process handle failed with error code "
                       << GetLastError() << OFStringStream_ends;
                OFSTRINGSTREAM_GETOFSTRING(stream, msg)
                return makeDcmnetCondition(DULC_CANNOTFORK, OF_error, msg.c_str());
            }

            // PROCESS_INFORMATION pi now contains various handles for the new process.
            // Now that we have a handle to the new process, we can duplicate the
            // socket handle into the new child process.
            if (DuplicateHandle(hParentProcessHandle, (HANDLE)sock, pi.hProcess,
                &childSocketHandle, 0, TRUE, DUPLICATE_SAME_ACCESS))
            {
                // close handles in PROCESS_INFORMATION structure
                // and our local copy of the socket handle.
                CloseHandle(hParentProcessHandle);
                CloseHandle(pi.hProcess);
                CloseHandle(pi.hThread);
                closesocket(sock);

                // send number of socket handle in child process over anonymous pipe
                DWORD bytesWritten;
                char buf[30];
                // we pass the socket handle as a 64-bit unsigned integer, which should work for 32 and 64 bit Windows
                OFStandard::snprintf(buf, sizeof(buf), "%llu", OFreinterpret_cast(unsigned __int64, childSocketHandle));
                if (!WriteFile(hChildStdInWriteDup, buf, OFstatic_cast(DWORD, strlen(buf) + 1), &bytesWritten, NULL))
                {
                    CloseHandle(hChildStdInWriteDup);
                    return makeDcmnetCondition(DULC_CANNOTFORK, OF_error, "Multi-Process Error: Writing to anonymous pipe failed");
                }

                // return OF_ok status code DULC_FORKEDCHILD with descriptive text
                OFOStringStream stream;
                stream << "New child process started with pid " << OFstatic_cast(int, pi.dwProcessId)
                       << ", socketHandle " << OFstatic_cast(int, OFreinterpret_cast(size_t, childSocketHandle)) << OFStringStream_ends;
                OFSTRINGSTREAM_GETOFSTRING(stream, msg)
                return makeDcmnetCondition(DULC_FORKEDCHILD, OF_ok, msg.c_str());
            }
            else
            {
                // unable to duplicate handle. Close handles nevertheless
                // to avoid resource leak.
                CloseHandle(hParentProcessHandle);
                CloseHandle(pi.hProcess);
                CloseHandle(pi.hThread);
                return makeDcmnetCondition(DULC_CANNOTFORK, OF_error, "Multi-Process Error: Duplicating socket handle failed");
            }
        }
    }
#endif

    sockarg.l_onoff = 0;
    if (setsockopt(sock, SOL_SOCKET, SO_LINGER, (char *) &sockarg, sizeof(sockarg)) < 0)
    {
        OFOStringStream stream;
        stream << "TCP Initialization Error: " << OFStandard::getLastNetworkErrorCode().message()
               << ", setsockopt failed on socket " << sock << OFStringStream_ends;
        OFSTRINGSTREAM_GETOFSTRING(stream, msg)
        return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
    }
    reuse = 1;

#ifdef _WIN32
    if (setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *) &reuse, sizeof(reuse)) < 0)
#else
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &reuse, sizeof(reuse)) < 0)
#endif
    {
        OFString msg = "TCP Initialization Error: ";
        msg += OFStandard::getLastNetworkErrorCode().message();
        return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
    }
    setTCPBufferLength(sock);

    /*
     * 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
#ifdef _MSC_VER
#pragma message("The macro DONT_DISABLE_NAGLE_ALGORITHM is not supported anymore. See 'macros.txt' for details.")
#else
#warning The macro DONT_DISABLE_NAGLE_ALGORITHM is not supported anymore. See "macros.txt" for details.
#endif
#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("DUL: 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("DUL: disabling Nagle algorithm as defined at compilation time (DISABLE_NAGLE_ALGORITHM)");
#else
      DCMNET_DEBUG("DUL: disabling Nagle algorithm as requested at runtime (TCP_NODELAY=" << tcpNoDelayString << ")");
#endif
      if (setsockopt(sock, 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("DUL: do not disable Nagle algorithm as requested at runtime (TCP_NODELAY=" << tcpNoDelayString << ")");
#endif
    }

    // create string containing numerical IP address.
    OFString client_dns_name;
    char client_ip_address[20];
    OFStandard::snprintf(client_ip_address, sizeof(client_ip_address), "%-d.%-d.%-d.%-d",  // this code is ugly but thread safe
       ((int) from.sa_data[2]) & 0xff,
       ((int) from.sa_data[3]) & 0xff,
       ((int) from.sa_data[4]) & 0xff,
       ((int) from.sa_data[5]) & 0xff);

    if (! dcmDisableGethostbyaddr.get())
       client_dns_name = OFStandard::getHostnameByAddress(&from.sa_data[2], sizeof(struct in_addr), AF_INET);

    if (client_dns_name.length() == 0)
    {
        // reverse DNS lookup disabled or host not found, use numerical address
        OFStandard::strlcpy(params->callingPresentationAddress, client_ip_address,
          sizeof(params->callingPresentationAddress));
        OFStandard::strlcpy((*association)->remoteNode, client_ip_address, sizeof((*association)->remoteNode));
        DCMNET_DEBUG("Association Received: " << params->callingPresentationAddress );
    }
    else
    {
        char node[260];
        if ((*network)->options & DUL_FULLDOMAINNAME)
            OFStandard::strlcpy(node, client_dns_name.c_str(), sizeof(node));
        else {
            if (sscanf(client_dns_name.c_str(), "%[^.]", node) != 1)
                node[0] = '\0';
        }
        OFStandard::strlcpy((*association)->remoteNode, node, sizeof((*association)->remoteNode));
        OFStandard::strlcpy(params->callingPresentationAddress, node, sizeof(params->callingPresentationAddress));
        DCMNET_DEBUG("Association Received: " << params->callingPresentationAddress );
    }

#ifdef WITH_TCPWRAPPER
    const char *daemon = dcmTCPWrapperDaemonName.get();
    if (daemon)
    {
        // enforce access control using the TCP wrapper - see hosts_access(5).

        // if reverse DNS lookup is disabled, use default value
        if (client_dns_name.empty()) client_dns_name = STRING_UNKNOWN;

        struct request_info request;
        request_init(&request, RQ_CLIENT_NAME, client_dns_name.c_str(), 0);
        request_set(&request, RQ_CLIENT_ADDR, client_ip_address, 0);
        request_set(&request, RQ_USER, STRING_UNKNOWN, 0);
        request_set(&request, RQ_DAEMON, daemon, 0);

        if (! dcmtk_hosts_access(&request))
        {
#ifdef HAVE_WINSOCK_H
          (void) shutdown(sock,  1 /* SD_SEND */);
          (void) closesocket(sock);
#else
          (void) close(sock);
#endif
          OFOStringStream stream;
          stream << "TCP wrapper: denied connection from " << client_dns_name
                 << " (" << client_ip_address << ")" << OFStringStream_ends;
          OFSTRINGSTREAM_GETOFSTRING(stream, msg)
          return makeDcmnetCondition(DULC_TCPWRAPPER, OF_error, msg.c_str());
        }
    }
#endif

    if ((*association)->connection) delete (*association)->connection;

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

    if ((*association)->connection == NULL)
    {
#ifdef HAVE_WINSOCK_H
      (void) shutdown(sock,  1 /* SD_SEND */);
      (void) closesocket(sock);
#else
      (void) close(sock);
#endif
      OFString msg = "TCP Initialization Error: ";
      msg += OFStandard::getLastNetworkErrorCode().message();
      return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
    }

    return (*association)->connection->serverSideHandshake();
}


/* createNetworkKey
**
** Purpose:
**      Create a network key for the network environment.
**
** Parameter Dictionary:
**      mode     Role played by the application entity
**      timeout  The timeout value to be used for timers
**      opt
**      key      Pointer to the structure maintaining the entire
**               information of the network environment.
**               This is returned back to the caller.
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
createNetworkKey(const char *mode,
                 int timeout, unsigned long opt, PRIVATE_NETWORKKEY ** key)
{
    if (strcmp(mode, AE_REQUESTOR) != 0 &&
        strcmp(mode, AE_ACCEPTOR) != 0 &&
        strcmp(mode, AE_BOTH) != 0)
    {
        OFString msg = "Unrecognized Network Mode: ";
        msg += mode;
        return makeDcmnetCondition(DULC_ILLEGALPARAMETER, OF_error, msg.c_str());
    }
    *key = (PRIVATE_NETWORKKEY *) malloc(sizeof(PRIVATE_NETWORKKEY));
    if (*key == NULL) return EC_MemoryExhausted;
    OFStandard::strlcpy((*key)->keyType, KEY_NETWORK, sizeof((*key)->keyType));

    (*key)->applicationFunction = 0;

    if (strcmp(mode, AE_REQUESTOR) == 0)
        (*key)->applicationFunction |= DICOM_APPLICATION_REQUESTOR;
    else if (strcmp(mode, AE_ACCEPTOR) == 0)
        (*key)->applicationFunction |= DICOM_APPLICATION_ACCEPTOR;
    else
        (*key)->applicationFunction |=
            DICOM_APPLICATION_ACCEPTOR | DICOM_APPLICATION_REQUESTOR;

    (*key)->networkState = NETWORK_DISCONNECTED;
    (*key)->protocolState = STATE1;

    if (timeout > 0)
        (*key)->timeout = timeout;
    else
        (*key)->timeout = DEFAULT_TIMEOUT;

    (*key)->options = opt;

    return EC_Normal;
}


/* initializeNetworkTCP
**
** Purpose:
**      Create a socket and listen for connections on the port number
**
** Parameter Dictionary:
**      key        Handle to the network environment
**      parameter  Port number on which to listen for connection
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
initializeNetworkTCP(PRIVATE_NETWORKKEY ** key, void *parameter)
{
    struct linger sockarg;
    int reuse = 1;

    (void) memset(&sockarg, 0, sizeof(sockarg));

    // initialize network layer settings to well-defined state
    (*key)->networkSpecific.TCP.tLayer = NULL;
    (*key)->networkSpecific.TCP.tLayerOwned = 0;
    (*key)->networkSpecific.TCP.port = -1;
#ifdef _WIN32
    (*key)->networkSpecific.TCP.listenSocket = INVALID_SOCKET;
#else
    (*key)->networkSpecific.TCP.listenSocket = -1;
#endif

    // Create listen socket if we're an application acceptor,
    // unless the socket handle has already been passed to us or
    // we are a forked child of an application acceptor, in which
    // case the socket also already exists.
#ifdef _WIN32
    if ((dcmExternalSocketHandle.get() == INVALID_SOCKET) &&
#else
    if ((dcmExternalSocketHandle.get() < 0) &&
#endif
        ((*key)->applicationFunction & DICOM_APPLICATION_ACCEPTOR) &&
        (! processIsForkedChild))
    {

      socklen_t length;

#ifdef _WIN32
      SOCKET sock;
#else
      int sock;
#endif
      struct sockaddr_in server;

      /* Create socket for Internet type communication */
      (*key)->networkSpecific.TCP.port = *(int *) parameter;

      // Create socket and prevent leakage of the open socket to processes called with exec()
      // by using SOCK_CLOEXEC (where available) or FD_CLOEXEC (POSIX.1-2008)
#ifdef SOCK_CLOEXEC
      (*key)->networkSpecific.TCP.listenSocket = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
      sock = (*key)->networkSpecific.TCP.listenSocket;
#elif defined(FD_CLOEXEC)
      (*key)->networkSpecific.TCP.listenSocket = socket(AF_INET, SOCK_STREAM, 0);
      sock = (*key)->networkSpecific.TCP.listenSocket;
      if (sock >= 0)
      {
          int flags = fcntl(sock, F_GETFD, 0);
          fcntl(sock, F_SETFD, FD_CLOEXEC | flags);
      }
#else
      (*key)->networkSpecific.TCP.listenSocket = socket(AF_INET, SOCK_STREAM, 0);
      sock = (*key)->networkSpecific.TCP.listenSocket;
#endif

#ifdef _WIN32
      if (sock == INVALID_SOCKET)
#else
      if (sock < 0)
#endif
      {
        OFString msg = "TCP Initialization Error: ";
        msg += OFStandard::getLastNetworkErrorCode().message();
        return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
      }
      reuse = 1;
#ifdef _WIN32
      if (setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *) &reuse, sizeof(reuse)) < 0)
#else
      if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &reuse, sizeof(reuse)) < 0)
#endif
      {
        OFString msg = "TCP Initialization Error: ";
        msg += OFStandard::getLastNetworkErrorCode().message();
          return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
      }

      /* Name socket using wildcards */
      server.sin_family = AF_INET;
      server.sin_addr.s_addr = INADDR_ANY;
      server.sin_port = htons(OFstatic_cast(Uint16, ((*key)->networkSpecific.TCP.port)));
      if (bind(sock, (struct sockaddr *) & server, sizeof(server)))
      {
        OFString msg = "TCP Initialization Error: ";
        msg += OFStandard::getLastNetworkErrorCode().message();
        return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
      }
      /* Find out assigned port number and print it out */
      length = sizeof(server);
      if (getsockname(sock, (struct sockaddr *) &server, &length))
      {
        OFString msg = "TCP Initialization Error: ";
        msg += OFStandard::getLastNetworkErrorCode().message();
        return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
      }

      /* If port 0 was specified by the client, the OS has assigned an unused port. */
      if ((*key)->networkSpecific.TCP.port == 0) {
        const u_short assignedPort = ntohs(server.sin_port);
        (*key)->networkSpecific.TCP.port = assignedPort;
        *(int *) parameter = assignedPort;
      }

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

      /* Listen on the socket */
      if (listen(sock, PRV_LISTENBACKLOG) < 0)
      {
        OFString msg = "TCP Initialization Error: ";
        msg += OFStandard::getLastNetworkErrorCode().message();
        return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, msg.c_str());
      }
    }

    (*key)->networkSpecific.TCP.tLayer = new DcmTransportLayer();
    (*key)->networkSpecific.TCP.tLayerOwned = 1;
    if (NULL == (*key)->networkSpecific.TCP.tLayer)
    {
      return makeDcmnetCondition(DULC_TCPINITERROR, OF_error, "Cannot initialize DcmTransportLayer");
    }

    return EC_Normal;
}


/* createAssociationKey
**
** Purpose:
**      Create handle to the Association.
**
** Parameter Dictionary:
**      networkKey      Handle to the network environment
**      remoteNode      The remote node to which the association is
**                      to be set up.
**      maxPDU          Size of the maximum PDU.
**      associationKey  The handle to the Association that is to be
**                      returned.
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
createAssociationKey(PRIVATE_NETWORKKEY ** networkKey,
                     const char *remoteNode, unsigned long maxPDU,
                     PRIVATE_ASSOCIATIONKEY ** associationKey)
{
    PRIVATE_ASSOCIATIONKEY *key;

    key = (PRIVATE_ASSOCIATIONKEY *) malloc(
        size_t(sizeof(PRIVATE_ASSOCIATIONKEY) + maxPDU + 100));
    if (key == NULL) return EC_MemoryExhausted;
    key->receivePDUQueue = NULL;

    OFStandard::strlcpy(key->keyType, KEY_ASSOCIATION, sizeof(key->keyType));
    key->applicationFunction = (*networkKey)->applicationFunction;

    OFStandard::strlcpy(key->remoteNode, remoteNode, sizeof(key->remoteNode));
    key->presentationContextID = 0;
    key->timeout = (*networkKey)->timeout;
    key->timerStart = 0;
    key->maxPDVInput = maxPDU;
    key->fragmentBufferLength = maxPDU + 100;
    key->fragmentBuffer = (unsigned char *) key + sizeof(*key);

    key->pdvList.count = 0;
    key->pdvList.scratch = key->fragmentBuffer;
    key->pdvList.scratchLength = maxPDU;
    key->pdvList.abort.result = 0x00;
    key->pdvList.abort.source = 0x00;
    key->pdvList.abort.reason = 0x00;
    key->pdvList.pdv = NULL;

    key->inputPDU = NO_PDU;
    key->nextPDUType = 0x00;
    key->nextPDUReserved = 0;
    key->nextPDULength = 0;
    key->compatibilityMode = 0;
    key->pdvCount = 0;
    key->pdvIndex = -1;
    key->pdvPointer = NULL;
    (void) memset(&key->currentPDV, 0, sizeof(key->currentPDV));

    key->associatePDUFlag = 0;
    key->associatePDU = NULL;
    key->associatePDULength = 0;

    key->logHandle = NULL;
    key->connection = NULL;
    key->modeCallback = NULL;
    *associationKey = key;
    return EC_Normal;
}


/* destroyAssociationKey
**
** Purpose:
**      Destroy the handle to the Association.
**
** Parameter Dictionary:
**      key  Handle to the association.
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static void
destroyAssociationKey(PRIVATE_ASSOCIATIONKEY ** key)
{
    if (*key && (*key)->connection) delete (*key)->connection;
    free(*key);
    *key = NULL;
}


/* get_association_parameter
**
** Purpose:
**      Get a single parameter.
**
** Parameter Dictionary:
**      paramAddress   Source parameter
**      paramType      Type of the source parameter
**      paramLength    Size of the source parameter
**      outputType     Type of the destination parameter
**      outputAddress  Destination parameter returned to caller
**      outputLength   Size of the destination parameter
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
get_association_parameter(void *paramAddress,
                          DUL_DATA_TYPE paramType, size_t paramLength,
         DUL_DATA_TYPE outputType, void *outputAddress, size_t outputLength)
{
    if (paramType != outputType) return DUL_WRONGDATATYPE;
    if ((paramType == DUL_K_INTEGER) && (outputLength != paramLength)) return DUL_INCORRECTBUFFERLENGTH;
    if ((paramType == DUL_K_STRING) && (outputLength < strlen((char*)paramAddress))) return DUL_INSUFFICIENTBUFFERLENGTH;

    switch (paramType) {
      case DUL_K_INTEGER:
        (void) memcpy(outputAddress, paramAddress, paramLength);
        break;
      case DUL_K_STRING:
        OFStandard::strlcpy((char*)outputAddress, (char*)paramAddress, outputLength);
        break;
    }
    return EC_Normal;
}


/* setTCPBufferLength
**
** Purpose:
**      Initialize the length of the buffer.
**
** Parameter Dictionary:
**      sock  Socket descriptor.
**
** 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("DUL: 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("DUL: 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("DUL: cannot parse environment variable TCP_BUFFER_LENGTH=" << TCPBufferLength);
    } else
        DCMNET_TRACE("  environment variable TCP_BUFFER_LENGTH not set, using the system defaults");
}


/* DUL_DumpParams
**
** Purpose:
**      Returns information of various fields of the service parameters.
**
** Parameter Dictionary:
**      ret_str
**      params   Pointer to structure holding the service parameters.
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
OFString&
DUL_DumpParams(OFString& ret_str, DUL_ASSOCIATESERVICEPARAMETERS * params)
{
    OFOStringStream str;
    OFString temp_str;

    str << "APP CTX NAME: " << params->applicationContextName << OFendl;
    str << dump_uid(params->applicationContextName, "%14s") << OFendl;
    str << "AP TITLE:     " << params->callingAPTitle << OFendl
        << "AP TITLE:     " << params->calledAPTitle << OFendl
        << "AP TITLE:     " << params->respondingAPTitle << OFendl
        << "MAX PDU:      " << (int)params->maxPDU << OFendl
        << "Peer MAX PDU: " << (int)params->peerMaxPDU << OFendl
        << "PRES ADDR:    " << params->callingPresentationAddress << OFendl
        << "PRES ADDR:    " << params->calledPresentationAddress << OFendl
        << "REQ IMP UID:  " << params->callingImplementationClassUID << OFendl;
    str << dump_uid(params->callingImplementationClassUID, "%14s") << OFendl;
    str << "REQ VERSION:  " << params->callingImplementationVersionName << OFendl
        << "ACC IMP UID:  " << params->calledImplementationClassUID << OFendl;
    str << dump_uid(params->calledImplementationClassUID, "%14s") << OFendl;
    str << "ACC VERSION:  " << params->calledImplementationVersionName << OFendl
        << "Requested Presentation Ctx" << OFendl;
    str << dump_presentation_ctx(&params->requestedPresentationContext);
    str << "Accepted Presentation Ctx" << OFendl;
    str << dump_presentation_ctx(&params->acceptedPresentationContext);
    if (params->requestedExtNegList != NULL) {
        str << "Requested Extended Negotiation" << OFendl;
        str << dumpExtNegList(temp_str, *params->requestedExtNegList);
    }
    if (params->acceptedExtNegList != NULL) {
        str << "Accepted Extended Negotiation" << OFendl;
        str << dumpExtNegList(temp_str, *params->acceptedExtNegList);
    }
    str << OFStringStream_ends;

    OFSTRINGSTREAM_GETSTR(str, ret)
    ret_str = ret;
    OFSTRINGSTREAM_FREESTR(ret)

    return ret_str;
}

typedef struct {
    DUL_SC_ROLE role;
    const char *text;
}   SC_MAP;

static SC_MAP scMap[] = {
    {DUL_SC_ROLE_NONE, "None"},
    {DUL_SC_ROLE_DEFAULT, "Default"},
    {DUL_SC_ROLE_SCU, "SCU"},
    {DUL_SC_ROLE_SCP, "SCP"},
    {DUL_SC_ROLE_SCUSCP, "SCUSCP"},
};


/* dump_presentation_ctx
**
** Purpose:
**      Display the contents of the presentation context list
**
** Parameter Dictionary:
**      l  Head of the list of various presentation contexts.
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFString
dump_presentation_ctx(LST_HEAD ** l)
{
    DUL_PRESENTATIONCONTEXT
    * ctx;
    DUL_TRANSFERSYNTAX
        * transfer;
    int
        l_index;
    OFOStringStream
        str;

    if (*l == NULL)
        return "";

    ctx = (DUL_PRESENTATIONCONTEXT*)LST_Head(l);
    if (ctx == NULL)
        return "";

    (void) LST_Position(l, (LST_NODE*)ctx);

    while (ctx != NULL) {
        str << "  Context ID:            " << (int)ctx->presentationContextID << OFendl
            << "  Abstract Syntax:       " << ctx->abstractSyntax << OFendl;
        str << dump_uid(ctx->abstractSyntax, "%25s") << OFendl;
        str << "  Result field:          " << (int) ctx->result << OFendl;
        for (l_index = 0; l_index < (int) DIM_OF(scMap); l_index++) {
            if (ctx->proposedSCRole == scMap[l_index].role)
                str << "  Proposed SCU/SCP Role: " << scMap[l_index].text << OFendl;
        }
        for (l_index = 0; l_index < (int) DIM_OF(scMap); l_index++) {
            if (ctx->acceptedSCRole == scMap[l_index].role)
                str << "  Accepted SCU/SCP Role: " << scMap[l_index].text << OFendl;
        }
        str << "  Proposed Xfer Syntax(es)" << OFendl;
        if (ctx->proposedTransferSyntax != NULL) {
            transfer = (DUL_TRANSFERSYNTAX*)LST_Head(&ctx->proposedTransferSyntax);
            if (transfer != NULL)
                (void) LST_Position(&ctx->proposedTransferSyntax, (LST_NODE*)transfer);

            while (transfer != NULL) {
                str << "                         " << transfer->transferSyntax << OFendl;
                str << dump_uid(transfer->transferSyntax, "%25s") << OFendl;
                transfer = (DUL_TRANSFERSYNTAX*)LST_Next(&ctx->proposedTransferSyntax);
            }
        }
        str << "  Accepted Xfer Syntax:  " << ctx->acceptedTransferSyntax << OFendl;
        str << dump_uid(ctx->acceptedTransferSyntax, "%25s") << OFendl;
        ctx = (DUL_PRESENTATIONCONTEXT*)LST_Next(l);
    }

    str << OFStringStream_ends;
    OFSTRINGSTREAM_GETOFSTRING(str, ret)
    return ret;
}


/* dumpExtNegList
**
** Purpose:
**      Display the extended negotiation structure
**
** Parameter Dictionary:
**      ret
**      lst
**
** Return Values:
**      None
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

OFString& dumpExtNegList(OFString& ret, SOPClassExtendedNegotiationSubItemList& lst)
{
    OFOStringStream str;
    OFListIterator(SOPClassExtendedNegotiationSubItem*) i = lst.begin();
    while (i != lst.end()) {
        SOPClassExtendedNegotiationSubItem* extNeg = *i;
        const char* uidName = dcmFindNameOfUID(extNeg->sopClassUID.c_str(), "Unknown-UID");
        str << "  =" << uidName
            << " (" << extNeg->sopClassUID.c_str() << ")" << OFendl
            << "    [";
        for (int k=0; k<(int)extNeg->serviceClassAppInfoLength; k++) {
            str << "0x";
            str << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << (int)(extNeg->serviceClassAppInfo[k]);
            if (k < (int)(extNeg->serviceClassAppInfoLength-1)) str << ", ";
        }
        str << "]" << STD_NAMESPACE dec << OFendl;
        ++i;
    }

    str << OFStringStream_ends;
    OFSTRINGSTREAM_GETSTR(str, res)
    ret = res;
    OFSTRINGSTREAM_FREESTR(res);
    return ret;
}


/* dump_uid
**
** Purpose:
**      Display the UID structure
**
** Parameter Dictionary:
**      UID     The UID associated with the structure
**      indent  Useful for printing purposes.
**
** Return Values:
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFString
dump_uid(const char *UID, const char *indent)
{
    const char* uidName;
    char buf[4096];

    if ((UID==NULL)||(UID[0] == '\0'))
    {
        OFStandard::snprintf(buf, sizeof(buf), indent, " ");
        return OFString(buf) + "No UID";
    } else {
        uidName = dcmFindNameOfUID(UID, "Unknown UID");
        OFStandard::snprintf(buf, sizeof(buf), indent, " ");
        return OFString(buf) + uidName;
    }
}


/* checkNetwork
**
** Purpose:
**      Verify the validity of the network handle.
**
** Parameter Dictionary:
**      networkKey  Handle to the network to be validated.
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
checkNetwork(PRIVATE_NETWORKKEY ** networkKey)
{
    if (networkKey == NULL) return DUL_NULLKEY;
    if (*networkKey == NULL) return DUL_NULLKEY;
    if (strcmp((*networkKey)->keyType, KEY_NETWORK) != 0) return DUL_ILLEGALKEY;

    return EC_Normal;
}


/* checkAssociation
**
** Purpose:
**      Verify the validity of the Association handle
**
** Parameter Dictionary:
**      association  Handle to the association to be validated.
**
** Return Values:
**
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
checkAssociation(PRIVATE_ASSOCIATIONKEY ** association)
{
    if (association == NULL) return DUL_NULLKEY;
    if (*association == NULL)  return DUL_NULLKEY;
    if (strcmp((*association)->keyType, KEY_ASSOCIATION) != 0) return DUL_ILLEGALKEY;

    return EC_Normal;
}


/* clearRequestorsParams
**
** Purpose:
**      Reset all the fields of the service parameters.
**
** Parameter Dictionary:
**      params  Pointer to the service parameters to be reset.
**
** Return Values:
**      None
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static void
clearRequestorsParams(DUL_ASSOCIATESERVICEPARAMETERS * params)
{
    params->applicationContextName[0] = '\0';
    params->callingAPTitle[0] = '\0';
    params->calledAPTitle[0] = '\0';
    params->respondingAPTitle[0] = '\0';
    params->result = params->resultSource = params->diagnostic = 0;
    params->callingPresentationAddress[0] = '\0';
    params->calledPresentationAddress[0] = '\0';
    params->requestedPresentationContext = NULL;
    params->acceptedPresentationContext = NULL;
    params->maximumOperationsInvoked = 0;
    params->maximumOperationsPerformed = 0;
    params->callingImplementationClassUID[0] = '\0';
    params->callingImplementationVersionName[0] = '\0';
    params->requestedExtNegList = NULL;
    params->acceptedExtNegList = NULL;
}


/* clearPresentationContext
**
** Purpose:
**      Free the memory occupied by the given presentation context.
**
** Parameter Dictionary:
**      l  Head of list of the presentation contexts to be freed.
**
** Return Values:
**      None
**
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static void
clearPresentationContext(LST_HEAD ** l)
{
    DUL_PRESENTATIONCONTEXT
    * ctx;
    DUL_TRANSFERSYNTAX
        * transfer;

    if (*l == NULL)
        return;

    while ((ctx = (DUL_PRESENTATIONCONTEXT*)LST_Pop(l)) != NULL) {
        if (ctx->proposedTransferSyntax != NULL) {
            while ((transfer = (DUL_TRANSFERSYNTAX*)LST_Pop(&ctx->proposedTransferSyntax)) != NULL)
                free(transfer);
            LST_Destroy(&ctx->proposedTransferSyntax);
        }
        free(ctx);
    }
    LST_Destroy(l);
}

OFCondition DUL_setTransportLayer(DUL_NETWORKKEY *callerNetworkKey, DcmTransportLayer *newLayer, int takeoverOwnership)
{
  if (callerNetworkKey && newLayer)
  {
    PRIVATE_NETWORKKEY * key = (PRIVATE_NETWORKKEY *) callerNetworkKey;
    if ((key->networkSpecific.TCP.tLayerOwned) && (key->networkSpecific.TCP.tLayer)) delete key->networkSpecific.TCP.tLayer;
    key->networkSpecific.TCP.tLayer = newLayer;
    key->networkSpecific.TCP.tLayerOwned = takeoverOwnership;
    return EC_Normal;
  }
  return DUL_NULLKEY;
}

OFString& DUL_DumpConnectionParameters(OFString& str, DUL_ASSOCIATIONKEY *association)
{
  if (association)
  {
    PRIVATE_ASSOCIATIONKEY *assoc = (PRIVATE_ASSOCIATIONKEY *)association;
    if (assoc->connection)
        return assoc->connection->dumpConnectionParameters(str);
  }
  str.clear();
  return str;
}

void DUL_setParentProcessMode(DUL_ASSOCIATIONKEY *callerAssociation)
{
    PRIVATE_ASSOCIATIONKEY *association = (PRIVATE_ASSOCIATIONKEY *) callerAssociation;
    if (association->connection)
    {
      association->connection->setParentProcessMode();
    }
}

// Legacy functions!
void DUL_DumpParams(DUL_ASSOCIATESERVICEPARAMETERS * params)
{
    OFString str;
    COUT << DUL_DumpParams(str, params) << OFendl;
}

void DUL_DumpConnectionParameters(DUL_ASSOCIATIONKEY *association, STD_NAMESPACE ostream& outstream)
{
    OFString str;
    outstream << DUL_DumpConnectionParameters(str, association) << OFendl;
}

void dumpExtNegList(SOPClassExtendedNegotiationSubItemList& lst)
{
    OFString str;
    COUT << dumpExtNegList(str, lst) << OFendl;
}