File: comm3705.c

package info (click to toggle)
hercules 3.13-9
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,392 kB
  • sloc: ansic: 175,124; sh: 8,792; makefile: 760; perl: 149
file content (2398 lines) | stat: -rw-r--r-- 85,011 bytes parent folder | download | duplicates (5)
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
/* COMM3705.C   (c) Copyright Max H. Parke, 2007-2012                */
/*              Hercules 3705 communications controller              */
/*              running NCP                                          */


/***********************************************************************/
/*                                                                     */
/* comm3705.c - (C) Copyright 2007 by MHP <ikj1234i at yahoo dot com>  */
/*                                                                     */
/* Loosely based on commadpt.c by Ivan Warren                          */
/*                                                                     */
/* This module appears to the "host" as a 3705 communications          */
/* controller running NCP.  It does not attempt to provide an emulated */
/* execution environment for native 3705 code.                         */
/*                                                                     */
/* Experimental release 0.02 Oct. 15, 2007                             */
/*                                                                     */
/* A very minimalistic SNA engine is implemented.  All received SNA    */
/* requests are responded to with a positive response.  Also, there's  */
/* enough code to enable a single SNA session to logon in LU1 (TTY)    */
/* mode.                                                               */
/*                                                                     */
/* FID1 is the only SNA header type supported.                         */
/*                                                                     */
/* A large amount of required SNA functionality is not present in this */
/* release.  There are no "state machines", "layers", "services",      */
/* chaining*, pacing, brackets, etc.etc.etc.  There are                */
/* probably more bugs than working functions...    Enjoy ;-)           */
/*                                                                     */
/* A better implementation might be to separate the SNA functions out  */
/* into an independent process, with communications over a full-duplex */
/* TCP/IP socket... We might also get rid of all the magic constants...*/
/*                                                                     */
/* New in release 0.02 -                                               */
/* - VTAM switched (dial) support                                      */
/* - New remote NCP capability                                         */
/* - SNA 3270 (LU2) support (*with RU chaining)                        */
/* - fixes for some bugs in 0.01                                       */
/* New in release 0.03 -                                               */
/* - don't process TTY lines until CR received                         */
/* New in release 0.04 -                                               */
/* - make debug messages optional                                      */
/*                                                                     */
/*                      73 DE KA1RBI                                   */
/***********************************************************************/

#include "hstdinc.h"
#include "hercules.h"
#include "devtype.h"
#include "opcode.h"
#include "parser.h"
#include "comm3705.h"

#if defined(WIN32) && defined(OPTION_DYNAMIC_LOAD) && !defined(HDL_USE_LIBTOOL) && !defined(_MSVC_)
  SYSBLK *psysblk;
  #define sysblk (*psysblk)
#endif

#if !defined(min)
#define  min(a,b)              (((a) <= (b)) ? (a) : (b))
#endif

static void make_sna_requests2(COMMADPT*);
static void make_sna_requests3(COMMADPT*);
static void make_sna_requests4(COMMADPT*, int, BYTE);
static void make_sna_requests5(COMMADPT*);

static unsigned char R010201[3] = {0x01, 0x02, 0x01};
static unsigned char R010202[3] = {0x01, 0x02, 0x02};
static unsigned char R010203[3] = {0x01, 0x02, 0x03};
static unsigned char R010204[3] = {0x01, 0x02, 0x04};
static unsigned char R010205[3] = {0x01, 0x02, 0x05};
static unsigned char R01020A[3] = {0x01, 0x02, 0x0A};
static unsigned char R01020B[3] = {0x01, 0x02, 0x0B};
static unsigned char R01020F[3] = {0x01, 0x02, 0x0F};
static unsigned char R010211[3] = {0x01, 0x02, 0x11};
static unsigned char R010216[3] = {0x01, 0x02, 0x16};
static unsigned char R010217[3] = {0x01, 0x02, 0x17};
static unsigned char R010219[3] = {0x01, 0x02, 0x19};
static unsigned char R01021A[3] = {0x01, 0x02, 0x1A};
static unsigned char R01021B[3] = {0x01, 0x02, 0x1B};
static unsigned char R010280[3] = {0x01, 0x02, 0x80};
static unsigned char R010281[3] = {0x01, 0x02, 0x81};
static unsigned char R010284[3] = {0x01, 0x02, 0x84};

#define BUFPD 0x1C

static BYTE commadpt_immed_command[256]=
{ 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

/*---------------------------------------------------------------*/
/* PARSER TABLES                                                 */
/*---------------------------------------------------------------*/
static PARSER ptab[]={
    {"lport","%s"},
    {"lhost","%s"},
    {"rport","%s"},
    {"rhost","%s"},
    {"dial","%s"},
    {"rto","%s"},
    {"pto","%s"},
    {"eto","%s"},
    {"switched","%s"},
    {"lnctl","%s"},
    {"debug","%s"},
    {"emu3791","%s"},
    {"locsuba","%s"},
    {"rmtsuba","%s"},
    {"locncpnm","%s"},
    {"rmtncpnm","%s"},
    {"idblk","%s"},
    {"idnum","%s"},
    {"unitsz","%s"},
    {"ackspeed","%s"},
    {NULL,NULL}
};

enum {
    COMMADPT_KW_LPORT=1,
    COMMADPT_KW_LHOST,
    COMMADPT_KW_RPORT,
    COMMADPT_KW_RHOST,
    COMMADPT_KW_DIAL,
    COMMADPT_KW_READTO,
    COMMADPT_KW_POLLTO,
    COMMADPT_KW_ENABLETO,
    COMMADPT_KW_SWITCHED,
    COMMADPT_KW_LNCTL,
    COMMADPT_KW_DEBUG,
    COMMADPT_KW_EMU3791,
    COMMADPT_KW_LOCSUBA,
    COMMADPT_KW_RMTSUBA,
    COMMADPT_KW_LOCNCPNM,
    COMMADPT_KW_RMTNCPNM,
    COMMADPT_KW_IDBLK,
    COMMADPT_KW_IDNUM,
    COMMADPT_KW_UNITSZ,
    COMMADPT_KW_ACKSPEED
} comm3705_kw;

//////////////////////////////////////////////////////////////////////
// some code copied from console.c
static  HOST_INFO  cons_hostinfo;       /* Host info for this system */
/*-------------------------------------------------------------------*/
/* Telnet command definitions                                        */
/*-------------------------------------------------------------------*/
#define BINARY          0       /* Binary Transmission */
#define IS              0       /* Used by terminal-type negotiation */
#define SEND            1       /* Used by terminal-type negotiation */
#define ECHO_OPTION     1       /* Echo option */
#define SUPPRESS_GA     3       /* Suppress go-ahead option */
#define TIMING_MARK     6       /* Timing mark option */
#define TERMINAL_TYPE   24      /* Terminal type option */
#define NAWS            31      /* Negotiate About Window Size */
#define EOR             25      /* End of record option */
#define EOR_MARK        239     /* End of record marker */
#define SE              240     /* End of subnegotiation parameters */
#define NOP             241     /* No operation */
#define DATA_MARK       242     /* The data stream portion of a Synch.
                                   This should always be accompanied
                                   by a TCP Urgent notification */
#define BRK             243     /* Break character */
#define IP              244     /* Interrupt Process */
#define AO              245     /* Abort Output */
#define AYT             246     /* Are You There */
#define EC              247     /* Erase character */
#define EL              248     /* Erase Line */
#define GA              249     /* Go ahead */
#define SB              250     /* Subnegotiation of indicated option */
#define WILL            251     /* Indicates the desire to begin
                                   performing, or confirmation that
                                   you are now performing, the
                                   indicated option */
#define WONT            252     /* Indicates the refusal to perform,
                                   or continue performing, the
                                   indicated option */
#define DO              253     /* Indicates the request that the
                                   other party perform, or
                                   confirmation that you are expecting
                                   the other party to perform, the
                                   indicated option */
#define DONT            254     /* Indicates the demand that the
                                   other party stop performing,
                                   or confirmation that you are no
                                   longer expecting the other party
                                   to perform, the indicated option */
#define IAC             255     /* Interpret as Command */

/*-------------------------------------------------------------------*/
/* 3270 definitions                                                  */
/*-------------------------------------------------------------------*/

/* 3270 remote commands */
#define R3270_EAU       0x6F            /* Erase All Unprotected     */
#define R3270_EW        0xF5            /* Erase/Write               */
#define R3270_EWA       0x7E            /* Erase/Write Alternate     */
#define R3270_RB        0xF2            /* Read Buffer               */
#define R3270_RM        0xF6            /* Read Modified             */
#define R3270_RMA       0x6E            /* Read Modified All         */
#define R3270_WRT       0xF1            /* Write                     */
#define R3270_WSF       0xF3            /* Write Structured Field    */

/* 3270 orders */
#define O3270_SBA       0x11            /* Set Buffer Address        */
#define O3270_SF        0x1D            /* Start Field               */
#define O3270_SFE       0x29            /* Start Field Extended      */
#define O3270_SA        0x28            /* Set Attribute             */
#define O3270_IC        0x13            /* Insert Cursor             */
#define O3270_MF        0x2C            /* Modify Field              */
#define O3270_PT        0x05            /* Program Tab               */
#define O3270_RA        0x3C            /* Repeat to Address         */
#define O3270_EUA       0x12            /* Erase Unprotected to Addr */
#define O3270_GE        0x08            /* Graphic Escape            */

/* Inbound structured fields */
#define SF3270_AID      0x88            /* Aid value of inbound SF   */
#define SF3270_3270DS   0x80            /* SFID of 3270 datastream SF*/

/*-------------------------------------------------------------------*/
/* Internal macro definitions                                        */
/*-------------------------------------------------------------------*/

/* DEBUG_LVL: 0 = none
              1 = status
              2 = headers
              3 = buffers
*/
#define DEBUG_LVL        0

#if DEBUG_LVL == 0
  #define TNSDEBUG1      1 ? ((void)0) : logmsg
  #define TNSDEBUG2      1 ? ((void)0) : logmsg
  #define TNSDEBUG3      1 ? ((void)0) : logmsg
#endif
#if DEBUG_LVL == 1
  #define TNSDEBUG1      logmsg
  #define TNSDEBUG2      1 ? ((void)0) : logmsg
  #define TNSDEBUG3      1 ? ((void)0) : logmsg
#endif
#if DEBUG_LVL == 2
  #define TNSDEBUG1      logmsg
  #define TNSDEBUG2      logmsg
  #define TNSDEBUG3      1 ? ((void)0) : logmsg
#endif
#if DEBUG_LVL == 3
  #define TNSDEBUG1      logmsg
  #define TNSDEBUG2      logmsg
  #define TNSDEBUG3      logmsg
#endif

#define TNSERROR        logmsg

#define BUFLEN_3270     65536           /* 3270 Send/Receive buffer  */
#define BUFLEN_1052     150             /* 1052 Send/Receive buffer  */


#undef  FIX_QWS_BUG_FOR_MCS_CONSOLES

/*-------------------------------------------------------------------*/
/* SUBROUTINE TO TRACE THE CONTENTS OF AN ASCII MESSAGE PACKET       */
/*-------------------------------------------------------------------*/
#if DEBUG_LVL == 3
static void
packet_trace(BYTE *addr, int len)
{
int  i, offset;
BYTE c;
BYTE print_chars[17];

    for (offset=0; offset < len; )
    {
        memset(print_chars,0,sizeof(print_chars));
        logmsg("+%4.4X  ", offset);
        for (i=0; i < 16; i++)
        {
            c = *addr++;
            if (offset < len) {
                logmsg("%2.2X", c);
                print_chars[i] = '.';
                if (isprint(c)) print_chars[i] = c;
                c = guest_to_host(c);
                if (isprint(c)) print_chars[i] = c;
            }
            else {
                logmsg("  ");
            }
            offset++;
            if ((offset & 3) == 0) {
                logmsg(" ");
            }
        } /* end for(i) */
        logmsg(" %s\n", print_chars);
    } /* end for(offset) */

} /* end function packet_trace */
#else
 #define packet_trace( _addr, _len)
#endif


#if 1
struct sockaddr_in * get_inet_socket(char *host_serv)
{
char *host = NULL;
char *serv;
struct sockaddr_in *sin;

    if((serv = strchr(host_serv,':')))
    {
        *serv++ = '\0';
        if(*host_serv)
            host = host_serv;
    }
    else
        serv = host_serv;

    if(!(sin = malloc(sizeof(struct sockaddr_in))))
        return sin;

    sin->sin_family = AF_INET;

    if(host)
    {
    struct hostent *hostent;

        hostent = gethostbyname(host);

        if(!hostent)
        {
            logmsg(_("HHCGI001I Unable to determine IP address from %s\n"),
                host);
            free(sin);
            return NULL;
        }

        memcpy(&sin->sin_addr,*hostent->h_addr_list,sizeof(sin->sin_addr));
    }
    else
        sin->sin_addr.s_addr = INADDR_ANY;

    if(serv)
    {
        if(!isdigit(*serv))
        {
        struct servent *servent;

            servent = getservbyname(serv, "tcp");

            if(!servent)
            {
                logmsg(_("HHCGI002I Unable to determine port number from %s\n"),
                    host);
                free(sin);
                return NULL;
            }

            sin->sin_port = servent->s_port;
        }
        else
            sin->sin_port = htons(atoi(serv));

    }
    else
    {
        logmsg(_("HHCGI003E Invalid parameter: %s\n"),
            host_serv);
        free(sin);
        return NULL;
    }

    return sin;

}

#endif
/*-------------------------------------------------------------------*/
/* SUBROUTINE TO DOUBLE UP ANY IAC BYTES IN THE DATA STREAM          */
/* Returns the new length after inserting extra IAC bytes            */
/*-------------------------------------------------------------------*/
static int
double_up_iac (BYTE *buf, int len)
{
int     m, n, x, newlen;

    /* Count the number of IAC bytes in the data */
    for (x=0, n=0; n < len; n++)
        if (buf[n] == IAC) x++;

    /* Exit if nothing to do */
    if (x == 0) return len;

    /* Insert extra IAC bytes backwards from the end of the buffer */
    newlen = len + x;
    TNSDEBUG3("console: DBG002: %d IAC bytes added, newlen=%d\n",
            x, newlen);
    for (n=newlen, m=len; n > m; ) {
        buf[--n] = buf[--m];
        if (buf[n] == IAC) buf[--n] = IAC;
    }
    packet_trace (buf, newlen);
    return newlen;

} /* end function double_up_iac */


/*-------------------------------------------------------------------*/
/* SUBROUTINE TO TRANSLATE A NULL-TERMINATED STRING TO EBCDIC        */
/*-------------------------------------------------------------------*/
static BYTE *
translate_to_ebcdic (char *str)
{
int     i;                              /* Array subscript           */
BYTE    c;                              /* Character work area       */

    for (i = 0; str[i] != '\0'; i++)
    {
        c = str[i];
        str[i] = (isprint(c) ? host_to_guest(c) : SPACE);
    }

    return (BYTE *)str;
} /* end function translate_to_ebcdic */


/*-------------------------------------------------------------------*/
/* SUBROUTINE TO SEND A DATA PACKET TO THE CLIENT                    */
/*-------------------------------------------------------------------*/
static int
send_packet (int csock, BYTE *buf, int len, char *caption)
{
int     rc;                             /* Return code               */

    if (caption != NULL) {
        TNSDEBUG2("console: DBG003: Sending %s\n", caption);
        packet_trace (buf, len);
    }

    rc = send (csock, buf, len, 0);

    if (rc < 0) {
        TNSERROR("console: DBG021: send: %s\n", strerror(HSO_errno));
        return -1;
    } /* end if(rc) */

    return 0;

} /* end function send_packet */


/*-------------------------------------------------------------------*/
/* SUBROUTINE TO RECEIVE A DATA PACKET FROM THE CLIENT               */
/* This subroutine receives bytes from the client.  It stops when    */
/* the receive buffer is full, or when the last two bytes received   */
/* consist of the IAC character followed by a specified delimiter.   */
/* If zero bytes are received, this means the client has closed the  */
/* connection, and this is treated as an error.                      */
/* Input:                                                            */
/*      csock is the socket number                                   */
/*      buf points to area to receive data                           */
/*      reqlen is the number of bytes requested                      */
/*      delim is the delimiter character (0=no delimiter)            */
/* Output:                                                           */
/*      buf is updated with data received                            */
/*      The return value is the number of bytes received, or         */
/*      -1 if an error occurred.                                     */
/*-------------------------------------------------------------------*/
static int
recv_packet (int csock, BYTE *buf, int reqlen, BYTE delim)
{
int     rc=0;                           /* Return code               */
int     rcvlen=0;                       /* Length of data received   */

    while (rcvlen < reqlen) {

        rc = recv (csock, buf + rcvlen, reqlen - rcvlen, 0);

        if (rc < 0) {
            TNSERROR("console: DBG022: recv: %s\n", strerror(HSO_errno));
            return -1;
        }

        if (rc == 0) {
            TNSDEBUG1("console: DBG004: Connection closed by client\n");
            return -1;
        }

        rcvlen += rc;

        if (delim != '\0' && rcvlen >= 2
            && buf[rcvlen-2] == IAC && buf[rcvlen-1] == delim)
            break;
    }

    TNSDEBUG2("console: DBG005: Packet received length=%d\n", rcvlen);
    packet_trace (buf, rcvlen);

    return rcvlen;

} /* end function recv_packet */


/*-------------------------------------------------------------------*/
/* SUBROUTINE TO RECEIVE A PACKET AND COMPARE WITH EXPECTED VALUE    */
/*-------------------------------------------------------------------*/
static int
expect (int csock, BYTE *expected, int len, char *caption)
{
int     rc;                             /* Return code               */
BYTE    buf[512];                       /* Receive buffer            */
#if 1
/* TCP/IP for MVS returns the server sequence rather then
   the client sequence during bin negotiation    19/06/00 Jan Jaeger */
static BYTE do_bin[] = { IAC, DO, BINARY, IAC, WILL, BINARY };
static BYTE will_bin[] = { IAC, WILL, BINARY, IAC, DO, BINARY };
#endif

    UNREFERENCED(caption);

    rc = recv_packet (csock, buf, len, 0);
    if (rc < 0) return -1;

#if 1
        /* TCP/IP FOR MVS DOES NOT COMPLY TO RFC 1576 THIS IS A BYPASS */
        if(memcmp(buf, expected, len) != 0
          && !(len == sizeof(will_bin)
              && memcmp(expected, will_bin, len) == 0
              && memcmp(buf, do_bin, len) == 0) )
#else
    if (memcmp(buf, expected, len) != 0)
#endif
    {
        TNSDEBUG2("console: DBG006: Expected %s\n", caption);
        return -1;
    }
    TNSDEBUG2("console: DBG007: Received %s\n", caption);

    return 0;

} /* end function expect */


/*-------------------------------------------------------------------*/
/* SUBROUTINE TO NEGOTIATE TELNET PARAMETERS                         */
/* This subroutine negotiates the terminal type with the client      */
/* and uses the terminal type to determine whether the client        */
/* is to be supported as a 3270 display console or as a 1052/3215    */
/* printer-keyboard console.                                         */
/*                                                                   */
/* Valid display terminal types are "IBM-NNNN", "IBM-NNNN-M", and    */
/* "IBM-NNNN-M-E", where NNNN is 3270, 3277, 3278, 3279, 3178, 3179, */
/* or 3180, M indicates the screen size (2=25x80, 3=32x80, 4=43x80,  */
/* 5=27x132, X=determined by Read Partition Query command), and      */
/* -E is an optional suffix indicating that the terminal supports    */
/* extended attributes. Displays are negotiated into tn3270 mode.    */
/* An optional device number suffix (example: IBM-3270@01F) may      */
/* be specified to request allocation to a specific device number.   */
/* Valid 3270 printer type is "IBM-3287-1"                           */
/*                                                                   */
/* Terminal types whose first four characters are not "IBM-" are     */
/* handled as printer-keyboard consoles using telnet line mode.      */
/*                                                                   */
/* Input:                                                            */
/*      csock   Socket number for client connection                  */
/* Output:                                                           */
/*      class   D=3270 display console, K=printer-keyboard console   */
/*              P=3270 printer                                       */
/*      model   3270 model indicator (2,3,4,5,X)                     */
/*      extatr  3270 extended attributes (Y,N)                       */
/*      devn    Requested device number, or FFFF=any device number   */
/* Return value:                                                     */
/*      0=negotiation successful, -1=negotiation error               */
/*-------------------------------------------------------------------*/
static int
negotiate(int csock, BYTE *class, BYTE *model, BYTE *extatr, U16 *devn,char *group)
{
int    rc;                              /* Return code               */
char  *termtype;                        /* Pointer to terminal type  */
char  *s;                               /* String pointer            */
BYTE   c;                               /* Trailing character        */
U16    devnum;                          /* Requested device number   */
BYTE   buf[512];                        /* Telnet negotiation buffer */
static BYTE do_term[] = { IAC, DO, TERMINAL_TYPE };
static BYTE will_term[] = { IAC, WILL, TERMINAL_TYPE };
static BYTE req_type[] = { IAC, SB, TERMINAL_TYPE, SEND, IAC, SE };
static BYTE type_is[] = { IAC, SB, TERMINAL_TYPE, IS };
static BYTE do_eor[] = { IAC, DO, EOR, IAC, WILL, EOR };
static BYTE will_eor[] = { IAC, WILL, EOR, IAC, DO, EOR };
static BYTE do_bin[] = { IAC, DO, BINARY, IAC, WILL, BINARY };
static BYTE will_bin[] = { IAC, WILL, BINARY, IAC, DO, BINARY };
#if 0
static BYTE do_tmark[] = { IAC, DO, TIMING_MARK };
static BYTE will_tmark[] = { IAC, WILL, TIMING_MARK };
static BYTE wont_sga[] = { IAC, WONT, SUPPRESS_GA };
static BYTE dont_sga[] = { IAC, DONT, SUPPRESS_GA };
#endif
static BYTE wont_echo[] = { IAC, WONT, ECHO_OPTION };
static BYTE dont_echo[] = { IAC, DONT, ECHO_OPTION };
static BYTE will_naws[] = { IAC, WILL, NAWS };

    /* Perform terminal-type negotiation */
    rc = send_packet (csock, do_term, sizeof(do_term),
                        "IAC DO TERMINAL_TYPE");
    if (rc < 0) return -1;

    rc = expect (csock, will_term, sizeof(will_term),
                        "IAC WILL TERMINAL_TYPE");
    if (rc < 0) return -1;

    /* Request terminal type */
    rc = send_packet (csock, req_type, sizeof(req_type),
                        "IAC SB TERMINAL_TYPE SEND IAC SE");
    if (rc < 0) return -1;

    rc = recv_packet (csock, buf, sizeof(buf)-2, SE);
    if (rc < 0) return -1;

    /* Ignore Negotiate About Window Size */
    if (rc >= (int)sizeof(will_naws) &&
        memcmp (buf, will_naws, sizeof(will_naws)) == 0)
    {
        memmove(buf, &buf[sizeof(will_naws)], (rc - sizeof(will_naws)));
        rc -= sizeof(will_naws);
    }

    if (rc < (int)(sizeof(type_is) + 2)
        || memcmp(buf, type_is, sizeof(type_is)) != 0
        || buf[rc-2] != IAC || buf[rc-1] != SE) {
        TNSDEBUG2("console: DBG008: Expected IAC SB TERMINAL_TYPE IS\n");
        return -1;
    }
    buf[rc-2] = '\0';
    termtype = (char *)(buf + sizeof(type_is));
    TNSDEBUG2("console: DBG009: Received IAC SB TERMINAL_TYPE IS %s IAC SE\n",
            termtype);

    /* Check terminal type string for device name suffix */
    s = strchr (termtype, '@');
    if(s!=NULL)
    {
        if(strlen(s)<16)
        {
            strlcpy(group,&s[1],16);
        }
    }
    else
    {
        group[0]=0;
    }

    if (s != NULL && sscanf (s, "@%hx%c", &devnum,&c) == 1)
    {
        *devn = devnum;
        group[0]=0;
    }
    else
    {
        *devn = 0xFFFF;
    }

    /* Test for non-display terminal type */
    if (memcmp(termtype, "IBM-", 4) != 0)
    {
#if 0
        /* Perform line mode negotiation */
        rc = send_packet (csock, do_tmark, sizeof(do_tmark),
                            "IAC DO TIMING_MARK");
        if (rc < 0) return -1;

        rc = expect (csock, will_tmark, sizeof(will_tmark),
                            "IAC WILL TIMING_MARK");
        if (rc < 0) return 0;

        rc = send_packet (csock, wont_sga, sizeof(wont_sga),
                            "IAC WONT SUPPRESS_GA");
        if (rc < 0) return -1;

        rc = expect (csock, dont_sga, sizeof(dont_sga),
                            "IAC DONT SUPPRESS_GA");
        if (rc < 0) return -1;
#endif

        if (memcmp(termtype, "ANSI", 4) == 0)
        {
            rc = send_packet (csock, wont_echo, sizeof(wont_echo),
                                "IAC WONT ECHO");
            if (rc < 0) return -1;

            rc = expect (csock, dont_echo, sizeof(dont_echo),
                                "IAC DONT ECHO");
            if (rc < 0) return -1;
        }

        /* Return printer-keyboard terminal class */
        *class = 'K';
        *model = '-';
        *extatr = '-';
        return 0;
    }

    /* Determine display terminal model */
    if (memcmp(termtype+4,"DYNAMIC",7) == 0) {
        *model = 'X';
        *extatr = 'Y';
    } else {
        if (!(memcmp(termtype+4, "3277", 4) == 0
              || memcmp(termtype+4, "3270", 4) == 0
              || memcmp(termtype+4, "3178", 4) == 0
              || memcmp(termtype+4, "3278", 4) == 0
              || memcmp(termtype+4, "3179", 4) == 0
              || memcmp(termtype+4, "3180", 4) == 0
              || memcmp(termtype+4, "3287", 4) == 0
              || memcmp(termtype+4, "3279", 4) == 0))
            return -1;

        *model = '2';
        *extatr = 'N';

        if (termtype[8]=='-') {
            if (termtype[9] < '1' || termtype[9] > '5')
                return -1;
            *model = termtype[9];
            if (memcmp(termtype+4, "328",3) == 0) *model = '2';
            if (memcmp(termtype+10, "-E", 2) == 0)
                *extatr = 'Y';
        }
    }

    /* Perform end-of-record negotiation */
    rc = send_packet (csock, do_eor, sizeof(do_eor),
                        "IAC DO EOR IAC WILL EOR");
    if (rc < 0) return -1;

    rc = expect (csock, will_eor, sizeof(will_eor),
                        "IAC WILL EOR IAC DO EOR");
    if (rc < 0) return -1;

    /* Perform binary negotiation */
    rc = send_packet (csock, do_bin, sizeof(do_bin),
                        "IAC DO BINARY IAC WILL BINARY");
    if (rc < 0) return -1;

    rc = expect (csock, will_bin, sizeof(will_bin),
                        "IAC WILL BINARY IAC DO BINARY");
    if (rc < 0) return -1;

    /* Return display terminal class */
    if (memcmp(termtype+4,"3287",4)==0) *class='P';
    else *class = 'D';
    return 0;

} /* end function negotiate */

/*-------------------------------------------------------------------*/
/* NEW CLIENT CONNECTION                                             */
/*-------------------------------------------------------------------*/
static int
connect_client (int *csockp)
/* returns 1 if 3270, else 0 */
{
int                     rc;             /* Return code               */
size_t                  len;            /* Data length               */
int                     csock;          /* Socket for conversation   */
struct sockaddr_in      client;         /* Client address structure  */
socklen_t               namelen;        /* Length of client structure*/
char                   *clientip;       /* Addr of client ip address */
U16                     devnum;         /* Requested device number   */
BYTE                    class;          /* D=3270, P=3287, K=3215/1052 */
BYTE                    model;          /* 3270 model (2,3,4,5,X)    */
BYTE                    extended;       /* Extended attributes (Y,N) */
char                    buf[256];       /* Message buffer            */
char                    conmsg[256];    /* Connection message        */
char                    devmsg[25];     /* Device message            */
char                    hostmsg[256];   /* Host ID message           */
char                    num_procs[16];  /* #of processors string     */
char                    group[16];      /* Console group             */

    /* Load the socket address from the thread parameter */
    csock = *csockp;

    /* Obtain the client's IP address */
    namelen = sizeof(client);
    rc = getpeername (csock, (struct sockaddr *)&client, &namelen);

    /* Log the client's IP address and hostname */
    clientip = strdup(inet_ntoa(client.sin_addr));

#if 0
    // The following isn't really needed and hangs under unusual
    // network configuration settings and thus has been removed.
    {
        struct hostent*  pHE;           /* Addr of hostent structure */
        char*            clientname;    /* Addr of client hostname   */

        pHE = gethostbyaddr ((unsigned char*)(&client.sin_addr),
                            sizeof(client.sin_addr), AF_INET);

        if (pHE != NULL && pHE->h_name != NULL
        && pHE->h_name[0] != '\0') {
            clientname = (char*) pHE->h_name;
        } else {
            clientname = "host name unknown";
        }

        TNSDEBUG1("console: DBG018: Received connection from %s (%s)\n",
                clientip, clientname);
    }
#else
    TNSDEBUG1("console: DBG018: Received connection from %s\n",
            clientip );
#endif

    /* Negotiate telnet parameters */
    rc = negotiate (csock, &class, &model, &extended, &devnum, group);
    if (rc != 0)
    {
        close_socket (csock);
        if (clientip) free(clientip);
        return 0;
    }

    /* Build connection message for client */

    if ( cons_hostinfo.num_procs > 1 )
        snprintf( num_procs, sizeof(num_procs), "MP=%d", cons_hostinfo.num_procs );
    else
        strlcpy( num_procs, "UP", sizeof(num_procs) );

    snprintf
    (
        hostmsg, sizeof(hostmsg),

        "running on %s (%s-%s.%s %s %s)"

        ,cons_hostinfo.nodename
        ,cons_hostinfo.sysname
        ,cons_hostinfo.release
        ,cons_hostinfo.version
        ,cons_hostinfo.machine
        ,num_procs
    );
    snprintf (conmsg, sizeof(conmsg),
                "Hercules version %s built on %s %s",
                VERSION, __DATE__, __TIME__);

    {
        snprintf (devmsg, sizeof(devmsg), "Connected to device %4.4X",
                  0);
    }

    logmsg (_("HHCTE009I Client %s connected to %4.4X device %4.4X\n"),
            clientip, 0x3270, 0);

    /* Send connection message to client */
    if (class != 'K')
    {
        len = snprintf (buf, sizeof(buf),
                    "\xF5\x40\x11\x40\x40\x1D\x60%s"
                    "\x11\xC1\x50\x1D\x60%s"
                    "\x11\xC2\x60\x1D\x60%s",
                    translate_to_ebcdic(conmsg),
                    translate_to_ebcdic(hostmsg),
                    translate_to_ebcdic(devmsg));

        if (len < sizeof(buf))
        {
            buf[len++] = IAC;
        }
        else
        {
            ASSERT(FALSE);
        }

        if (len < sizeof(buf))
        {
            buf[len++] = EOR_MARK;
        }
        else
        {
            ASSERT(FALSE);
        }
    }
    else
    {
        len = snprintf (buf, sizeof(buf), "%s\r\n%s\r\n%s\r\n",
                        conmsg, hostmsg, devmsg);
    }

    if (class != 'P')  /* do not write connection resp on 3287 */
    {
        rc = send_packet (csock, (BYTE *)buf, len, "CONNECTION RESPONSE");
    }
    return (class == 'D') ? 1 : 0;   /* return 1 if 3270 */
} /* end function connect_client */


static void logdump(char *txt,DEVBLK *dev,BYTE *bfr,size_t sz)
{
    size_t i;
    if(!dev->ccwtrace)
    {
        return;
    }
    logmsg(_("HHCCA300D %4.4X:%s\n"),
            dev->devnum,
            txt);
    logmsg(_("HHCCA300D %4.4X:%s : Dump of %d (%x) byte(s)\n"),dev->devnum,txt,sz,sz);
    for(i=0;i<sz;i++)
    {
        if(i%16==0)
        {
            if(i!=0)
            {
                logmsg("\n");
            }
            logmsg(_("HHCCA300D %4.4X:%s : %4.4X:"),dev->devnum,txt,i);
        }
        if(i%4==0)
        {
            logmsg(" ");
        }
        logmsg("%2.2X",bfr[i]);
    }
    logmsg("\nHHCCA300D ");
    for(i=0;i<sz;i++)
    {
        if(i%16==0)
        {
            if(i!=0)
            {
                logmsg("\nHHCCA300D ");
            }
        }
        logmsg (_("%c"),(bfr[i] & 0x7f) < 0x20 ? '.' : (bfr[i] & 0x7f));
    }
    logmsg("\n");
}

static void put_bufpool(void ** anchor, BYTE * ele) {
       void ** elep = anchor;
       for (;;) {
               if (!*elep) break;
               elep = *elep;
       }
       *elep = ele;
       *(void**)ele = 0;
}

static BYTE * get_bufpool(void ** anchor) {
       void ** elep = *anchor;
       if (elep) {
                *anchor = *elep;
       } else {
                *anchor = 0;
       }
       return (BYTE*)elep;
}

static void init_bufpool(COMMADPT *ca) {
        BYTE * areap;
        int i1;
        int numbufs = 64;
        int bufsize = ca->unitsz+16+4;
        ca->poolarea = (BYTE*)calloc (numbufs, bufsize);
        if (!ca->poolarea) {
                return;
        }
        areap = ca->poolarea;
        for (i1 = 0; i1 < numbufs; i1++) {
                put_bufpool(&ca->freeq, areap);
                areap += (bufsize);
        }
}

static void free_bufpool(COMMADPT *ca) {
        ca->sendq = 0;
        ca->freeq = 0;
        if (ca->poolarea) {
            free(ca->poolarea);
            ca->poolarea = 0;
        }
}

/*-------------------------------------------------------------------*/
/* Free all private structures and buffers                           */
/*-------------------------------------------------------------------*/
static void commadpt_clean_device(DEVBLK *dev)
{
    if(dev->commadpt!=NULL)
    {
        free(dev->commadpt);
        dev->commadpt=NULL;
        if(dev->ccwtrace)
        {
                logmsg(_("HHCCA300D %4.4X:clean : Control block freed\n"),
                        dev->devnum);
        }
    }
    else
    {
        if(dev->ccwtrace)
        {
                logmsg(_("HHCCA300D %4.4X:clean : Control block not freed : not allocated\n"),dev->devnum);
        }
    }
    return;
}

/*-------------------------------------------------------------------*/
/* Allocate initial private structures                               */
/*-------------------------------------------------------------------*/
static int commadpt_alloc_device(DEVBLK *dev)
{
    dev->commadpt=malloc(sizeof(COMMADPT));
    if(dev->commadpt==NULL)
    {
        logmsg(_("HHCCA020E %4.4X:Memory allocation failure for main control block\n"),
                dev->devnum);
        return -1;
    }
    memset(dev->commadpt,0,sizeof(COMMADPT));
    dev->commadpt->dev=dev;
    return 0;
}
/*-------------------------------------------------------------------*/
/* Parsing utilities                                                 */
/*-------------------------------------------------------------------*/
/*-------------------------------------------------------------------*/
/* commadpt_getport : returns a port number or -1                    */
/*-------------------------------------------------------------------*/
static int commadpt_getport(char *txt)
{
    int pno;
    struct servent *se;
    pno=atoi(txt);
    if(pno==0)
    {
        se=getservbyname(txt,"tcp");
        if(se==NULL)
        {
            return -1;
        }
        pno=se->s_port;
    }
    return(pno);
}
/*-------------------------------------------------------------------*/
/* commadpt_getaddr : set an in_addr_t if ok, else return -1         */
/*-------------------------------------------------------------------*/
static int commadpt_getaddr(in_addr_t *ia,char *txt)
{
    struct hostent *he;
    he=gethostbyname(txt);
    if(he==NULL)
    {
        return(-1);
    }
    memcpy(ia,he->h_addr_list[0],4);
    return(0);
}

static void connect_message(int sfd, int na, int flag) {
    int rc;
    struct sockaddr_in client;
    socklen_t namelen;
    char *ipaddr;
    char msgtext[256];
    if (!sfd)
	    return;
    namelen = sizeof(client);
    rc = getpeername (sfd, (struct sockaddr *)&client, &namelen);
    ipaddr = inet_ntoa(client.sin_addr);
    if (flag == 0)
        sprintf(msgtext, "%s:%d VTAM CONNECTION ACCEPTED - NETWORK NODE= %4.4X", ipaddr, (int)ntohs(client.sin_port), na);
    else
        sprintf(msgtext, "%s:%d VTAM CONNECTION TERMINATED", ipaddr, (int)ntohs(client.sin_port));
    logmsg( _("%s\n"), msgtext);
    write(sfd, msgtext, strlen(msgtext));
    write(sfd, "\r\n", 2);
}

static void commadpt_read_tty(COMMADPT *ca, BYTE * bfr, int len)
// everything has been tortured to now do 3270 also
{
    BYTE        bfr3[3];
    BYTE        c;
    int i1;
    int eor=0;
           logdump("RECV",ca->dev, bfr,len);
    /* If there is a complete data record already in the buffer
       then discard it before reading more data
       For TTY, allow data to accumulate until CR is received */
	   if (ca->is_3270) {
               if (ca->inpbufl) {
                   ca->rlen3270 = 0;
                   ca->inpbufl = 0;
               }
           }
	   for (i1 = 0; i1 < len; i1++) {
		c = (unsigned char) bfr[i1];
		if (ca->telnet_opt) {
			ca->telnet_opt = 0;
		          if(ca->dev->ccwtrace)
			    logmsg(_("HHCCA300D %4.4X: Received TELNET CMD 0x%02x 0x%02x\n"),
			            ca->dev->devnum,
				    ca->telnet_cmd, c);
			bfr3[0] = 0xff;  /* IAC */
			/* set won't/don't for all received commands */
			bfr3[1] = (ca->telnet_cmd == 0xfd) ? 0xfc : 0xfe;
			bfr3[2] = c;
                          if (ca->sfd > 0) {
                              write_socket(ca->sfd,bfr3,3);
                          }
		          if(ca->dev->ccwtrace)
			    logmsg(_("HHCCA300D %4.4X: Sending TELNET CMD 0x%02x 0x%02x\n"),
			            ca->dev->devnum,
				    bfr3[1], bfr3[2]);
			continue;
		}
		if (ca->telnet_iac) {
			ca->telnet_iac = 0;
		          if(ca->dev->ccwtrace)
			    logmsg(_("HHCCA300D %4.4X: Received TELNET IAC 0x%02x\n"),
			            ca->dev->devnum,
				    c);
			switch (c) {
			case 0xFB:  /* TELNET WILL option cmd */
			case 0xFD:  /* TELNET DO option cmd */
				ca->telnet_opt = 1;
				ca->telnet_cmd = c;
				break;
			case 0xF4:  /* TELNET interrupt */
				if (!ca->telnet_int) {
					ca->telnet_int = 1;
				}
				break;
			case EOR_MARK:
                                eor = 1;
				break;
			case 0xFF:  /* IAC IAC */
		                ca->inpbuf[ca->rlen3270++] = 0xFF;
				break;
			}
			continue;
		}
		if (c == 0xFF) {  /* TELNET IAC */
			ca->telnet_iac = 1;
			continue;
		} else {
			ca->telnet_iac = 0;
		}
		if (!ca->is_3270) {
		  if (c == 0x0D) // CR in TTY mode ?
			  ca->eol_flag = 1;
		  c = host_to_guest(c);   // translate ASCII to EBCDIC for tty
		}
		ca->inpbuf[ca->rlen3270++] = c;
	    }
         /* received data (rlen3270 > 0) is sufficient for 3270,
            but for TTY, eol_flag must also be set */
	 if ((ca->eol_flag || ca->is_3270) && ca->rlen3270) {
		ca->eol_flag = 0;
		if (ca->is_3270) {
                   if (eor) {
		       ca->inpbufl = ca->rlen3270;
                       ca->rlen3270 = 0; /* for next msg */
                   }
		} else {
                   ca->inpbufl = ca->rlen3270;
                   ca->rlen3270 = 0; /* for next msg */
		}
                   if(ca->dev->ccwtrace)
                       logmsg(_("%4.4X: posted %d input bytes\n"),ca->dev->devnum,ca->inpbufl);
	 }
}

static void *telnet_thread(void *vca) {
    COMMADPT *ca;
    int devnum;                 /* device number copy for convenience*/
    int        sockopt;         /* Used for setsocketoption          */
    int ca_shutdown=0;            /* Thread shutdown internal flag     */
    int rc;                     /* return code from various rtns     */
    struct sockaddr_in sin;     /* bind socket address structure     */
    BYTE bfr[256];
        
    ca=(COMMADPT*)vca;
    /* get a work copy of devnum (for messages) */
    ca->sfd = 0;
    devnum=ca->devnum;

        ca->lfd=socket(AF_INET,SOCK_STREAM,0);
        if(!socket_is_socket(ca->lfd))
        {
            logmsg(_("HHCCA003E %4.4X:Cannot obtain socket for incoming calls : %s\n"),devnum,strerror(HSO_errno));
            ca->have_cthread=0;
            release_lock(&ca->lock);
            return NULL;
        }

        /* Reuse the address regardless of any */
        /* spurious connection on that port    */
        sockopt=1;
        setsockopt(ca->lfd,SOL_SOCKET,SO_REUSEADDR,(GETSET_SOCKOPT_T*)&sockopt,sizeof(sockopt));

        /* Bind the socket */
        sin.sin_family=AF_INET;
        sin.sin_addr.s_addr=ca->lhost;
        sin.sin_port=htons(ca->lport);
        while(1)
        {
            rc=bind(ca->lfd,(struct sockaddr *)&sin,sizeof(sin));
            if(rc<0)
            {
                    logmsg(_("HHCCA018E %4.4X:Bind failed : %s\n"),devnum,strerror(HSO_errno));
                    ca_shutdown=1;
                    break;
            }
            else
            {
                break;
            }
        }
        /* Start the listen */
        if(!ca_shutdown)
        {
            listen(ca->lfd,10);
            logmsg(_("HHCCA005I %4.4X:Listening on port %d for incoming TCP connections\n"),
                    devnum,
                    ca->lport);
        }
        for (;;) {
            ca->sfd = 0;
            ca->sfd=accept(ca->lfd,NULL,0);
            if (ca->sfd < 1) continue;
            if  (connect_client(&ca->sfd)) {
                ca->is_3270 = 1;
            } else {
                ca->is_3270 = 0;
            }
	    socket_set_blocking_mode(ca->sfd,0);  // set to non-blocking mode
            if (ca->emu3791 == 0) {make_sna_requests4(ca, 0, (ca->is_3270) ? 0x02 : 0x01);}   // send REQCONT
	    ca->hangup = 0;
	    for (;;) {
		usleep(50000);
		if (ca->hangup)
                    break;
        /* read_socket has changed from 3.04 to 3.06 - we need old way */
#ifdef _MSVC_
          rc=recv(ca->sfd,bfr,ca->unitsz-BUFPD,0);
#else
          rc=read(ca->sfd,bfr,ca->unitsz-BUFPD);
#endif
		if (rc < 0) {
                    if(0
#ifndef WIN32
                                || EAGAIN == errno
#endif
                                || HSO_EWOULDBLOCK == HSO_errno
                    ) {
			    continue;
                    }
		    break;
//                    make_sna_requests4(ca, 1);   // send REQDISCONT
                    if (ca->emu3791 == 0) {make_sna_requests5(ca);}
                }
		if (rc == 0) {
//                    make_sna_requests4(ca, 1);   // send REQDISCONT
                    if (ca->emu3791 == 0) {make_sna_requests5(ca);}
                    break;
		}
                commadpt_read_tty(ca,bfr,rc);
            }
	    close_socket(ca->sfd);
	    ca->sfd = 0;
        }
}

/*-------------------------------------------------------------------*/
/* Communication Thread main loop                                    */
/*-------------------------------------------------------------------*/
static void *commadpt_thread(void *vca)
{
    COMMADPT    *ca;            /* Work CA Control Block Pointer     */
    int devnum;                 /* device number copy for convenience*/
    int delay;                  /* unacknowledged attention delay    */
    int rc;                     /* return code from various rtns     */
    int ca_shutdown;            /* Thread shutdown internal flag     */
    int init_signaled;          /* Thread initialisation signaled    */

    /*---------------------END OF DECLARES---------------------------*/

    /* fetch the commadpt structure */
    ca=(COMMADPT *)vca;

    /* Obtain the CA lock */
    obtain_lock(&ca->lock);

    /* get a work copy of devnum (for messages) */
    devnum=ca->devnum;

    /* reset shutdown flag */
    ca_shutdown=0;

    init_signaled=0;

    logmsg(_("HHCCA002I %4.4X:3705 Communication thread "TIDPAT" started\n"),devnum,thread_id());

    for (;;) {
        release_lock(&ca->lock);
        if(ca->ackspeed == 0) delay = 50000 + (ca->unack_attn_count * 100000);         /* Max's reliable algorithm      */
        else delay = (ca->unack_attn_count * ca->unack_attn_count + 1) * ca->ackspeed; /* much faster but TCAM hates it */
        usleep(min(1000000,delay));                                                    /* go to sleep, max. 1 second    */
        obtain_lock(&ca->lock);
                make_sna_requests2(ca);
                make_sna_requests3(ca);
                if (ca->sendq
// attempt to fix hot i/o bug
                     && ca->unack_attn_count < 10
                ) {
                    ca->unack_attn_count++;
                    rc = device_attention(ca->dev, CSW_ATTN);
                    if(ca->dev->ccwtrace)
                        logmsg(_("%4.4X: Raised attention rc = %d\n"), ca->dev->devnum, rc);
                }
    }

    logmsg(_("HHCCA009I %4.4X:3705 utility thread terminated\n"),ca->devnum);
    release_lock(&ca->lock);
    return NULL;
}
/*-------------------------------------------------------------------*/
/* Halt currently executing I/O command                              */
/*-------------------------------------------------------------------*/
static void    commadpt_halt(DEVBLK *dev)
{
    if(!dev->busy)
    {
        return;
    }
}

/* The following 3 MSG functions ensure only 1 (one)  */
/* hardcoded instance exist for the same numbered msg */
/* that is issued on multiple situations              */
static void msg013e(DEVBLK *dev,char *kw,char *kv)
{
        logmsg(_("HHCCA013E %4.4X:Incorrect %s specification %s\n"),dev->devnum,kw,kv);
}
/*-------------------------------------------------------------------*/
/* Device Initialisation                                             */
/*-------------------------------------------------------------------*/
static int commadpt_init_handler (DEVBLK *dev, int argc, char *argv[])
{
    char thread_name[32];
    char thread_name2[32];
    int i;
    int rc;
    int pc; /* Parse code */
    int errcnt;
    struct in_addr in_temp;
    union {
        int num;
        char text[80];
    } res;
        dev->devtype=0x3705;
        if(dev->ccwtrace)
        {
                logmsg(_("HHCCA300D %4.4X:Initialisation starting\n"),dev->devnum);
        }

        if(dev->commadpt!=NULL)
        {
            commadpt_clean_device(dev);
        }
        rc=commadpt_alloc_device(dev);
        if(rc<0)
        {
                logmsg(_("HHCCA010I %4.4X:initialisation not performed\n"),
                        dev->devnum);
            return(-1);
        }
        if(dev->ccwtrace)
        {
                logmsg(_("HHCCA300D %4.4X:Initialisation : Control block allocated\n"),dev->devnum);
        }
        errcnt=0;
        /*
         * Initialise ports & hosts
        */
        dev->commadpt->sfd=-1;
        dev->commadpt->lport=0;
        dev->commadpt->debug_sna=0;
        dev->commadpt->emu3791=0;
        dev->commadpt->locsuba = 0x3800;              /* local  subarea = 7 (maxsuba=31)        */
        dev->commadpt->rmtsuba = 0x4000;              /* remote subarea = 8 (maxsuba=31)        */
        strcpy(dev->commadpt->locncpnm,"MHP3705 ");   /* local  NCP name                        */
        strcpy(dev->commadpt->rmtncpnm,"MHPRMT1 ");   /* remote NCP name                        */
        translate_to_ebcdic(dev->commadpt->locncpnm); /* convert to EBCDIC                      */
        translate_to_ebcdic(dev->commadpt->rmtncpnm); /* convert to EBCDIC                      */
        dev->commadpt->idblk = 0x17;                  /* IDBLK of switched PU (default=0x017)   */
        dev->commadpt->idnum = 0x17;                  /* IDNUM of switched PU (default=0x00017) */
        dev->commadpt->unitsz = 256;                  /* I/O blocksize (must equal RRT KEYLN)   */
                                                      /* unitsz=256 is invalid for TCAM and     */
                                                      /* instable for VTAM. Default retained    */
                                                      /* for compatibility with previous        */
                                                      /* versions only.                         */
        dev->commadpt->ackspeed = 0;                  /* choose Max's original attn algorithm   */
        for(i=0;i<argc;i++)
        {
            pc=parser(ptab,argv[i],&res);
            if(pc<0)
            {
                logmsg(_("HHCCA011E %4.4X:Error parsing %s\n"),dev->devnum,argv[i]);
                errcnt++;
                continue;
            }
            if(pc==0)
            {
                logmsg(_("HHCCA012E %4.4X:Unrecognized parameter %s\n"),dev->devnum,argv[i]);
                errcnt++;
                continue;
            }
            switch(pc)
            {
                case COMMADPT_KW_DEBUG:
		    if (res.text[0] == 'y' || res.text[0] == 'Y')
			dev->commadpt->debug_sna = 1;
		    else
			dev->commadpt->debug_sna = 0;
                    break;
                case COMMADPT_KW_LPORT:
                    rc=commadpt_getport(res.text);
                    if(rc<0)
                    {
                        errcnt++;
                        msg013e(dev,"LPORT",res.text);
                        break;
                    }
                    dev->commadpt->lport=rc;
                    break;
                case COMMADPT_KW_LHOST:
                    if(strcmp(res.text,"*")==0)
                    {
                        dev->commadpt->lhost=INADDR_ANY;
                        break;
                    }
                    rc=commadpt_getaddr(&dev->commadpt->lhost,res.text);
                    if(rc!=0)
                    {
                        msg013e(dev,"LHOST",res.text);
                        errcnt++;
                    }
                    break;
                case COMMADPT_KW_EMU3791:
                    if(strcasecmp(res.text,"yes")==0 || strcmp(res.text,"1"))
                        dev->commadpt->emu3791=1;
                    break;
                case COMMADPT_KW_LOCSUBA:
                        dev->commadpt->locsuba = (atoi(res.text)<<11); /* (maxsuba=31) */
                    break;
                case COMMADPT_KW_RMTSUBA:
                        dev->commadpt->rmtsuba = (atoi(res.text)<<11); /* (maxsuba=31) */
                    break;
                case COMMADPT_KW_LOCNCPNM:
                        strcpy(dev->commadpt->locncpnm,"        ");
                        strcpy(dev->commadpt->locncpnm,res.text);
                        memcpy(&dev->commadpt->locncpnm[strlen(res.text)]," ",1);
                        translate_to_ebcdic(dev->commadpt->locncpnm);
                    break;
                case COMMADPT_KW_RMTNCPNM:
                        strcpy(dev->commadpt->rmtncpnm,"        ");
                        strcpy(dev->commadpt->rmtncpnm,res.text);
                        memcpy(&dev->commadpt->rmtncpnm[strlen(res.text)]," ",1);
                        translate_to_ebcdic(dev->commadpt->rmtncpnm);
                    break;
                case COMMADPT_KW_IDBLK:
                        sscanf(res.text,"%3x",&dev->commadpt->idblk);
                    break;
                case COMMADPT_KW_IDNUM:
                        sscanf(res.text,"%5x",&dev->commadpt->idnum);
                    break;
                case COMMADPT_KW_UNITSZ:
                        dev->commadpt->unitsz = atoi(res.text);
                    break;
                case COMMADPT_KW_ACKSPEED:
                        dev->commadpt->ackspeed = atoi(res.text);
                    break;
                default:
                    break;
            }
        }
        if(errcnt>0)
        {
            logmsg(_("HHCCA021I %4.4X:Initialisation failed due to previous errors\n"),dev->devnum);
            return -1;
        }
        in_temp.s_addr=dev->commadpt->lhost;
        dev->bufsize=dev->commadpt->unitsz;
        dev->numsense=2;
        memset(dev->sense,0,sizeof(dev->sense));

        init_bufpool(dev->commadpt);

        dev->commadpt->devnum=dev->devnum;

        /* Initialize the CA lock */
        initialize_lock(&dev->commadpt->lock);

        /* Initialise thread->I/O & halt initiation EVB */
        initialize_condition(&dev->commadpt->ipc);
        initialize_condition(&dev->commadpt->ipc_halt);

        /* Allocate I/O -> Thread signaling pipe */
        create_pipe(dev->commadpt->pipe);

        /* Point to the halt routine for HDV/HIO/HSCH handling */
        dev->halt_device=commadpt_halt;

        /* Obtain the CA lock */
        obtain_lock(&dev->commadpt->lock);

        /* Start the telnet worker thread */

    /* Set thread-name for debugging purposes */
        snprintf(thread_name2,sizeof(thread_name2),
                 "commadpt %4.4X thread2",dev->devnum);
        thread_name2[sizeof(thread_name2)-1]=0;

        if(create_thread(&dev->commadpt->tthread,&sysblk.detattr,telnet_thread,dev->commadpt,thread_name2))
        {
            logmsg(D_("HHCCA022E create_thread: %s\n"),strerror(errno));
            release_lock(&dev->commadpt->lock);
            return -1;
        }

        /* Start the async worker thread */

    /* Set thread-name for debugging purposes */
        snprintf(thread_name,sizeof(thread_name),
                 "commadpt %4.4X thread",dev->devnum);
        thread_name[sizeof(thread_name)-1]=0;

        if(create_thread(&dev->commadpt->cthread,&sysblk.detattr,commadpt_thread,dev->commadpt,thread_name))
        {
            logmsg(D_("HHCCA022E create_thread: %s\n"),strerror(errno));
            release_lock(&dev->commadpt->lock);
            return -1;
        }
        dev->commadpt->have_cthread=1;

        /* Release the CA lock */
        release_lock(&dev->commadpt->lock);
        /* Indicate succesfull completion */
        return 0;
}

/*-------------------------------------------------------------------*/
/* Query the device definition                                       */
/*-------------------------------------------------------------------*/
static void commadpt_query_device (DEVBLK *dev, char **class,
                int buflen, char *buffer)
{
    BEGIN_DEVICE_CLASS_QUERY( "LINE", dev, class, buflen, buffer );

    snprintf(buffer,buflen,"Read count=%d, Write count=%d", dev->commadpt->read_ccw_count, dev->commadpt->write_ccw_count);
}

/*-------------------------------------------------------------------*/
/* Close the device                                                  */
/* Invoked by HERCULES shutdown & DEVINIT processing                 */
/*-------------------------------------------------------------------*/
static int commadpt_close_device ( DEVBLK *dev )
{
    if(dev->ccwtrace)
    {
        logmsg(_("HHCCA300D %4.4X:Closing down\n"),dev->devnum);
    }

    /* Obtain the CA lock */
    obtain_lock(&dev->commadpt->lock);

    /* Terminate current I/O thread if necessary */
    if(dev->busy)
    {
        commadpt_halt(dev);
    }

    free_bufpool(dev->commadpt);

    /* release the CA lock */
    release_lock(&dev->commadpt->lock);

    /* Free all work storage */
    commadpt_clean_device(dev);

    /* Indicate to hercules the device is no longer opened */
    dev->fd=-1;

    if(dev->ccwtrace)
    {
        logmsg(_("HHCCA300D %4.4X:Closed down\n"),dev->devnum);
    }
    return 0;
}

void make_seq (COMMADPT * ca, BYTE * reqptr) {
    if (reqptr[4] == (ca->locsuba >> 8)) { /* local NCP  */
        reqptr[6] = (unsigned char)(++ca->ncpa_sscp_seqn >> 8) & 0xff;
        reqptr[7] = (unsigned char)(  ca->ncpa_sscp_seqn     ) & 0xff;
    } else
    if (reqptr[4] == (ca->rmtsuba >> 8)){ /* remote NCP */
        reqptr[6] = (unsigned char)(++ca->ncpb_sscp_seqn >> 8) & 0xff;
        reqptr[7] = (unsigned char)(  ca->ncpb_sscp_seqn     ) & 0xff;
    }
}

static void format_sna (BYTE * requestp, char * tag, int devnum) {
       char     fmtbuf[32];
       char     fmtbuf2[32];
       char     fmtbuf3[32];
       char     fmtbuf4[32];
       char     fmtbuf5[256];
       char     fmtbuf6[32];
       char     *ru_type="";
       int      len;
       sprintf(fmtbuf, "%02X%02X %02X%02X %02X%02X %02X%02X %02X%02X",
          requestp[0], requestp[1], requestp[2], requestp[3], requestp[4], requestp[5], requestp[6], requestp[7], requestp[8], requestp[9]);
       sprintf(fmtbuf2, "%02X%02X%02X",
          requestp[10], requestp[11], requestp[12]);
       len = (requestp[8] << 8) + requestp[9];
       len -= 3;   /* for len of ru only */
       sprintf(fmtbuf3, "%02X", requestp[13]);
       sprintf(fmtbuf4, "%02X", requestp[14]);
       if (len > 1)
          strcat(fmtbuf3, fmtbuf4);
       sprintf(fmtbuf4, "%02X", requestp[15]);
       if (len > 2)
          strcat(fmtbuf3, fmtbuf4);
       if (requestp[13] == 0x11)
          ru_type = "ACTPU";
       if (requestp[13] == 0x0D)
          ru_type = "ACTLU";
       if (requestp[13] == 0x0E)
          ru_type = "DACTLU";
       if (requestp[13] == 0x12)
          ru_type = "DACTPU";
       if (requestp[13] == 0xA0)
          ru_type = "SDT";
       if (requestp[13] == 0x31)
          ru_type = "BIND";
       if (requestp[13] == 0x32)
          ru_type = "UNBIND";
       if (!memcmp(&requestp[13], R010201, 3))
          ru_type = "CONTACT";
       if (!memcmp(&requestp[13], R010202, 3))
          ru_type = "DISCONTACT";
       if (!memcmp(&requestp[13], R010203, 3))
          ru_type = "IPLINIT";
       if (!memcmp(&requestp[13], R010204, 3))
          ru_type = "IPLTEXT";
       if (!memcmp(&requestp[13], R010205, 3))
          ru_type = "IPLFINAL";
       if (!memcmp(&requestp[13], R01020A, 3))
          ru_type = "ACTLINK";
       if (!memcmp(&requestp[13], R01020B, 3))
          ru_type = "DACTLINK";
       if (!memcmp(&requestp[13], R010211, 3)) {
	    sprintf(fmtbuf6, "%s[%02x]", "SETCV", requestp[18]);
            ru_type = fmtbuf6;
            if ((requestp[10] & 0x80) != 0)
                ru_type = "SETCV";
	  }
       if (!memcmp(&requestp[13], R010280, 3))
          ru_type = "CONTACTED";
       if (!memcmp(&requestp[13], R010281, 3))
          ru_type = "INOP";
       if (!memcmp(&requestp[13], R010284, 3))
          ru_type = "REQCONT";
       if (!memcmp(&requestp[13], R01021B, 3))
          ru_type = "REQDISCONT";
       if (!memcmp(&requestp[13], R01021A, 3))
          ru_type = "FNA";
       if (!memcmp(&requestp[13], R01020F, 3))
          ru_type = "ABCONN";
       if (!memcmp(&requestp[13], R010219, 3))
          ru_type = "ANA";
       if (!memcmp(&requestp[13], R010216, 3))
          ru_type = "ACTCONNIN";
       if (!memcmp(&requestp[13], R010217, 3))
          ru_type = "DACTCONNIN";
       if ((requestp[10] & 0x08) == 0)
          ru_type = "";
       sprintf(fmtbuf5, "%4.4X: %s: %s %s %-6.6s %s\n", devnum, tag, fmtbuf, fmtbuf2, fmtbuf3, ru_type);
       logmsg(fmtbuf5);
}

static void make_sna_requests2 (COMMADPT *ca) {
        BYTE    *respbuf;
        BYTE    *ru_ptr;
        int     ru_size;
        void    *eleptr;
        int     bufp = 0;
    while (ca->inpbufl > 0) {
        eleptr = get_bufpool(&ca->freeq);
        if (!eleptr)  {
                logmsg("no buffers trying to send SNA request2\n");
                return;
        }
        respbuf = SIZEOF_INT_P + (BYTE*)eleptr;

        /* first do the ten-byte FID1 TH */
        respbuf[0] = 0x1C;
        respbuf[1] = 0x00;
        respbuf[2] = ca->tso_addr0;   // daf
        respbuf[3] = ca->tso_addr1;
        respbuf[4] = ca->lu_addr0;   // oaf
        respbuf[5] = ca->lu_addr1;   // oaf
        respbuf[6] = (unsigned char)(++ca->lu_lu_seqn >> 8) & 0xff;
        respbuf[7] = (unsigned char)(  ca->lu_lu_seqn     ) & 0xff;

        /* do RH */
        respbuf[10] = 0x00;
        if (!bufp) {
            respbuf[10] |= 0x02;      /* set first in chain */
        }
        respbuf[11] = 0x90;
        respbuf[12] = 0x00;

        /* do RU */

        // FIXME - max. ru_size should be based on BIND settings
	// A true fix would also require code changes to READ CCW processing
	// including possibly (gasp) segmenting long PIUs into multiple BTUs
	// JW: still not fixed but unitsz is now an external parameter
	//     to allow easier modification
        ru_size = min(ca->unitsz-(BUFPD+10+3),ca->inpbufl);
        ru_ptr = &respbuf[13];

        if (!ca->bindflag) {
           // send as character-coded logon to SSCP
           if (ru_size > 0 && (ca->inpbuf[ca->inpbufl-1] == 0x0d || ca->inpbuf[ca->inpbufl-1] == 0x25)) {
               ru_size--;
           }
           if (ru_size > 0 && (ca->inpbuf[ca->inpbufl-1] == 0x0d || ca->inpbuf[ca->inpbufl-1] == 0x25)) {
               ru_size--;
           }
            respbuf[2] = ca->sscp_addr0;
            respbuf[3] = ca->sscp_addr1;
            respbuf[11] = 0x80;
            respbuf[12] = 0x00;
        }
        memcpy(ru_ptr, &ca->inpbuf[bufp], ru_size);
        bufp        += ru_size;
        ca->inpbufl -= ru_size;
	if (!ca->is_3270) {
            ca->inpbufl = 0;
        }
        if (!ca->inpbufl) {
            respbuf[10] |= 0x01;      /* set last in chain */
	    if (ca->bindflag) {
              respbuf[12] |= 0x20;      /* set CD */
	    }
        }

        /* set length field in TH */
        ru_size += 3;   /* for RH */
        respbuf[8] = (unsigned char)(ru_size >> 8) & 0xff;
        respbuf[9] = (unsigned char)(ru_size     ) & 0xff;

        put_bufpool(&ca->sendq, eleptr);
    } /* end of while (ca->inpbufl > 0) */
}

static void make_sna_requests3 (COMMADPT *ca) {
        BYTE    *respbuf;
        BYTE    *ru_ptr;
        int     ru_size;
        void    *eleptr;
        if (!ca->telnet_int) return;
        eleptr = get_bufpool(&ca->freeq);
        if (!eleptr)  {
                logmsg("no buffers trying to send SNA request3\n");
                return;
        }
        respbuf = SIZEOF_INT_P + (BYTE*)eleptr;

        /* first do the ten-byte FID1 TH */
        respbuf[0] = 0x1D;
        respbuf[1] = 0x00;
        respbuf[2] = ca->tso_addr0;   // daf
        respbuf[3] = ca->tso_addr1;
        respbuf[4] = ca->lu_addr0;   // oaf
        respbuf[5] = ca->lu_addr1;   // oaf
        respbuf[6] = 0x11;
        respbuf[7] = 0x11;

        /* do RH */
        respbuf[10] = 0x4B;
        respbuf[11] = 0x80;
        respbuf[12] = 0x00;

        /* do RU */
        ru_size = 0;
        ru_ptr = &respbuf[13];

        ru_ptr[ru_size++] = 0xc9;      // SIG
        ru_ptr[ru_size++] = 0x00;
        ru_ptr[ru_size++] = 0x01;

        ru_size += 3;   /* for RH */
        respbuf[8] = (unsigned char)(ru_size >> 8) & 0xff;
        respbuf[9] = (unsigned char)(ru_size     ) & 0xff;

        put_bufpool(&ca->sendq, eleptr);
        ca->telnet_int = 0;
}

static void make_sna_requests4 (COMMADPT *ca, int flag, BYTE pu_type) {
	/* send type flag: 0=REQCONT 1=REQDISCONT */
        BYTE    *respbuf;
        BYTE    *ru_ptr;
        int     ru_size;
        U32     stids;
        void    *eleptr;
        eleptr = get_bufpool(&ca->freeq);
        if (!eleptr)  {
                logmsg("no buffers trying to send SNA request4\n");
                return;
        }
        respbuf = SIZEOF_INT_P + (BYTE*)eleptr;

        /* first do the ten-byte FID1 TH */
        respbuf[0] = 0x1C;
        respbuf[1] = 0x00;
        respbuf[2] = ca->sscp_addr0;   // daf
        respbuf[3] = ca->sscp_addr1;
	// set oaf
	if (flag == 0) {
            respbuf[4] = ca->ncp_addr0;
            respbuf[5] = ca->ncp_addr1;
            make_seq(ca, respbuf);
        } else {
            respbuf[4] = ca->pu_addr0;
            respbuf[5] = ca->pu_addr1;
            respbuf[6] = 0x00;
            respbuf[7] = 0x01;
        }

        /* do RH */
        respbuf[10] = 0x0b;
        respbuf[11] = 0x00;
        respbuf[12] = 0x00;

        /* do RU */
        ru_size = 0;
        ru_ptr = &respbuf[13];
        if (flag == 0) {
            ru_ptr[ru_size++] = 0x01;      // REQCONT (REQUEST CONTACT)
            ru_ptr[ru_size++] = 0x02;
            ru_ptr[ru_size++] = 0x84;

            ru_ptr[ru_size++] = (ca->rmtsuba >> 8); // network address of link
            ru_ptr[ru_size++] = 0x01;

            ru_ptr[ru_size++] = pu_type;      // PU type

            ru_ptr[ru_size++] = 0x00;

            stids = ((ca->idblk << 20) & 0xfff00000) | (ca->idnum & 0x000fffff); // 12 bit IDBLK, 20 bit IDNUM
            ru_ptr[ru_size++] = (stids >> 24) &0xff;
            ru_ptr[ru_size++] = (stids >> 16) &0xff;
            ru_ptr[ru_size++] = (stids >>  8) &0xff;
            ru_ptr[ru_size++] =  stids        &0xff;
        } else {
            ru_ptr[ru_size++] = 0x01;      // REQDISCONT (REQUEST DISCONTACT)
            ru_ptr[ru_size++] = 0x02;
            ru_ptr[ru_size++] = 0x1B;
            ru_ptr[ru_size++] = 0x00;
	}
        ru_size += 3;   /* for RH */
        respbuf[8] = (unsigned char)(ru_size >> 8) & 0xff;
        respbuf[9] = (unsigned char)(ru_size     ) & 0xff;

        put_bufpool(&ca->sendq, eleptr);
        ca->telnet_int = 0;
}

static void make_sna_requests5 (COMMADPT *ca) {
        BYTE    *respbuf;
        BYTE    *ru_ptr;
        int     ru_size;
        void    *eleptr;
        eleptr = get_bufpool(&ca->freeq);
        if (!eleptr)  {
                logmsg("no buffers trying to send SNA request5\n");
                return;
        }
        respbuf = SIZEOF_INT_P + (BYTE*)eleptr;

        /* first do the ten-byte FID1 TH */
        respbuf[0] = 0x1C;
        respbuf[1] = 0x00;
        respbuf[2] = ca->sscp_addr0;   // daf
        respbuf[3] = ca->sscp_addr1;
        respbuf[4] = ca->ncp_addr0;    // oaf
        respbuf[5] = ca->ncp_addr1;
	// set seq no.
        make_seq(ca, respbuf);
        /* do RH */
        respbuf[10] = 0x0B;
        respbuf[11] = 0x00;
        respbuf[12] = 0x00;

        /* do RU */
        ru_size = 0;
        ru_ptr = &respbuf[13];

        ru_ptr[ru_size++] = 0x01;      // INOP
        ru_ptr[ru_size++] = 0x02;
        ru_ptr[ru_size++] = 0x81;
        ru_ptr[ru_size++] = ca->pu_addr0;
        ru_ptr[ru_size++] = ca->pu_addr1;
        ru_ptr[ru_size++] = 0x01;      // format/reason

        ru_size += 3;   /* for RH */
        respbuf[8] = (unsigned char)(ru_size >> 8) & 0xff;
        respbuf[9] = (unsigned char)(ru_size     ) & 0xff;

        put_bufpool(&ca->sendq, eleptr);
}

void make_sna_requests (BYTE * requestp, COMMADPT *ca) {
        BYTE    *respbuf;
        BYTE    *ru_ptr;
        int     ru_size;
        void    *eleptr;
        if (memcmp(&requestp[13], R010201, 3)) return;   // we only want to process CONTACT
        eleptr = get_bufpool(&ca->freeq);
        if (!eleptr)  {
                logmsg("no buffers trying to send SNA request\n");
                return;
        }
        respbuf = SIZEOF_INT_P + (BYTE*)eleptr;

        /* first do the ten-byte FID1 TH */
//        respbuf[0] = requestp[0];
//        respbuf[1] = requestp[1];
        respbuf[0] = 0x1c;
        respbuf[1] = 0x00;
        respbuf[2] = requestp[4];   // daf
        respbuf[3] = requestp[5];
        respbuf[4] = requestp[2];   // oaf
        respbuf[5] = requestp[3];
        make_seq(ca, respbuf);
        /* do RH */
        respbuf[10] = requestp[10];
        respbuf[11] = requestp[11];
        respbuf[11] = 0x00;
        respbuf[12] = requestp[12];

        /* make a CONTACTED RU */
        ru_size = 0;
        ru_ptr = &respbuf[13];
        ru_ptr[ru_size++] = 0x01;
        ru_ptr[ru_size++] = 0x02;
        ru_ptr[ru_size++] = 0x80;
        ru_ptr[ru_size++] = requestp[16];
        ru_ptr[ru_size++] = requestp[17];
        ru_ptr[ru_size++] = 0x01;

        /* set length field in TH */
        ru_size += 3;   /* for RH */
        respbuf[8] = (unsigned char)(ru_size >> 8) & 0xff;
        respbuf[9] = (unsigned char)(ru_size     ) & 0xff;

        put_bufpool(&ca->sendq, eleptr);
}

void make_sna_response (BYTE * requestp, COMMADPT *ca) {
        BYTE    *respbuf;
        BYTE    *ru_ptr;
        int     ru_size;
        void    *eleptr;
        BYTE    obuf[4096];
        BYTE    buf[BUFLEN_3270];
        int     amt;
        int     i1;

        if ((requestp[10] & 0x80) != 0) return;   // disregard if this is a resp.
        if ((requestp[10] & (unsigned char)0xfc) == 0x00 && requestp[2] == ca->lu_addr0 && requestp[3] == ca->lu_addr1 && ca->sfd > 0) {   /* if type=data, and DAF matches up, and socket exists */
          amt = (requestp[8] << 8) + requestp[9];
          amt -= 3;
          if (ca->is_3270) {
            memcpy(buf, &requestp[13], amt);
            /* Double up any IAC bytes in the data */
            amt = double_up_iac (buf, amt);
            /* Append telnet EOR marker at end of data */
            if ((requestp[10] & 0x01) == 0x01) {   /* if last-in-chain is set */
                buf[amt++] = IAC;
                buf[amt++] = EOR_MARK;
            }
            /* Send the data to the client */
            logdump ("SEND", ca->dev, buf, amt);
            write_socket(ca->sfd,buf,amt);
          } else {
            // convert data portion to ASCII and write to remote user
            if (amt > 0) {
                memcpy(obuf, &requestp[13], amt);
                for (i1=0; i1<amt; i1++) {
                    obuf[i1] = guest_to_host(obuf[i1]);
                }
                logdump ("SEND", ca->dev, obuf, amt);
                write_socket(ca->sfd,obuf,amt);
            }
          }
        }
        if ((requestp[11] & 0xf0) != 0x80) return;   // disregard if not DR1 requested

        eleptr = get_bufpool(&ca->freeq);
        if (!eleptr)  {
                logmsg("no buffers trying to send SNA response\n");
                return;
        }
        respbuf = SIZEOF_INT_P + (BYTE*)eleptr;

        /* first do the ten-byte FID1 TH */
        respbuf[0] = requestp[0];
        respbuf[1] = requestp[1];
        respbuf[2] = requestp[4];   // daf
        respbuf[3] = requestp[5];
        respbuf[4] = requestp[2];   // oaf
        respbuf[5] = requestp[3];
        respbuf[6] = requestp[6];   // seq #
        respbuf[7] = requestp[7];

        /* do RH */
        respbuf[10] = requestp[10];
        respbuf[10] |= 0x83;         // indicate this is a resp.
        respbuf[11] = requestp[11];
//        respbuf[12] = requestp[12];
        respbuf[12] = 0x00;

        /* do RU */
        ru_size = 0;
        ru_ptr = &respbuf[13];
        if ((requestp[10] & 0x08) != 0)
            ru_ptr[ru_size++] = requestp[13];
        if (requestp[13] == 0x11 && requestp[14] == 0x02) {   /* ACTPU (NCP)*/
	    ca->ncp_addr0 = requestp[2];
	    ca->ncp_addr1 = requestp[3];
//            ca->ncp_sscp_seqn = 0;
            ru_ptr[ru_size++] = 0x02;
            if (requestp[2] == (ca->rmtsuba >> 8)){      /* remote NCP    */
                memcpy(&ru_ptr[ru_size],ca->rmtncpnm,8); /* load mod name */
                ru_size += 8;
                ca->ncpb_sscp_seqn = 0;
            } else
            if (requestp[2] == (ca->locsuba >> 8)){      /* local  NCP    */
                memcpy(&ru_ptr[ru_size],ca->locncpnm,8); /* load mod name */
                ru_size += 8;
                ca->ncpa_sscp_seqn = 0;
            }
        }
        if (requestp[13] == 0x11 && requestp[14] == 0x01) {   /* ACTPU (PU)*/
            ru_ptr[ru_size++] = 0x01;
            /* save daf as our own net addr */
	    ca->pu_addr0 = requestp[2];
	    ca->pu_addr1 = requestp[3];
        }
        if (requestp[13] == 0x01) {   /* 01XXXX Network Services */
            ru_ptr[ru_size++] = requestp[14];
            ru_ptr[ru_size++] = requestp[15];
        }
        if (!memcmp(&requestp[13], R010219, 3) && ca->sfd > 0) {   /* ANA */
            if (!ca->is_3270) {
              connect_message(ca->sfd, (requestp[20] << 8) + requestp[21], 0);
	    }
        }
        if (requestp[13] == 0x0D) {   /* ACTLU */
            /* save daf as our own net addr */
            ca->lu_addr0 = requestp[2];
            ca->lu_addr1 = requestp[3];
            /* save oaf as our sscp net addr */
            ca->sscp_addr0 = requestp[4];
            ca->sscp_addr1 = requestp[5];

            ca->lu_sscp_seqn = 0;
            ca->bindflag = 0;
        }
        if (requestp[13] == 0x0E || !memcmp(&requestp[13], R01020F, 3)) {  // DACTLU or ABCONN
            if (!ca->is_3270) {
              connect_message(ca->sfd, 0, 1);
	    }
	    ca->hangup = 1;
        }
        if (requestp[13] == 0x31) {   /* BIND */
            /* save oaf from BIND request */
            ca->tso_addr0 = requestp[4];
            ca->tso_addr1 = requestp[5];
            ca->lu_lu_seqn = 0;
            ca->bindflag = 1;
        }
        if (requestp[13] == 0x32 && requestp[14] != 0x02) {   /* BIND */
            ca->bindflag = 0;
        }
#if 0
        if (requestp[13] == 0x32 && requestp[14] == 0x01 && ca->sfd > 0) {   /* UNBIND */
            close_socket(ca->sfd);
            ca->sfd=-1;
        }
#endif

        /* set length field in TH */
        ru_size += 3;   /* for RH */
        respbuf[8] = (unsigned char)(ru_size >> 8) & 0xff;
        respbuf[9] = (unsigned char)(ru_size     ) & 0xff;

        put_bufpool(&ca->sendq, eleptr);
}

enum fid_remap {
	MAP_FID1_FID2,
	MAP_FID2_FID1
};

static void th_remap(enum fid_remap r, BYTE * thptr, U16 locsuba)
{ /* for 3791 support, remaps SNA FID1 <--> FID2 TH headers */
int     thmpf;
int     thm2;
int     thdaf;
int     thoaf;
int     thsnf;
int     len;

    if (r == MAP_FID1_FID2)
    {
        thmpf = thptr[0];
        thm2  = thptr[1];
        thdaf = (thptr[2] << 8) + thptr[3];
        thoaf = (thptr[4] << 8) + thptr[5];
        thsnf = (thptr[6] << 8) + thptr[7];
        len = (thptr[8] << 8) + thptr[9];
        len += 10;
        thptr[0] = (len >> 8) & 0xff;
        thptr[1] = len & 0xff;
        thptr[2] = 0x00;
        thptr[3] = 0x00;
        thptr[4] = 0x20 | (thmpf & 0x0f);
        thptr[5] = thm2;
        thptr[6] = thdaf & 0xff;
        thptr[7] = thoaf & 0xff;
        thptr[8] = (thsnf >> 8) & 0xff;
        thptr[9] = thsnf & 0xff;
    }
    else
    { /* map fid2 to fid1 */
        len = (thptr[0] << 8) + thptr[1];
        thmpf = thptr[4];
        thm2  = thptr[5];
        thdaf = thptr[6];
        thoaf = thptr[7];
        thsnf = (thptr[8] << 8) + thptr[9];
        thdaf |= locsuba; 
        thoaf |= 0x0800;   /* SSCP subarea = 1 (maxsuba=31) */
        len -= 10;
        thptr[0] = 0x10 | (thmpf & 0x0f);
        thptr[1] = thm2;
        thptr[2] = (thdaf >> 8) & 0xff;
        thptr[3] = thdaf & 0xff;
        thptr[4] = (thoaf >> 8) & 0xff;
        thptr[5] = thoaf & 0xff;
        thptr[6] = (thsnf >> 8) & 0xff;
        thptr[7] = thsnf & 0xff;
        thptr[8] = (len >> 8) & 0xff;
        thptr[9] = len & 0xff;
    }
}

/*-------------------------------------------------------------------*/
/* Execute a Channel Command Word                                    */
/*-------------------------------------------------------------------*/
static void commadpt_execute_ccw (DEVBLK *dev, BYTE code, BYTE flags,
        BYTE chained, U16 count, BYTE prevcode, int ccwseq,
        BYTE *iobuf, BYTE *more, BYTE *unitstat, U16 *residual)
{
U32 num;                        /* Work : Actual CCW transfer count                   */
BYTE    *piudata;
int     piusize;
void    *eleptr;
int     llsize;
    
    UNREFERENCED(flags);
    UNREFERENCED(chained);
    UNREFERENCED(prevcode);
    UNREFERENCED(ccwseq);
    *residual = 0;
    /*
     * Obtain the COMMADPT lock
     */
    if(dev->ccwtrace)
    {
        logmsg(_("HHCCA300D %4.4X:CCW Exec - Entry code = %x\n"),dev->devnum,code);
    }
    obtain_lock(&dev->commadpt->lock);
    switch (code) {
        /*---------------------------------------------------------------*/
        /* BASIC SENSE                                                   */
        /*---------------------------------------------------------------*/
        case 0x04:
                dev->commadpt->unack_attn_count = 0;
                num=count<dev->numsense?count:dev->numsense;
                *more=count<dev->numsense?1:0;
                memcpy(iobuf,dev->sense,num);
                *residual=count-num;
                *unitstat=CSW_CE|CSW_DE;
                break;

        /*---------------------------------------------------------------*/
        /* READ type CCWs                                                */
        /*---------------------------------------------------------------*/
        case 0x02:   /* READ */
                dev->commadpt->read_ccw_count++;
                dev->commadpt->unack_attn_count = 0;
                *more = 0;
                make_sna_requests2(dev->commadpt);
                make_sna_requests3(dev->commadpt);
                eleptr = get_bufpool(&dev->commadpt->sendq);
                *residual=count;
                if (eleptr) {
                    piudata = SIZEOF_INT_P + (BYTE*)eleptr;
                    piusize = (piudata[8] << 8) + piudata[9];
                    piusize += 10;    // for FID1 TH
                    iobuf[0] = BUFPD;
                    memcpy (&iobuf[BUFPD], piudata, piusize);
                    if (dev->commadpt->emu3791) {
                        llsize = piusize + BUFPD;
                        iobuf[0] = (llsize >> 8) & 0xff;
                        iobuf[1] = llsize & 0xff;
                        th_remap(MAP_FID1_FID2, &iobuf[BUFPD], dev->commadpt->locsuba);
                    }
                    *residual=count - (piusize + BUFPD);
                    logdump("READ", dev, &iobuf[BUFPD], piusize);
                    if (dev->commadpt->debug_sna)
                        format_sna(piudata, "RD", dev->devnum);
                    put_bufpool(&dev->commadpt->freeq, eleptr);
                }
                *unitstat=CSW_CE|CSW_DE;
#if 0
                if (dev->commadpt->sendq) {
                    *unitstat|=CSW_ATTN;
                }
#endif
                *unitstat|=CSW_UX;
                break;

        /*---------------------------------------------------------------*/
        /* 3791 WRITE BLOCK                                              */
        /*---------------------------------------------------------------*/
        case 0x05:
                logdump("WRITE BLOCK", dev, iobuf, count);
                *residual=0;
                *unitstat=CSW_CE|CSW_DE;
                break;

        /*---------------------------------------------------------------*/
        /* WRITE type CCWs                                               */
        /*---------------------------------------------------------------*/
        case 0x09:   /* WRITE BREAK */
        case 0x01:   /* WRITE */
                dev->commadpt->write_ccw_count++;
                dev->commadpt->unack_attn_count = 0;
                logdump("WRITE", dev, iobuf, count);
                if (dev->commadpt->emu3791 && (iobuf[4] & 0xf0) == 0x20)
                    th_remap(MAP_FID2_FID1, iobuf, dev->commadpt->locsuba);
                if ((iobuf[0] & 0xf0) == 0x10) {  // if FID1
                    if (dev->commadpt->debug_sna)
                        format_sna(iobuf, "WR", dev->devnum);
                    make_sna_response(iobuf, dev->commadpt);
                    make_sna_requests(iobuf, dev->commadpt);
                }
                *residual=0;
                *unitstat=CSW_CE|CSW_DE;
#if 0
                if (dev->commadpt->sendq) {
                    *unitstat|=CSW_ATTN;
                    *unitstat|=CSW_UX|CSW_ATTN;
                }
#endif
                break;

        /*---------------------------------------------------------------*/
        /* CCWs to be treated as NOPs                                    */
        /*---------------------------------------------------------------*/
        case 0x03:   /* NOP */
        case 0x93:   /* RESTART */
        case 0x31:   /* WS0 */
        case 0x51:   /* WS1 */
        case 0x32:   /* RS0 */
        case 0x52:   /* RS1 */
                *residual=count;
                *unitstat=CSW_CE|CSW_DE;
                break;

        default:
        /*---------------------------------------------------------------*/
        /* INVALID OPERATION                                             */
        /*---------------------------------------------------------------*/
            /* Set command reject sense byte, and unit check status */
            *unitstat=CSW_CE+CSW_DE+CSW_UC;
            dev->sense[0]=SENSE_CR;
            break;

    }
    release_lock(&dev->commadpt->lock);
}


/*---------------------------------------------------------------*/
/* DEVICE FUNCTION POINTERS                                      */
/*---------------------------------------------------------------*/

#if defined(OPTION_DYNAMIC_LOAD)
static
#endif
DEVHND com3705_device_hndinfo = {
        &commadpt_init_handler,        /* Device Initialisation      */
        &commadpt_execute_ccw,         /* Device CCW execute         */
        &commadpt_close_device,        /* Device Close               */
        &commadpt_query_device,        /* Device Query               */
        NULL,                          /* Device Start channel pgm   */
        NULL,                          /* Device End channel pgm     */
        NULL,                          /* Device Resume channel pgm  */
        NULL,                          /* Device Suspend channel pgm */
        NULL,                          /* Device Read                */
        NULL,                          /* Device Write               */
        NULL,                          /* Device Query used          */
        NULL,                          /* Device Reserve             */
        NULL,                          /* Device Release             */
        NULL,                          /* Device Attention           */
        commadpt_immed_command,        /* Immediate CCW Codes        */
        NULL,                          /* Signal Adapter Input       */
        NULL,                          /* Signal Adapter Output      */
        NULL,                          /* Hercules suspend           */
        NULL                           /* Hercules resume            */
};


/* Libtool static name colision resolution */
/* note : lt_dlopen will look for symbol & modulename_LTX_symbol */
#if !defined(HDL_BUILD_SHARED) && defined(HDL_USE_LIBTOOL)
#define hdl_ddev hdt3705_LTX_hdl_ddev
#define hdl_depc hdt3705_LTX_hdl_depc
#define hdl_reso hdt3705_LTX_hdl_reso
#define hdl_init hdt3705_LTX_hdl_init
#define hdl_fini hdt3705_LTX_hdl_fini
#endif


#if defined(OPTION_DYNAMIC_LOAD)
HDL_DEPENDENCY_SECTION;
{
     HDL_DEPENDENCY(HERCULES);
     HDL_DEPENDENCY(DEVBLK);
     HDL_DEPENDENCY(SYSBLK);
}
END_DEPENDENCY_SECTION;


#if defined(WIN32) && !defined(HDL_USE_LIBTOOL) && !defined(_MSVC_)
  #undef sysblk
  HDL_RESOLVER_SECTION;
  {
    HDL_RESOLVE_PTRVAR( psysblk, sysblk );
  }
  END_RESOLVER_SECTION;
#endif


HDL_DEVICE_SECTION;
{
    HDL_DEVICE(3705, com3705_device_hndinfo );
}
END_DEVICE_SECTION;
#endif