|
root / base / usr / src / cmd / backup / lib
lib Plain Text 2304 lines 53.3 KB
   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
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

LIBRARY=	libdump.a

# Has to be before include of Makefile.backup
# This should be POFILE=libdump.po, but that causes make to
# fall over due to some seriously weird interactions in the
# various indirectly-included makefiles.  So, since this works
# and is otherwise harmless, we fake it.
PROG=		libdump

# Include library definitions, then backup definitions, as in general
# we want the flags and such from our tree.

include ../../../lib/Makefile.lib
include ../Makefile.backup

SRCDIR =	.

# Specifically request the construction of a static library.
# This library is not installed in the proto area.
LIBS=	$(LIBRARY)

HDRS=		../include/byteorder.h \
	../include/memutils.h ../include/myrcmd.h \
	../../../head/protocols/dumprestore.h \
	../include/rmt.h

YFILE=		getdate.y
YSRC=		getdate.c

CLOBBERFILES +=	$(LIBS) $(GLIB)

LOBJS=		rmtlib.o myrcmd.o \
		$(YSRC:%.c=%.o) \
		byteorder.o memutils.o $(RPC_CLNT:%.c=%.o) $(RPC_XDR:%.c=%.o)

OBJECTS=	$(LOBJS)
POFILES=	$(OBJECTS:.o=.po)
GENERAL=	../include
GLOBAL=		../../../head
CPPFLAGS=	-I$(GENERAL) -I$(GLOBAL) $(CPPFLAGS.master)
CERRWARN +=	-Wno-implicit-function-declaration
CERRWARN +=	-Wno-parentheses
CERRWARN +=	-Wno-unused-variable
CLEANFILES=	$(OBJECTS) $(DEBUGS) $(YSRC) $(LIBRARY)

# because of labels from yacc
objs/getdate.o : CERRWARN +=	-Wno-unused-label

# support for -g library
GLIB=		libdump_g.a
DEBUGS=		$(OBJECTS:%=.debug/%)
$(GLIB):	AROBJS = $(DEBUGS)
$(GLIB):	DIR = .debug
$(GLIB):	CFLAGS= $(CCGDEBUG) -DDEBUG -DYYDEBUG $(SBFLAGS)

.KEEP_STATE:

all:	$(LIBS)

debug:	$(LIBS) $(GLIB)

.debug:
	-@mkdir -p $@

.debug/%.o: %.c
	$(COMPILE.c) -o $@ $<
	$(POST_PROCESS_O)

$(GLIB): .debug $$(DEBUGS)
	$(BUILD.AR)
	$(POST_PROCESS_A)

$(OBJECTS):	$(HDRS)

install:	all

$(POFILE):	$(POFILES)
	$(RM) $@; cat $(POFILES) > $@

check:	$(HDRS)
	$(CSTYLE) $(CSTYLEFLAGS) `echo $(SRCS) | sed -e s/getdate.c//` $(HDRS)
	$(HDRCHK) $(HDRCHKFLAGS) $(HDRS)

# include library targets
include ../../../lib/Makefile.targ

_msg:		$(POFILE)
/*
 * Copyright 1996, 1998, 2002-2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
/*	  All Rights Reserved	*/

/*
 * Copyright (c) 1983 Regents of the University of California.
 * All rights reserved.  The Berkeley software License Agreement
 * specifies the terms and conditions for redistribution.
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/vnode.h>
#include <locale.h>
#include <stdlib.h>
#include <sys/fs/ufs_inode.h>
#include <sys/fs/ufs_fsdir.h>
#include <sys/fs/ufs_acl.h>
#include <byteorder.h>

struct byteorder_ctx *
byteorder_create(void)
{
	struct byteorder_ctx *rc;

	/* LINTED: assignment value is used */
	if ((rc = (struct byteorder_ctx *)calloc(1, sizeof (*rc))) == NULL)
		return (NULL);
	return (rc);
}

void
byteorder_destroy(struct byteorder_ctx *ctx)
{
	if (ctx != NULL)
		(void) free((char *)ctx);
}

void
byteorder_banner(struct byteorder_ctx *ctx, FILE *filep)
{
	if ((! ctx->initialized) || (filep == NULL))
		return;

	if (ctx->Bcvt)
		(void) fprintf(filep, gettext("Note: doing byte swapping\n"));
}

/*
 * Control string (cp) is a sequence of optional numeric repeat counts
 * and format specifiers.  s/w/h indicate a 16-bit quantity is to be
 * byte-swapped, l indicates a 32-bit quantity.  A repeat count is
 * identical in effect to having the following format character appear
 * N times (e.g., "3h" is equivalent to "hhh").
 *
 * The byte-swapping is performed in-place, in the buffer sp.
 */
void
swabst(char *cp, uchar_t *sp)
{
	int n = 0;
	uchar_t c;

	while (*cp) {
		switch (*cp) {
		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			n = (n * 10) + (*cp++ - '0');
			continue;

		case 's': case 'w': case 'h':
			/* LINTED: type punning ok here */
			c = sp[0]; sp[0] = sp[1]; sp[1] = c;
			sp++;
			break;

		case 'l':
			c = sp[0]; sp[0] = sp[3]; sp[3] = c;
			c = sp[2]; sp[2] = sp[1]; sp[1] = c;
			sp += 3;
		}
		/* Any other character, like 'b' counts as byte. */
		sp++;
		if (n <= 1) {
			n = 0; cp++;
		} else
			n--;
	}
}

uint32_t
swabl(uint32_t x)
{
	uint32_t l = x;

	swabst("l", (uchar_t *)&l);
	/* LINTED: type punning ok here */
	return (l);
}

static int
checksum(struct byteorder_ctx *ctx, int *b, int size)
{
	uint_t i, j;

	if (! ctx->initialized)
		return (-1);

	/*
	 * We should only be called on to checksum u_spcl's, so make
	 * sure that's what we got.
	 */
	if ((unsigned)size < tp_bsize)
		return (-1);

	j = tp_bsize / sizeof (int);
	i = 0;
	if (!ctx->Bcvt) {
		do
			i += (uint_t)*b++;
		while (--j);
	} else {
		/*
		 * What happens if we want to read restore tapes
		 * for a 16bit int machine???
		 */
		do
			i += swabl(*b++);
		while (--j);
	}

	return (i != CHECKSUM);
}

/*
 * normspcl() checks that a spclrec is valid.  it does byte/quad
 * swapping if necessary, and checks the checksum.  it does NOT convert
 * from the old filesystem format; gethead() in tape.c does that.
 *
 * ctx is the context for this package
 * sp is a pointer to a current-format spclrec, that may need to be
 *	byteswapped.
 * cs is a pointer to the thing we want to checksum.  if we're
 *	converting from the old filesystem format, it might be different
 *	from sp.
 * css is the size of the thing we want to checksum.
 * magic is the magic number we compare against.
 */

int
normspcl(struct byteorder_ctx *ctx, struct s_spcl *sp, int *cs,
    int css, int magic)
{
	u_offset_t sv;

	if ((! ctx->initialized) && (sp->c_magic != magic)) {
		if (swabl(sp->c_magic) != (uint32_t)magic)
			return (-1);
		ctx->Bcvt = 1;
	}
	ctx->initialized = 1;

	if (checksum(ctx, cs, css))
		return (-1);

	/*
	 * Unless our caller is actively trying to break us, a
	 * successful checksum() means that *sp is at least as
	 * big as what we think it should be as far as byte
	 * swapping goes.  Therefore, we don't need to do any
	 * more size checks here.
	 */

	/* handle byte swapping */
	if (ctx->Bcvt) {
		/*
		 * byteswap
		 *	c_type, c_date, c_ddate, c_volume, c_tapea, c_inumber,
		 *	c_magic, c_checksum,
		 *	all of c_dinode, and c_count.
		 */

		swabst("8l4s31l", (uchar_t *)sp);

		/*
		 * byteswap
		 *	c_flags, c_firstrec, and c_spare.
		 */

		swabst("34l", (uchar_t *)&(sp->c_flags));

		/* byteswap the inodes if necessary. */

#ifndef	lint	/* lint won't shut up about sprintf below */
		if (sp->c_flags & DR_INODEINFO) {
			char buffy[BUFSIZ];
			/* Can't overflow, max len is %d format (20)+`l'+\0 */
			/* LINTED lint can't tell diff between %ld and %dl */
			(void) sprintf(buffy, "%dl", TP_NINOS);
			swabst(buffy, (uchar_t *)sp->c_data.s_inos);
		}
#endif	/* lint */

		/* if no metadata, byteswap the level */

		if (! (sp->c_flags & DR_HASMETA))
			swabst("1l", (uchar_t *)&(sp->c_level));
	}

	/* handle quad swapping (note -- we no longer perform this check */
	/*	we now do quad swapping iff we're doing byte swapping.)  */

	/*
	 * 	the following code is being changed during the large file
	 *	project. This code needed to be changed because ic_size
	 *	is no longer a quad, it has been changed to ic_lsize, which is
	 *	an offset_t, and the field "val" doesn't exist anymore.
	 */

/*
 * This is the old code. (before large file project.)
 *
 *	sv = sp->c_dinode.di_ic.ic_size.val;
 *
 *	if (ctx->Bcvt) {
 *		long foo;
 *
 *		foo = sv[1];
 *		sv[1] = sv[0];
 *		sv[0] = foo;
 *	}
 */

	/* swap the upper 32 bits of ic_lsize with the lower 32 bits */

	if (ctx->Bcvt) {
		sv = sp->c_dinode.di_ic.ic_lsize;
		sv = (sv << 32) | (sv >> 32);
		sp->c_dinode.di_ic.ic_lsize = sv;
	}

	if (sp->c_magic != magic)
		return (-1);
	return (0);
}

void
normdirect(ctx, d)
	struct byteorder_ctx *ctx;
	struct direct *d;
{
	assert(ctx->initialized);

	if (ctx->Bcvt)
		swabst("l2s", (uchar_t *)d);
}

void
normacls(struct byteorder_ctx *ctx, ufs_acl_t *acl, int n)
{
	static int complained = 0;
	int i;
	uid32_t uid;

	assert(ctx->initialized);

	if (! ctx->Bcvt)
		return;

	for (i = 0; i < n; i++) {
		swabst("1s", (uchar_t *)&(acl[i].acl_tag));  /* u_short */
		swabst("1s", (uchar_t *)&(acl[i].acl_perm)); /* o_mode_t */

		/* LINTED explicitly checking for truncation below */
		uid = (uid32_t)(acl[i].acl_who);
		if (!complained && ((uid_t)uid) != acl[i].acl_who) {
			/*
			 * The problem is that acl_who is a uid_t,
			 * and we know that the on-tape version is
			 * definitely 32 bits.  To avoid getting
			 * burned if/when uid_t becomes bigger
			 * than that, we need to do the explicit
			 * conversion and check.
			 */
			(void) fprintf(stderr,
			    "Some ACL uids have been truncated\n");
			complained = 1;
		}
		swabst("1l", (uchar_t *)&(uid));	/* uid32_t */
	}
}
%{
/*
 * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/* $OrigRevision: 2.1 $
**
**  Originally written by Steven M. Bellovin <smb@research.att.com> while
**  at the University of North Carolina at Chapel Hill.  Later tweaked by
**  a couple of people on Usenet.  Completely overhauled by Rich $alz
**  <rsalz@bbn.com> and Jim Berets <jberets@bbn.com> in August, 1990;
**  send any email to Rich.
**
**  This grammar has eight shift/reduce conflicts.
**
**  This code is in the public domain and has no copyright.
*/
/* SUPPRESS 287 on yaccpar_sccsid *//* Unusd static variable */
/* SUPPRESS 288 on yyerrlab *//* Label unused */
#include <stdio.h>
#include <ctype.h>

#include <sys/types.h>
#define NEED_TZSET
struct timeb {
    time_t		time;		/* Seconds since the epoch	*/
    unsigned short	millitm;	/* Field not used		*/
    short		timezone;
    short		dstflag;	/* Field not used		*/
};
#include <time.h>

#include <locale.h>
#include <string.h>
#include <stdlib.h>
#include <note.h>
#include <libintl.h>

#if	!defined(lint) && !defined(SABER)
static char RCS[] =
	"$Header: /home/laramie/berliner/ws/backup/usr/src/cmd/backup/lib/getdate.y,v 1.5 1992/06/09 21:46:21 sam Exp $";
#endif	/* !defined(lint) && !defined(SABER) */


#define EPOCH		1970
#define HOURN(x)	(x * 60)
#define SECSPERDAY	(24L * 60L * 60L)

#define CHECK_TM(y) (((y) % 100) < 70 ? (y) + 2000 : (y) + 1900)

/*
**  An entry in the lexical lookup table.
*/
typedef struct _TABLE {
    char	*name;
    int		type;
    time_t	value;
} TABLE;


/*
**  Daylight-savings mode:  on, off, or not yet known.
*/
typedef enum _DSTMODE {
    DSTon, DSToff, DSTmaybe
} DSTMODE;

/*
**  Meridian:  am, pm, or 24-hour style.
*/
typedef enum _MERIDIAN {
    MERam, MERpm, MER24
} MERIDIAN;


/*
**  Global variables.  We could get rid of most of these by using a good
**  union as the yacc stack.  (This routine was originally written before
**  yacc had the %union construct.)  Maybe someday; right now we only use
**  the %union very rarely.
*/
static char	*yyInput;
static DSTMODE	yyDSTmode;
static time_t	yyDayOrdinal;
static time_t	yyDayNumber;
static int	yyHaveDate;
static int	yyHaveDay;
static int	yyHaveRel;
static int	yyHaveTime;
static int	yyHaveZone;
static time_t	yyTimezone;
static time_t	yyDay;
static time_t	yyHour;
static time_t	yyMinutes;
static time_t	yyMonth;
static time_t	yySeconds;
static time_t	yyYear;
static MERIDIAN	yyMeridian;
static time_t	yyRelMonth;
static time_t	yyRelSeconds;

static char	*domainname = "hsm_libdump";	/* for dgettext() */

#define yylex 1					/* suppress yacc's definition */
%}

%union {
    time_t		Number;
    enum _MERIDIAN	Meridian;
}

%token	tAGO tDAY tDAYZONE tID tMERIDIAN tMINUTE_UNIT tMONTH tMONTH_UNIT
%token	tSEC_UNIT tSNUMBER tUNUMBER tZONE

%type	<Number>	tDAY tDAYZONE tMINUTE_UNIT tMONTH tMONTH_UNIT
%type	<Number>	tSEC_UNIT tSNUMBER tUNUMBER tZONE
%type	<Meridian>	tMERIDIAN o_merid

%%

spec	: /* NULL */
	| spec item
	;

item	: time {
	    yyHaveTime++;
	}
	| zone {
	    yyHaveZone++;
	}
	| date {
	    yyHaveDate++;
	}
	| day {
	    yyHaveDay++;
	}
	| rel {
	    yyHaveRel++;
	}
	| number
	;

time	: tUNUMBER tMERIDIAN {
	    yyHour = $1;
	    yyMinutes = 0;
	    yySeconds = 0;
	    yyMeridian = $2;
	}
	| tUNUMBER ':' tUNUMBER o_merid {
	    yyHour = $1;
	    yyMinutes = $3;
	    yySeconds = 0;
	    yyMeridian = $4;
	}
	| tUNUMBER ':' tUNUMBER tSNUMBER {
	    yyHour = $1;
	    yyMinutes = $3;
	    yyMeridian = MER24;
	    yyDSTmode = DSToff;
	    yyTimezone = - ($4 % 100 + ($4 / 100) * 60);
	}
	| tUNUMBER ':' tUNUMBER ':' tUNUMBER o_merid {
	    yyHour = $1;
	    yyMinutes = $3;
	    yySeconds = $5;
	    yyMeridian = $6;
	}
	| tUNUMBER ':' tUNUMBER ':' tUNUMBER tSNUMBER {
	    yyHour = $1;
	    yyMinutes = $3;
	    yySeconds = $5;
	    yyMeridian = MER24;
	    yyDSTmode = DSToff;
	    yyTimezone = - ($6 % 100 + ($6 / 100) * 60);
	}
	;

zone	: tZONE {
	    yyTimezone = $1;
	    yyDSTmode = DSToff;
	}
	| tDAYZONE {
	    yyTimezone = $1;
	    yyDSTmode = DSTon;
	}
	;

day	: tDAY {
	    yyDayOrdinal = 1;
	    yyDayNumber = $1;
	}
	| tDAY ',' {
	    yyDayOrdinal = 1;
	    yyDayNumber = $1;
	}
	| tUNUMBER tDAY {
	    yyDayOrdinal = $1;
	    yyDayNumber = $2;
	}
	;

date	: tUNUMBER '/' tUNUMBER {
	    yyMonth = $1;
	    yyDay = $3;
	}
	| tUNUMBER '/' tUNUMBER '/' tUNUMBER {
	    yyMonth = $1;
	    yyDay = $3;
	    yyYear = $5;
	}
	| tMONTH tUNUMBER {
	    yyMonth = $1;
	    yyDay = $2;
	}
	| tMONTH tUNUMBER ',' tUNUMBER {
	    yyMonth = $1;
	    yyDay = $2;
	    yyYear = $4;
	}
	| tUNUMBER tMONTH {
	    yyMonth = $2;
	    yyDay = $1;
	}
	| tUNUMBER tMONTH tUNUMBER {
	    yyMonth = $2;
	    yyDay = $1;
	    yyYear = $3;
	}
	;

rel	: relunit tAGO {
	    yyRelSeconds = -yyRelSeconds;
	    yyRelMonth = -yyRelMonth;
	}
	| relunit
	;

relunit	: tUNUMBER tMINUTE_UNIT {
	    yyRelSeconds += $1 * $2 * 60L;
	}
	| tSNUMBER tMINUTE_UNIT {
	    yyRelSeconds += $1 * $2 * 60L;
	}
	| tMINUTE_UNIT {
	    yyRelSeconds += $1 * 60L;
	}
	| tSNUMBER tSEC_UNIT {
	    yyRelSeconds += $1;
	}
	| tUNUMBER tSEC_UNIT {
	    yyRelSeconds += $1;
	}
	| tSEC_UNIT {
	    yyRelSeconds++;
	}
	| tSNUMBER tMONTH_UNIT {
	    yyRelMonth += $1 * $2;
	}
	| tUNUMBER tMONTH_UNIT {
	    yyRelMonth += $1 * $2;
	}
	| tMONTH_UNIT {
	    yyRelMonth += $1;
	}
	;

number	: tUNUMBER {
	    if (yyHaveTime && yyHaveDate && !yyHaveRel)
		yyYear = $1;
	    else {
		yyHaveTime++;
		if ($1 < 100) {
		    yyHour = $1;
		    yyMinutes = 0;
		}
		else {
		    yyHour = $1 / 100;
		    yyMinutes = $1 % 100;
		}
		yySeconds = 0;
		yyMeridian = MER24;
	    }
	}
	;

o_merid	: /* NULL */ {
	    $$ = MER24;
	}
	| tMERIDIAN {
	    $$ = $1;
	}
	;

%%

/* Month and day table. */
static TABLE	MonthDayTable[] = {
    { "january",	tMONTH,  1 },
    { "february",	tMONTH,  2 },
    { "march",		tMONTH,  3 },
    { "april",		tMONTH,  4 },
    { "may",		tMONTH,  5 },
    { "june",		tMONTH,  6 },
    { "july",		tMONTH,  7 },
    { "august",		tMONTH,  8 },
    { "september",	tMONTH,  9 },
    { "sept",		tMONTH,  9 },
    { "october",	tMONTH, 10 },
    { "november",	tMONTH, 11 },
    { "december",	tMONTH, 12 },
    { "sunday",		tDAY, 0 },
    { "monday",		tDAY, 1 },
    { "tuesday",	tDAY, 2 },
    { "tues",		tDAY, 2 },
    { "wednesday",	tDAY, 3 },
    { "wednes",		tDAY, 3 },
    { "thursday",	tDAY, 4 },
    { "thur",		tDAY, 4 },
    { "thurs",		tDAY, 4 },
    { "friday",		tDAY, 5 },
    { "saturday",	tDAY, 6 },
    { NULL }
};

/* Time units table. */
static TABLE	UnitsTable[] = {
    { "year",		tMONTH_UNIT,	12 },
    { "month",		tMONTH_UNIT,	1 },
    { "fortnight",	tMINUTE_UNIT,	14 * 24 * 60 },
    { "week",		tMINUTE_UNIT,	7 * 24 * 60 },
    { "day",		tMINUTE_UNIT,	1 * 24 * 60 },
    { "hour",		tMINUTE_UNIT,	60 },
    { "minute",		tMINUTE_UNIT,	1 },
    { "min",		tMINUTE_UNIT,	1 },
    { "second",		tSEC_UNIT,	1 },
    { "sec",		tSEC_UNIT,	1 },
    { NULL }
};

/* Assorted relative-time words. */
static TABLE	OtherTable[] = {
    { "tomorrow",	tMINUTE_UNIT,	1 * 24 * 60 },
    { "yesterday",	tMINUTE_UNIT,	-1 * 24 * 60 },
    { "today",		tMINUTE_UNIT,	0 },
    { "now",		tMINUTE_UNIT,	0 },
    { "last",		tUNUMBER,	-1 },
    { "this",		tMINUTE_UNIT,	0 },
    { "next",		tUNUMBER,	2 },
    { "first",		tUNUMBER,	1 },
/*  { "second",		tUNUMBER,	2 }, */
    { "third",		tUNUMBER,	3 },
    { "fourth",		tUNUMBER,	4 },
    { "fifth",		tUNUMBER,	5 },
    { "sixth",		tUNUMBER,	6 },
    { "seventh",	tUNUMBER,	7 },
    { "eighth",		tUNUMBER,	8 },
    { "ninth",		tUNUMBER,	9 },
    { "tenth",		tUNUMBER,	10 },
    { "eleventh",	tUNUMBER,	11 },
    { "twelfth",	tUNUMBER,	12 },
    { "ago",		tAGO,	1 },
    { NULL }
};

/* The timezone table. */
static TABLE	TimezoneTable[] = {
    { "gmt",	tZONE,     HOURN( 0) },	/* Greenwich Mean */
    { "ut",	tZONE,     HOURN( 0) },	/* Universal (Coordinated) */
    { "utc",	tZONE,     HOURN( 0) },
    { "wet",	tZONE,     HOURN( 0) },	/* Western European */
    { "bst",	tDAYZONE,  HOURN( 0) },	/* British Summer */
    { "wat",	tZONE,     HOURN( 1) },	/* West Africa */
    { "at",	tZONE,     HOURN( 2) },	/* Azores */
#if	0
    /* For completeness.  BST is also British Summer, and GST is
     * also Guam Standard. */
    { "bst",	tZONE,     HOURN( 3) },	/* Brazil Standard */
    { "gst",	tZONE,     HOURN( 3) },	/* Greenland Standard */
#endif
    { "nft",	tZONE,     HOURN(3.5) },	/* Newfoundland */
    { "nst",	tZONE,     HOURN(3.5) },	/* Newfoundland Standard */
    { "ndt",	tDAYZONE,  HOURN(3.5) },	/* Newfoundland Daylight */
    { "ast",	tZONE,     HOURN( 4) },	/* Atlantic Standard */
    { "adt",	tDAYZONE,  HOURN( 4) },	/* Atlantic Daylight */
    { "est",	tZONE,     HOURN( 5) },	/* Eastern Standard */
    { "edt",	tDAYZONE,  HOURN( 5) },	/* Eastern Daylight */
    { "cst",	tZONE,     HOURN( 6) },	/* Central Standard */
    { "cdt",	tDAYZONE,  HOURN( 6) },	/* Central Daylight */
    { "mst",	tZONE,     HOURN( 7) },	/* Mountain Standard */
    { "mdt",	tDAYZONE,  HOURN( 7) },	/* Mountain Daylight */
    { "pst",	tZONE,     HOURN( 8) },	/* Pacific Standard */
    { "pdt",	tDAYZONE,  HOURN( 8) },	/* Pacific Daylight */
    { "yst",	tZONE,     HOURN( 9) },	/* Yukon Standard */
    { "ydt",	tDAYZONE,  HOURN( 9) },	/* Yukon Daylight */
    { "hst",	tZONE,     HOURN(10) },	/* Hawaii Standard */
    { "hdt",	tDAYZONE,  HOURN(10) },	/* Hawaii Daylight */
    { "cat",	tZONE,     HOURN(10) },	/* Central Alaska */
    { "ahst",	tZONE,     HOURN(10) },	/* Alaska-Hawaii Standard */
    { "nt",	tZONE,     HOURN(11) },	/* Nome */
    { "idlw",	tZONE,     HOURN(12) },	/* International Date Line West */
    { "cet",	tZONE,     -HOURN(1) },	/* Central European */
    { "met",	tZONE,     -HOURN(1) },	/* Middle European */
    { "mewt",	tZONE,     -HOURN(1) },	/* Middle European Winter */
    { "mest",	tDAYZONE,  -HOURN(1) },	/* Middle European Summer */
    { "swt",	tZONE,     -HOURN(1) },	/* Swedish Winter */
    { "sst",	tDAYZONE,  -HOURN(1) },	/* Swedish Summer */
    { "fwt",	tZONE,     -HOURN(1) },	/* French Winter */
    { "fst",	tDAYZONE,  -HOURN(1) },	/* French Summer */
    { "eet",	tZONE,     -HOURN(2) },	/* Eastern Europe, USSR Zone 1 */
    { "bt",	tZONE,     -HOURN(3) },	/* Baghdad, USSR Zone 2 */
    { "it",	tZONE,     -HOURN(3.5) },/* Iran */
    { "zp4",	tZONE,     -HOURN(4) },	/* USSR Zone 3 */
    { "zp5",	tZONE,     -HOURN(5) },	/* USSR Zone 4 */
    { "ist",	tZONE,     -HOURN(5.5) },/* Indian Standard */
    { "zp6",	tZONE,     -HOURN(6) },	/* USSR Zone 5 */
#if	0
    /* For completeness.  NST is also Newfoundland Stanard, nad SST is
     * also Swedish Summer. */
    { "nst",	tZONE,     -HOURN(6.5) },/* North Sumatra */
    { "sst",	tZONE,     -HOURN(7) },	/* South Sumatra, USSR Zone 6 */
#endif	/* 0 */
    { "wast",	tZONE,     -HOURN(7) },	/* West Australian Standard */
    { "wadt",	tDAYZONE,  -HOURN(7) },	/* West Australian Daylight */
    { "jt",	tZONE,     -HOURN(7.5) },/* Java (3pm in Cronusland!) */
    { "cct",	tZONE,     -HOURN(8) },	/* China Coast, USSR Zone 7 */
    { "jst",	tZONE,     -HOURN(9) },	/* Japan Standard, USSR Zone 8 */
    { "cast",	tZONE,     -HOURN(9.5) },/* Central Australian Standard */
    { "cadt",	tDAYZONE,  -HOURN(9.5) },/* Central Australian Daylight */
    { "east",	tZONE,     -HOURN(10) },	/* Eastern Australian Standard */
    { "eadt",	tDAYZONE,  -HOURN(10) },	/* Eastern Australian Daylight */
    { "gst",	tZONE,     -HOURN(10) },	/* Guam Standard, USSR Zone 9 */
    { "nzt",	tZONE,     -HOURN(12) },	/* New Zealand */
    { "nzst",	tZONE,     -HOURN(12) },	/* New Zealand Standard */
    { "nzdt",	tDAYZONE,  -HOURN(12) },	/* New Zealand Daylight */
    { "idle",	tZONE,     -HOURN(12) },	/* International Date Line East */
    {  NULL  }
};

/* Military timezone table. */
static TABLE	MilitaryTable[] = {
    { "a",	tZONE,	HOURN(  1) },
    { "b",	tZONE,	HOURN(  2) },
    { "c",	tZONE,	HOURN(  3) },
    { "d",	tZONE,	HOURN(  4) },
    { "e",	tZONE,	HOURN(  5) },
    { "f",	tZONE,	HOURN(  6) },
    { "g",	tZONE,	HOURN(  7) },
    { "h",	tZONE,	HOURN(  8) },
    { "i",	tZONE,	HOURN(  9) },
    { "k",	tZONE,	HOURN( 10) },
    { "l",	tZONE,	HOURN( 11) },
    { "m",	tZONE,	HOURN( 12) },
    { "n",	tZONE,	HOURN(- 1) },
    { "o",	tZONE,	HOURN(- 2) },
    { "p",	tZONE,	HOURN(- 3) },
    { "q",	tZONE,	HOURN(- 4) },
    { "r",	tZONE,	HOURN(- 5) },
    { "s",	tZONE,	HOURN(- 6) },
    { "t",	tZONE,	HOURN(- 7) },
    { "u",	tZONE,	HOURN(- 8) },
    { "v",	tZONE,	HOURN(- 9) },
    { "w",	tZONE,	HOURN(-10) },
    { "x",	tZONE,	HOURN(-11) },
    { "y",	tZONE,	HOURN(-12) },
    { "z",	tZONE,	HOURN(  0) },
    { NULL }
};




static int
yyerror(const char *s __unused)
{
	return (0);
}


static time_t
ToSeconds(Hours, Minutes, Seconds, Meridian)
    time_t	Hours;
    time_t	Minutes;
    time_t	Seconds;
    MERIDIAN	Meridian;
{
    if (Minutes < 0 || Minutes > 59 || Seconds < 0 || Seconds > 59)
	return -1;
    switch (Meridian) {
    case MER24:
	if (Hours < 0 || Hours > 23)
	    return -1;
	return (Hours * 60L + Minutes) * 60L + Seconds;
    case MERam:
	if (Hours < 1 || Hours > 12)
	    return -1;
	if (Hours != 12)
	    return (Hours * 60L + Minutes) * 60L + Seconds;
	else
	    return Minutes * 60L + Seconds;
    case MERpm:
	if (Hours < 1 || Hours > 12)
	    return -1;
	if (Hours != 12)
	    return ((Hours + 12) * 60L + Minutes) * 60L + Seconds;
	else
	    return (720L + Minutes) * 60L + Seconds;
    }
    /* NOTREACHED */
    return (-1);
}


static time_t
Convert(Month, Day, Year, Hours, Minutes, Seconds, Meridian, DSTmode)
    time_t	Month;
    time_t	Day;
    time_t	Year;
    time_t	Hours;
    time_t	Minutes;
    time_t	Seconds;
    MERIDIAN	Meridian;
    DSTMODE	DSTmode;
{
    static int	DaysInMonth[12] = {
	31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };
    time_t	tod;
    time_t	Julian;
    time_t	i;

    if (Year < 0)
	Year = -Year;
    if (Year < 138)
	Year += 1900;
    DaysInMonth[1] = Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0)
		    ? 29 : 28;
    if (Year < EPOCH || Year > 2037
     || Month < 1 || Month > 12
     /* LINTED Month is a time_t so intermediate results aren't truncated */
     || Day < 1 || Day > DaysInMonth[(int)--Month])
	return -1;

    for (Julian = Day - 1, i = 0; i < Month; i++)
	Julian += DaysInMonth[i];
    for (i = EPOCH; i < Year; i++)
	Julian += 365 + (i % 4 == 0);
    Julian *= SECSPERDAY;
    Julian += yyTimezone * 60L;
    if ((tod = ToSeconds(Hours, Minutes, Seconds, Meridian)) < 0)
	return -1;
    Julian += tod;
    if (DSTmode == DSTon
     || (DSTmode == DSTmaybe && localtime(&Julian)->tm_isdst))
	Julian -= 60 * 60;
    return Julian;
}


static time_t
DSTcorrect(Start, Future)
    time_t	Start;
    time_t	Future;
{
    time_t	StartDay;
    time_t	FutureDay;

    StartDay = (localtime(&Start)->tm_hour + 1) % 24;
    FutureDay = (localtime(&Future)->tm_hour + 1) % 24;
    return (Future - Start) + (StartDay - FutureDay) * 60L * 60L;
}


static time_t
RelativeDate(Start, DayOrdinal, DayNumber)
    time_t	Start;
    time_t	DayOrdinal;
    time_t	DayNumber;
{
    struct tm	*tm;
    time_t	now;

    now = Start;
    tm = localtime(&now);
    now += SECSPERDAY * ((DayNumber - tm->tm_wday + 7) % 7);
    now += 7 * SECSPERDAY * (DayOrdinal <= 0 ? DayOrdinal : DayOrdinal - 1);
    return DSTcorrect(Start, now);
}


static time_t
RelativeMonth(Start, RelMonth)
    time_t	Start;
    time_t	RelMonth;
{
    struct tm	*tm;
    time_t	Month;
    time_t	Year;

    if (RelMonth == 0)
	return 0;
    tm = localtime(&Start);
    Month = 12 * tm->tm_year + tm->tm_mon + RelMonth;
    Year = Month / 12;
    Month = Month % 12 + 1;
    return DSTcorrect(Start,
	    Convert(Month, (time_t)tm->tm_mday, Year,
		(time_t)tm->tm_hour, (time_t)tm->tm_min, (time_t)tm->tm_sec,
		MER24, DSTmaybe));
}


static int
LookupWord(buff)
    char		*buff;
{
    char	*p;
    char	*q;
    TABLE	*tp;
    uint_t	i;
    int		abbrev;

    /* Make it lowercase. */
    for (p = buff; *p; p++)
	if (isupper((u_char)*p))
	    *p = tolower(*p);

    if (strcmp(buff, "am") == 0 || strcmp(buff, "a.m.") == 0) {
	yylval.Meridian = MERam;
	return tMERIDIAN;
    }
    if (strcmp(buff, "pm") == 0 || strcmp(buff, "p.m.") == 0) {
	yylval.Meridian = MERpm;
	return tMERIDIAN;
    }

    /* See if we have an abbreviation for a month. */
    if (strlen(buff) == 3)
	abbrev = 1;
    else if (strlen(buff) == 4 && buff[3] == '.') {
	abbrev = 1;
	buff[3] = '\0';
    }
    else
	abbrev = 0;

    for (tp = MonthDayTable; tp->name; tp++) {
	if (abbrev) {
	    if (strncmp(buff, tp->name, 3) == 0) {
		yylval.Number = tp->value;
		return tp->type;
	    }
	}
	else if (strcmp(buff, tp->name) == 0) {
	    yylval.Number = tp->value;
	    return tp->type;
	}
    }

    for (tp = TimezoneTable; tp->name; tp++)
	if (strcmp(buff, tp->name) == 0) {
	    yylval.Number = tp->value;
	    return tp->type;
	}

    for (tp = UnitsTable; tp->name; tp++)
	if (strcmp(buff, tp->name) == 0) {
	    yylval.Number = tp->value;
	    return tp->type;
	}

    /* Strip off any plural and try the units table again. */
    i = strlen(buff) - 1;
    if (buff[i] == 's') {
	buff[i] = '\0';
	for (tp = UnitsTable; tp->name; tp++)
	    if (strcmp(buff, tp->name) == 0) {
		yylval.Number = tp->value;
		return tp->type;
	    }
    }

    for (tp = OtherTable; tp->name; tp++)
	if (strcmp(buff, tp->name) == 0) {
	    yylval.Number = tp->value;
	    return tp->type;
	}

    /* Military timezones. */
    if (buff[1] == '\0' && isalpha((u_char)*buff)) {
	for (tp = MilitaryTable; tp->name; tp++)
	    if (strcmp(buff, tp->name) == 0) {
		yylval.Number = tp->value;
		return tp->type;
	    }
    }

    /* Drop out any periods and try the timezone table again. */
    for (i = 0, p = q = buff; *q; q++)
	if (*q != '.')
	    *p++ = *q;
	else
	    i++;
    *p = '\0';
    if (i)
	for (tp = TimezoneTable; tp->name; tp++)
	    if (strcmp(buff, tp->name) == 0) {
		yylval.Number = tp->value;
		return tp->type;
	    }

    return tID;
}

void
pdateerr(p)
    char	*p;
{
    char	*name = "DATEMSK";	/* env variable for date format */
    char	*value;
    char	fmt[256], line[256];
    FILE	*fp;
    time_t	now;
    struct tm	*tm;

    value = getenv(name);
    if (value == (char *)0) {
	fprintf(stderr,
	    dgettext(domainname, "%s: Environment variable %s not set\n"),
		p, name);
	return;
    }
    switch (getdate_err) {
	case 0:
	default:
	    fprintf(stderr,
		dgettext(domainname, "%s: Unkown getdate() error\n"), p);
	    break;
	case 1:
	    fprintf(stderr,
		dgettext(domainname, "%s: %s null or undefined\n"), p, name);
	    break;
	case 2:
	    fprintf(stderr, dgettext(domainname,
		"%s: Cannot read template file %s\n"), p, value);
	    break;
	case 3:
	    fprintf(stderr, dgettext(domainname,
		"%s: Failed to get file status information\n"), p);
	    break;
	case 4:
	    fprintf(stderr, dgettext(domainname,
		"%s: Template file %s not a regular file\n"), p, value);
	    break;
	case 5:
	    fprintf(stderr, dgettext(domainname,
		"%s: Error reading template file %s\n"), p, value);
	    break;
	case 6:
	    fprintf(stderr, dgettext(domainname,
		"%s: %s failed\n"), p, "malloc()");
	    break;
	case 7:
	    fprintf(stderr, dgettext(domainname,
		"%s: Bad date/time format\n"), p);
	    fp = fopen(value, "r");
	    if (fp == (FILE *)0)
		break;
	    now = time((time_t *)0);
	    tm = localtime(&now);
	    fprintf(stderr, dgettext(domainname,
		"The following are examples of valid formats:\n"));
	    while (fgets(fmt, sizeof (fmt), fp)) {
		if (strchr(fmt, '%') == (char *)0)
		    continue;
		fprintf(stderr, "    ");
	        (void) strftime(line, sizeof (line), fmt, tm);
		fprintf(stderr, "%s", line);
	    }
	    (void) fclose(fp);
	    break;
	case 8:
	    (void) fprintf(stderr, dgettext(domainname,
		"%s: Invalid date specification\n"), p);
	    break;
    }
}

#undef yylex
static int
yylex()
{
    char	c;
    char	*p;
    char	buff[20];
    int		Count;
    int		sign;

    for ( ; ; ) {
	while (isspace((u_char)*yyInput))
	    yyInput++;

	if (isdigit((u_char)(c = *yyInput)) || c == '-' || c == '+') {
	    if (c == '-' || c == '+') {
		sign = c == '-' ? -1 : 1;
		if (!isdigit((u_char)*++yyInput))
		    /* skip the '-' sign */
		    continue;
	    }
	    else
		sign = 0;
	    yylval.Number = 0;
	    while (isdigit((u_char)(c = *yyInput++))) {
		int n;
		char digit = c;
		(void) sscanf(&digit, "%1d", &n);
		yylval.Number = 10 * yylval.Number + n;
	    }
	    yyInput--;
	    if (sign < 0)
		yylval.Number = -yylval.Number;
	    return sign ? tSNUMBER : tUNUMBER;
	}
	if (isalpha((u_char)c)) {
	    for (p = buff; isalpha((u_char)(c = *yyInput++)) || c == '.'; )
		if (p < &buff[sizeof (buff) - 1])
		    *p++ = c;
	    *p = '\0';
	    yyInput--;
	    return LookupWord(buff);
	}
	if (c != '(')
	    return *yyInput++;
	Count = 0;
	do {
	    c = *yyInput++;
	    if (c == '\0')
		return c;
	    if (c == '(')
		Count++;
	    else if (c == ')')
		Count--;
	} while (Count > 0);
    }
}


time_t
getreldate(p, now)
    char		*p;
    struct timeb	*now;
{
    struct tm		*tm;
    struct timeb	ftz;
    time_t		Start;
    time_t		tod;

    if (strcmp(setlocale(LC_TIME, NULL), "C")) {
	static char localedate[24];
	struct tm ltm;

	tm = getdate(p);
	if (getdate_err == 1 /* NODATEMASK */) {
	    char buffy[BUFSIZ];
	    time_t current;

	    printf(gettext("environment variable %s not set\n"), "DATEMSK");
	    do {
		time(&current);
		tm = localtime(&current);
		memcpy(&ltm, tm, sizeof(ltm));
		tm = &ltm;

		(void) fputs(gettext("Enter date as mmddhhmm[yy]: "), stdout);
		(void) fflush(stdout);
		if (fgets(buffy, sizeof (buffy), stdin) == NULL) {
			(void) printf(gettext("Encountered EOF on stdin\n"));
			return(-1);
		}
	    } while (sscanf(buffy, "%2d%2d%2d%2d%2d",
		&(tm->tm_mon), &(tm->tm_mday), &(tm->tm_hour),
		&(tm->tm_min), &(tm->tm_year)) < 4);

	    (tm->tm_mon)--;
	} else if (tm == NULL)
	    return(-1);

	(void)sprintf(localedate, "%d:%2.2d %d/%d %d",
	    tm->tm_hour, tm->tm_min, tm->tm_mon + 1,
	    tm->tm_mday, CHECK_TM(tm->tm_year));
	p = localedate;
    }

    yyInput = p;
    if (now == NULL) {
	now = &ftz;
	(void) time(&ftz.time);
	/* Set the timezone global. */
	tzset();
	/* LINTED timezone is time_t so intermediate results aren't truncated */
	ftz.timezone = (int) timezone / 60;
    }

    tm = localtime(&now->time);
    yyYear = tm->tm_year;
    yyMonth = tm->tm_mon + 1;
    yyDay = tm->tm_mday;
    yyTimezone = now->timezone;
    yyDSTmode = DSTmaybe;
    yyHour = tm->tm_hour;
    yyMinutes = tm->tm_min;
    yySeconds = tm->tm_sec;
    yyMeridian = MER24;
    yyRelSeconds = 0;
    yyRelMonth = 0;
    yyHaveDate = 0;
    yyHaveDay = 0;
    yyHaveRel = 0;
    yyHaveTime = 0;
    yyHaveZone = 0;

    if (yyparse()
     || yyHaveTime > 1 || yyHaveZone > 1 || yyHaveDate > 1 || yyHaveDay > 1)
	return -1;

    if (yyHaveDate || yyHaveTime || yyHaveDay) {
	Start = Convert(yyMonth, yyDay, yyYear, yyHour, yyMinutes, yySeconds,
		    yyMeridian, yyDSTmode);
	if (Start < 0)
	    return -1;
    }
    else {
	Start = now->time;
	if (!yyHaveRel)
	    Start -= ((tm->tm_hour * 60L) + tm->tm_min * 60L) + tm->tm_sec;
    }

    Start += yyRelSeconds;
    Start += RelativeMonth(Start, yyRelMonth);

    if (yyHaveDay && !yyHaveDate) {
	tod = RelativeDate(Start, yyDayOrdinal, yyDayNumber);
	Start += tod;
    }

    /* Have to do *something* with a legitimate -1 so it's distinguishable
     * from the error return value.  (Alternately could set errno on error.) */
    return Start == -1 ? 0 : Start;
}

#if	defined(TEST)

/* ARGSUSED */
main(ac, av)
    int		ac;
    char	*av[];
{
    char	buff[128];
    time_t	d;

    (void) setlocale(LC_ALL, "");
#if !defined(TEXT_DOMAIN)
#define	TEXT_DOMAIN "SYS_TEST"
#endif
    (void) textdomain(TEXT_DOMAIN);

    (void) printf(gettext("Enter date, or blank line to exit.\n\t> "));
    (void) fflush(stdout);
    while (gets(buff) && buff[0]) {
	d = getreldate(buff, (struct timeb *)NULL);
	if (d == -1)
	    (void) printf(gettext("Bad format - couldn't convert.\n"));
	else {
	    (void) cftime(buff, "%c\n", &d);
	    (void) printf("%s", buff);
	}
	(void) printf("\t> ");
	(void) fflush(stdout);
    }
    exit(0);
    /* NOTREACHED */
}
#endif	/* defined(TEST) */
/^"operator_xdr.c.*variable unused in function/d
/yaccpar/d
/getdate.y.*include file.*unnecessary/d
/different definitions.*CLK_TCK/d
/lint suppression directive not used/d
/no corresponding .h file/d
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1998 by Sun Microsystems, Inc.
 * All rights reserved.
 */

#include <stdlib.h>
#include <errno.h>
#include <libintl.h>
#include <string.h>
#include "memutils.h"

extern void msg(const char *, ...);
extern void dumpabort(void);

void *
xmalloc(bytes)
	size_t bytes;
{
	void *cp;

	cp = malloc(bytes);
	if (cp == NULL) {
		int saverr = errno;
		msg(gettext("Cannot allocate memory: %s\n"), strerror(saverr));
		dumpabort();
	}
	return (cp);
}

void *
xcalloc(nelem, size)
	size_t nelem;
	size_t size;
{
	void *cp;

	cp = calloc(nelem, size);
	if (cp == NULL) {
		int saverr = errno;
		msg(gettext("Cannot allocate memory: %s\n"), strerror(saverr));
		dumpabort();
	}
	return (cp);
}

void *
xrealloc(allocated, newsize)
	void *allocated;
	size_t newsize;
{
	void *cp;

	/* LINTED realloc knows what to do with a NULL pointer */
	cp = realloc(allocated, newsize);
	if (cp == NULL) {
		int saverr = errno;
		msg(gettext("Cannot allocate memory: %s\n"), strerror(saverr));
		dumpabort();
	}
	return (cp);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 1999 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T	*/
/*	  All Rights Reserved  	*/

/*
 * Portions of this source code were derived from Berkeley 4.3 BSD
 * under license from the Regents of the University of California.
 */

#include <myrcmd.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <pwd.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/file.h>
#include <signal.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <netdb.h>
#include <fcntl.h>
#include <libintl.h>

#include <memutils.h>

#define	index(s, c)		strchr(s, c)
char	*strchr();

char	*inet_ntoa();

char myrcmd_stderr[1024];

int
myrcmd(char **ahost, unsigned short rport, char *locuser, char *remuser,
    char *cmd)
{
	uint_t loclen, remlen, cmdlen;
	int s, timo, retval;
	int tries = 0;
	pid_t pid;
	struct sockaddr_in sin;
	char c;
	int lport;
	int saverr;
	struct hostent *hp;
	sigset_t oldmask;
	sigset_t newmask;
	struct sigaction oldaction;
	struct sigaction newaction;
	static struct hostent numhp;
	static char numhostname[32];	/* big enough for "255.255.255.255" */
	struct in_addr numaddr;
	struct in_addr *numaddrlist[2];

	myrcmd_stderr[0] = '\0';	/* empty error string */
	pid = getpid();
	hp = gethostbyname(*ahost);
	if (hp == 0) {
		char *straddr;

		bzero((char *)numaddrlist, sizeof (numaddrlist));
		if ((numaddr.s_addr = inet_addr(*ahost)) == (in_addr_t)-1) {
			(void) snprintf(myrcmd_stderr, sizeof (myrcmd_stderr),
			    gettext("%s: unknown host\n"), *ahost);
			return (MYRCMD_NOHOST);
		} else {
			bzero((char *)&numhp, sizeof (numhp));
			bzero(numhostname, sizeof (numhostname));

			if ((straddr = inet_ntoa(numaddr)) == (char *)0) {
				(void) snprintf(myrcmd_stderr,
				    sizeof (myrcmd_stderr),
				    gettext("%s: unknown host\n"), *ahost);
				return (MYRCMD_NOHOST);
			}
			(void) strncpy(numhostname, straddr,
			    sizeof (numhostname));
			numhostname[sizeof (numhostname) - 1] = '\0';
			numhp.h_name = numhostname;
			numhp.h_addrtype = AF_INET;
			numhp.h_length = sizeof (numaddr);
			numaddrlist[0] = &numaddr;
			numaddrlist[1] = NULL;
			numhp.h_addr_list = (char **)numaddrlist;
			hp = &numhp;
		}
	}
	*ahost = hp->h_name;

	/* This provides a bounds-test for the bcopy()s below. */
	if ((unsigned)(hp->h_length) > sizeof (sin.sin_addr)) {
		(void) snprintf(myrcmd_stderr, sizeof (myrcmd_stderr),
		    gettext("rcmd: address size: %d larger than limit %d\n"),
		    hp->h_length, sizeof (sin.sin_addr));
		return (MYRCMD_EBAD);
	}

	/* ignore SIGPIPE */
	bzero((char *)&newaction, sizeof (newaction));
	newaction.sa_handler = SIG_IGN;
	newaction.sa_flags = SA_ONSTACK;
	(void) sigaction(SIGPIPE, &newaction, &oldaction);

	/* block SIGURG */
	bzero((char *)&newmask, sizeof (newmask));
	(void) sigaddset(&newmask, SIGURG);
	(void) sigprocmask(SIG_BLOCK, &newmask, &oldmask);
again:
	timo = 1;
	/*
	 * Use 0 as lport means that rresvport() will bind to a port in
	 * the anonymous priviledged port range.
	 */
	lport = 0;
	for (;;) {
		s = rresvport(&lport);
		if (s < 0) {
			int err;

			if (errno == EAGAIN) {
				(void) snprintf(myrcmd_stderr,
				    sizeof (myrcmd_stderr),
				    gettext("socket: All ports in use\n"));
				err = MYRCMD_ENOPORT;
			} else {
				saverr = errno;
				(void) snprintf(myrcmd_stderr,
				    sizeof (myrcmd_stderr),
				    gettext("rcmd: socket: %s\n"),
				    strerror(saverr));
				err = MYRCMD_ENOSOCK;
			}
			/* restore original SIGPIPE handler */
			(void) sigaction(SIGPIPE, &oldaction,
			    (struct sigaction *)0);

			/* restore original signal mask */
			(void) sigprocmask(SIG_SETMASK, &oldmask,
			    (sigset_t *)0);
			return (err);
		}
		/* Can't fail, according to fcntl(2) */
		(void) fcntl(s, F_SETOWN, pid);
		sin.sin_family = hp->h_addrtype;
		bcopy(hp->h_addr_list[0], (caddr_t)&sin.sin_addr, hp->h_length);
		sin.sin_port = rport;
		if (connect(s, (struct sockaddr *)&sin, sizeof (sin)) >= 0)
			break;
		saverr = errno;
		(void) close(s);
		if (saverr == EADDRINUSE) {
			continue;
		}
		if (saverr == ECONNREFUSED && timo <= 16) {
			sleep(timo);
			timo *= 2;
			continue;
		}
		if (hp->h_addr_list[1] != NULL) {
			saverr = errno;

			fprintf(stderr,
			    gettext("connect to address %s: "),
			    inet_ntoa(sin.sin_addr));
			errno = saverr;
			perror(0);
			hp->h_addr_list++;
			bcopy(hp->h_addr_list[0], (caddr_t)&sin.sin_addr,
			    hp->h_length);
			fprintf(stderr, gettext("Trying %s...\n"),
				inet_ntoa(sin.sin_addr));
			continue;
		}
		(void) snprintf(myrcmd_stderr, sizeof (myrcmd_stderr),
		    "%s: %s\n", hp->h_name, strerror(saverr));
		/* restore original SIGPIPE handler */
		(void) sigaction(SIGPIPE, &oldaction,
		    (struct sigaction *)0);

		/* restore original signal mask */
		(void) sigprocmask(SIG_SETMASK, &oldmask, (sigset_t *)0);
		return (MYRCMD_ENOCONNECT);
	}
	if (write(s, "", 1) < 0) {
		(void) close(s);
		return (MYRCMD_ENOCONNECT);
	}

	loclen = strlen(locuser) + 1;
	remlen = strlen(remuser) + 1;
	cmdlen = strlen(cmd) + 1;

	if (((retval = write(s, locuser, loclen)) != loclen) ||
	    ((retval = write(s, remuser, remlen)) != remlen) ||
	    ((retval = write(s, cmd, cmdlen)) != cmdlen)) {
		if (retval == -1)
			(void) snprintf(myrcmd_stderr, sizeof (myrcmd_stderr),
			    "write: %s\n", strerror(errno));
		else
			(void) snprintf(myrcmd_stderr, sizeof (myrcmd_stderr),
			    gettext("write unexpectedly truncated\n"));
		goto bad;
	}
	retval = read(s, &c, 1);
	if (retval != 1) {
		if (retval == 0) {
			/*
			 * Solaris 2.0 bug alert.  Sometimes, if the
			 * tapehost is a Solaris 2.0 system, the connection
			 * will be dropped at this point.  Let's try again,
			 * three times, before we throw in the towel.
			 */
			if (++tries < 3) {
				(void) close(s);
				goto again;
			}
			(void) snprintf(myrcmd_stderr, sizeof (myrcmd_stderr),
			    gettext("Protocol error, %s closed connection\n"),
			    *ahost);
		} else if (retval < 0) {
			(void) snprintf(myrcmd_stderr, sizeof (myrcmd_stderr),
			    "%s: %s\n", *ahost, strerror(errno));
		} else {
			(void) snprintf(myrcmd_stderr, sizeof (myrcmd_stderr),
			    gettext("Protocol error, %s sent %d bytes\n"),
			    *ahost, retval);
		}
		goto bad;
	}
	if (c != 0) {
		char *cp = myrcmd_stderr;
		char *ecp = &myrcmd_stderr[sizeof (myrcmd_stderr) - 1];

		while (read(s, &c, 1) == 1) {
			*cp++ = c;
			if (c == '\n' || cp >= ecp)
				break;
		}
		*cp = '\0';
		goto bad;
	}
	/* restore original SIGPIPE handler */
	(void) sigaction(SIGPIPE, &oldaction, (struct sigaction *)0);

	/* restore original signal mask */
	(void) sigprocmask(SIG_SETMASK, &oldmask, (sigset_t *)0);
	return (s);
bad:
	(void) close(s);
	/* restore original SIGPIPE handler */
	(void) sigaction(SIGPIPE, &oldaction, (struct sigaction *)0);

	/* restore original signal mask */
	(void) sigprocmask(SIG_SETMASK, &oldmask, (sigset_t *)0);
	return (MYRCMD_EBAD);
}
/*LINTLIBRARY*/
/*PROTOLIB1*/
/*
 * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */
/*
 * Copyright (c) 1980 Regents of the University of California.
 * All rights reserved.  The Berkeley software License Agreement
 * specifies the terms and conditions for redistribution.
 */

#include <myrcmd.h>
#include <stdio.h>
#include <locale.h>
#include <ctype.h>
#include <pwd.h>
#include <string.h>
#include <signal.h>
#include <sys/mtio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <locale.h>
#include <stdlib.h>
#include <errno.h>
#include <rmt.h>
#include <libintl.h>

#define	sigvec		sigaction
#define	sv_handler	sa_handler

#include <netinet/in.h>

extern	int32_t	tp_bsize;

#define	TS_CLOSED	0
#define	TS_OPEN		1

static int	rmtstate = TS_CLOSED;
static int	rmtape = -1;
static int	rmtversion = 0;
static char	*rmtpeer, *rmtpeer_malloc;
static uint_t	ntrec;			/* blocking factor on tape */

static char *domainname = "hsm_libdump";	/* for dgettext() */

#ifdef __STDC__
static void rmtmsg(const char *, ...);	/* package print routine */
static void rmtconnaborted(int);
static void rmtgetconn(void);
static int rmtstatus_extended(struct mtget *);
static int rmtioctl_extended(int, long);
static int map_extended_ioctl(int);
static int okname(char *);
static int rmtcall(char *, char *);
static int rmtreply(char *);
static int rmtpush(char *, uint_t);
static void rmtgets(char *, int);

static void (*print)(const char *, ...);	/* print routine */
static void (*Exit)(int);			/* exit routine */
#else
static void rmtmsg();
static void rmtconnaborted();
static void rmtgetconn();
static int okname();
static int rmtstatus_extended();
static int rmtioctl_extended();
static int map_extended_ioctl();
static int rmtcall();
static int rmtreply();
static int rmtpush();
static void rmtgets();

static void (*print)();
static void (*Exit)();
#endif

/*
 * Get a program-specific print and exit routine into
 * the package.  This is primarily for dump's benefit.
 * This routine is optional -- if not called the two
 * default to fprintf(stderr) and exit.
 */
#ifdef __STDC__
void
rmtinit(
	void (*errmsg)(const char *, ...),	/* print routine */
	void (*errexit)(int))			/* exit routine */
#else
void
rmtinit(void (*errmsg)(), void (*errexit)())
#endif
{
	print = errmsg;
	Exit = errexit;
}

int
rmthost(char *host, uint_t blocksize)
{
	struct sigvec sv;

#ifdef __STDC__
	if (print == (void (*)(const char *, ...))0)
#else
	if (print == (void (*)())0)
#endif
		print = rmtmsg;
#ifdef __STDC__
	if (Exit == (void (*)(int))0)
#else
	if (Exit == (void (*)())0)
#endif
		Exit = exit;
	if (rmtape >= 0 && rmtstate != TS_OPEN) {
		(void) close(rmtape);
		rmtape = -1;
	}
	if (rmtpeer_malloc)
		(void) free(rmtpeer_malloc);
	rmtpeer = rmtpeer_malloc = strdup(host);
	if (rmtpeer == (char *)0)
		return (0);
	ntrec = blocksize;
	sv.sa_flags = SA_RESTART;
	(void) sigemptyset(&sv.sa_mask);
	sv.sv_handler = rmtconnaborted;
	(void) sigvec(SIGPIPE, &sv, (struct sigvec *)0);
	rmtgetconn();
	if (rmtape < 0)
		return (0);
	return (1);
}

/*ARGSUSED*/
static void
rmtconnaborted(int sig)
{
	print(dgettext(domainname, "Lost connection to remote host.\n"));
	Exit(1);
}

static void
#ifdef __STDC__
rmtgetconn(void)
#else
rmtgetconn()
#endif
{
	static struct servent *sp = 0;
	static struct passwd *pwd = 0;
	char *tuser, *host, *device;
	uint_t size;

	if (sp == 0) {
		sp = getservbyname("shell", "tcp");
		if (sp == 0) {
			print(dgettext(domainname,
				"shell/tcp: unknown service\n"));
			Exit(1);
		}
		pwd = getpwuid(getuid());
		if (pwd == 0) {
			print(dgettext(domainname,
				"Cannot find password entry for uid %d\n"),
				getuid());
			Exit(1);
		}
	}
	/* Was strrchr(), be consistent with dump */
	host = strchr(rmtpeer, '@');
	if (host) {
		tuser = rmtpeer;
		*host++ = 0;
		rmtpeer = host;
		if (!okname(tuser))
			Exit(1);
	} else {
		host = rmtpeer;
		tuser = pwd->pw_name;
	}
	/* Was strrchr() - be consistent with dump and restore */
	device = strchr(host, ':');
	if (device)
		*device = 0;	/* throw away device name */
	/*
	 * myrcmd() replaces the contents of rmtpeer with a pointer
	 * to a static copy of the canonical host name.  However,
	 * since we never refer to rmtpeer again (other than to
	 * overwrite it in the next rmthost() invocation), we don't
	 * really care.
	 */
	/* LINTED sp->s_port is an int, even though port numbers are 1..65535 */
	rmtape = myrcmd(&rmtpeer, (ushort_t)sp->s_port, pwd->pw_name,
			tuser, "/etc/rmt");
	if (rmtape < 0) {
		if (*myrcmd_stderr)
			print("%s", myrcmd_stderr);
	} else {
		size = ntrec * tp_bsize;
		while (size > tp_bsize &&
		    setsockopt(rmtape, SOL_SOCKET, SO_SNDBUF, (char *)&size,
		    sizeof (size)) < 0)
			size -= tp_bsize;
	}
}

static int
okname(char *cp0)
{
	char *cp;
	uchar_t c;

	for (cp = cp0; *cp; cp++) {
		c = (uchar_t)*cp;
		if (!isascii(c) || !(isalnum(c) || c == '_' || c == '-')) {
			print(dgettext(domainname,
				"invalid user name %s\n"), cp0);
			return (0);
		}
	}
	return (1);
}

int
rmtopen(char *tape, int mode)
{
	struct mtget mt;
	char buf[256];
	int fd;

	(void) snprintf(buf, sizeof (buf), "O%s\n%d\n", tape, mode);
	rmtstate = TS_OPEN;
	fd = rmtcall(tape, buf);
	if (fd != -1) {
		/* see if the rmt server supports the extended protocol */
		rmtversion = rmtioctl(-1, 0);

		/*
		 * Some rmt daemons apparently close the connection
		 * when they get a bogus ioctl.  See 1210852 (ignore
		 * the evaluation).  Make sure we can still talk to
		 * the device, re-opening it if necessary.
		 */
		if (rmtversion < 1) {
			if (rmtstatus(&mt) < 0) {
				rmtclose();
				rmtgetconn();
				rmtversion = 0;
			}
		}
	}
	return (fd);
}

void
#ifdef __STDC__
rmtclose(void)
#else
rmtclose()
#endif
{
	if (rmtstate != TS_OPEN)
		return;
	(void) rmtcall("close", "C\n");
	rmtstate = TS_CLOSED;
}

int
rmtstatus(struct mtget *mt)
{
	char *buf = (char *)mt;
	int n, i, cc;

	if (rmtversion > 0)
		return (rmtstatus_extended(mt));

	n = rmtcall("status", "S");
	if (n < 0) {
		return (-1);
	}
	if ((unsigned)n > sizeof (*mt)) {
		print(dgettext(domainname,
		    "rmtstatus: expected response size %d, got %d\n"),
		    sizeof (struct mtget), n);
		print(dgettext(domainname,
		    "This means the remote rmt daemon is not compatible.\n"));
		rmtconnaborted(0);
	}
	i = 0;
	while (i < n) {
		cc = read(rmtape, buf+i, n - i);
		if (cc <= 0)
			rmtconnaborted(0);
		i += cc;
	}
	return (n);
}

static int
rmtstatus_extended(struct mtget *mt)
{
	if ((mt->mt_type = rmtcall("status", "sT")) == -1)
		return (-1);
	mt->mt_dsreg = rmtcall("status", "sD");
	mt->mt_erreg = rmtcall("status", "sE");
	mt->mt_resid = rmtcall("status", "sR");
	mt->mt_fileno = rmtcall("status", "sF");
	mt->mt_blkno = rmtcall("status", "sB");
	mt->mt_flags = rmtcall("status", "sf");
	mt->mt_bf = rmtcall("status", "sb");
	return (0);
}

int
rmtread(char *buf, uint_t count)
{
	char line[30];
	int n, i, cc;

	(void) snprintf(line, sizeof (line), "R%d\n", count);
	n = rmtcall("read", line);
	if (n < 0) {
		return (-1);
	}
	if (n > count) {
		print(dgettext(domainname,
		    "rmtread: expected response size %d, got %d\n"),
		    count, n);
		print(dgettext(domainname,
		    "This means the remote rmt daemon is not compatible.\n"));
		rmtconnaborted(0);
	}
	i = 0;
	while (i < n) {
		cc = read(rmtape, buf+i, n - i);
		if (cc <= 0)
			rmtconnaborted(0);
		i += cc;
	}
	return (n);
}

int
rmtwrite(char *buf, uint_t count)
{
	int retval;
	char line[64];		/* numbers can get big */

	(void) snprintf(line, sizeof (line), "W%d\n", count);
	retval = rmtpush(line, strlen(line));
	if (retval <= 0)
		return (-1);

	retval = rmtpush(buf, count);
	if (retval <= 0)
		return (-1);

	return (rmtreply("write"));
}

int
rmtpush(char *buf, uint_t count)
{
	int retval;

	do {
		retval = write(rmtape, buf, count);
		buf += retval;
		count -= retval;
	} while (count && retval > 0);

	return (retval);
}

int
rmtseek(int offset, int pos)
{
	char line[80];

	(void) snprintf(line, sizeof (line), "L%d\n%d\n", offset, pos);
	return (rmtcall("seek", line));
}

int
rmtioctl(int cmd, long count)
{
	char buf[256];
	int xcmd;

	if (count < 0)
		return (-1);

	if ((xcmd = map_extended_ioctl(cmd)) != -1)
		return (rmtioctl_extended(xcmd, count));

	(void) snprintf(buf, sizeof (buf), "I%d\n%ld\n", cmd, count);
	return (rmtcall("ioctl", buf));
}

/*
 * Map from the standard Sun ioctl commands into the extended version,
 * if possible.
 */
static int
map_extended_ioctl(int cmd)
{
	int xcmd;

	if (rmtversion <= 0)
		return (-1);		/* extended protocol not supported */

	switch (cmd) {
	case MTRETEN:
		xcmd = 2;
		break;
	case MTERASE:
		xcmd = 3;
		break;
	case MTEOM:
		xcmd = 4;
		break;
	case MTNBSF:
		xcmd = 5;
		break;
	default:
		xcmd = -1;		/* not supported */
		break;
	}
	return (xcmd);
}

static int
rmtioctl_extended(int cmd, long count)
{
	char buf[256];

	(void) snprintf(buf, sizeof (buf), "i%d\n%ld\n", cmd, count);
	return (rmtcall("ioctl", buf));
}

static int
rmtcall(char *cmd, char *buf)
{
	if (rmtpush(buf, strlen(buf)) != strlen(buf))
		rmtconnaborted(0);
	return (rmtreply(cmd));
}

static int
rmtreply(char *cmd)
{
	char code[30], emsg[BUFSIZ];

	rmtgets(code, sizeof (code));
	if (*code == 'E' || *code == 'F') {
		rmtgets(emsg, sizeof (emsg));
		/*
		 * don't print error message for ioctl or status;
		 * or if we are opening up a full path (i.e. device)
		 * and the tape is not loaded (EIO error)
		 */
		if (strcmp(cmd, "ioctl") != 0 &&
		    strcmp(cmd, "status") != 0 &&
		    !(cmd[0] == '/' && atoi(code + 1) == EIO))
			print("%s: %s\n", cmd, emsg);
		errno = atoi(code + 1);
		if (*code == 'F') {
			rmtstate = TS_CLOSED;
			return (-1);
		}
		return (-1);
	}
	if (*code != 'A') {
		print(dgettext(domainname,
			"Protocol to remote tape server botched (code %s?).\n"),
			code);
		rmtconnaborted(0);
	}
	return (atoi(code + 1));
}

static void
rmtgets(char *cp, int len)
{
	int i, n;

	n = recv(rmtape, cp, len-1, MSG_PEEK);
	for (i = 0; i < n; i++)
		if (cp[i] == '\n')
			break;
	n = i + 1;			/* characters to read at once */
	for (i = 0; i < len; i += n, n = 1) {
		n = read(rmtape, cp, n);
		if (n <= 0)
			rmtconnaborted(0);
		cp += n;
		if (cp[-1] == '\n') {
			cp[-1] = '\0';
			return;
		}
	}
	print(dgettext(domainname,
		"Protocol to remote tape server botched (in rmtgets).\n"));
	rmtconnaborted(0);
}

#ifdef __STDC__
#include <stdarg.h>

/* VARARGS1 */
static void
rmtmsg(const char *fmt, ...)
{
	va_list	args;

	va_start(args, fmt);
	(void) vfprintf(stderr, fmt, args);
	(void) fflush(stderr);
}
#else
#include <varargs.h>

/* VARARGS */
static void
rmtmsg(va_dcl)
{
	va_list	args;
	char	*fmt;

	va_start(args);
	fmt = va_arg(args, char *);
	(void) vfprintf(stderr, fmt, args);
	(void) fflush(stderr);
}
#endif